// 能量與軍餉 — 核心列表 / WCA 帳本 / AI 用量
(() => {
const { Panel, Badge, Button, ProgressBar, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const REASON_LABEL = { initial: "初始配發", buy_core: "購買能量核心", reward: "獎勵", adjust: "人工調整" };
const TASK_LABEL = {
  explain: "快速解釋", completeness: "完整度檢查", socratic: "蘇格拉底追問", structure: "結構化整理",
  challenge: "反方挑戰", next_step: "下一步建議", crosscheck: "跨關卡一致性", pitch: "Pitch 組裝",
};

function Energy() {
  const [data, setData] = React.useState(null);
  const load = () => api("/api/energy").then(setData).catch(() => {});
  React.useEffect(load, []);
  if (!data) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>帳本翻閱中…</div>;

  const buy = async () => {
    if (!confirm(`用 ${data.core_price_wca} WCA Token 購買一顆新能量核心（容量 ${data.core_capacity_wau.toLocaleString()} WAU）？`)) return;
    try { await api("/api/energy/buy", { method: "POST" }); load(); } catch (e) { alert(e.message); }
  };

  return (
    <div>
      <SectionTitle eyebrow="SUPPLY LINE" align="left" size="h2" subtitle="能量是消耗品，軍餉是硬通貨">能量與軍餉</SectionTitle>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, margin: "18px 0" }}>
        <Panel header="能量核心">
          {data.cores.map((c) => {
            const pct = c.status === "depleted" ? 0 : Math.max(0, Math.round((1 - c.used_wau / c.capacity_wau) * 100));
            return (
              <div key={c.seq} style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                  <span style={{ fontSize: 13, color: "var(--gold-300)" }}>第 {c.seq} 顆核心</span>
                  <Badge tone={c.status === "active" ? "gold" : "neutral"} size="sm">{c.status === "active" ? "使用中" : "已耗盡"}</Badge>
                </div>
                <ProgressBar value={pct} max={100} height={10} />
                <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>
                  {c.used_wau.toLocaleString()} / {c.capacity_wau.toLocaleString()} WAU
                </div>
              </div>
            );
          })}
          <div style={{ borderTop: "1px solid rgba(212,175,55,.2)", paddingTop: 12, display: "flex", alignItems: "center", gap: 12 }}>
            <Button size="sm" onClick={buy}>購買新核心（{data.core_price_wca} WCA）</Button>
          </div>
        </Panel>
        <Panel header="WCA 軍餉帳本">
          <div style={{ textAlign: "center", margin: "6px 0 14px" }}>
            <span style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 22, color: "var(--gold-300)" }}>{data.balance}</span>
            <span style={{ color: "var(--text-muted)", fontSize: 12, marginLeft: 8 }}>WCA</span>
          </div>
          <div style={{ maxHeight: 260, overflow: "auto" }}>
            {data.ledger.map((l, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: 12, padding: "6px 2px", borderBottom: "1px solid rgba(212,175,55,.1)" }}>
                <span style={{ color: "var(--text-secondary)" }}>{REASON_LABEL[l.reason] || l.reason}</span>
                <span style={{ color: "var(--text-muted)" }}>{l.created_at.slice(5, 16)}</span>
                <span style={{ color: l.delta >= 0 ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)", fontWeight: 700, width: 48, textAlign: "right" }}>
                  {l.delta >= 0 ? "+" : ""}{l.delta}
                </span>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      <Panel header={`AI 出擊紀錄（最近 ${data.usage.length} 次）`}>
        {data.usage.length === 0 ? (
          <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "10px 0" }}>還沒出擊過——到關卡工作區召喚 AI 教練。</div>
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <thead>
                <tr style={{ color: "var(--gold-300)", textAlign: "left" }}>
                  <th style={{ padding: "6px 8px" }}>時間</th><th style={{ padding: "6px 8px" }}>關卡</th>
                  <th style={{ padding: "6px 8px" }}>任務</th><th style={{ padding: "6px 8px", textAlign: "right" }}>消耗 WAU</th>
                </tr>
              </thead>
              <tbody>
                {data.usage.map((u, i) => (
                  <tr key={i} style={{ borderTop: "1px solid rgba(212,175,55,.1)", color: "var(--text-secondary)" }}>
                    <td style={{ padding: "6px 8px", color: "var(--text-muted)" }}>{u.created_at.slice(5, 16)}</td>
                    <td style={{ padding: "6px 8px" }}>第 {u.module_id} 關</td>
                    <td style={{ padding: "6px 8px" }}>{TASK_LABEL[u.task_type] || u.task_type}</td>
                    <td style={{ padding: "6px 8px", textAlign: "right", color: "var(--gold-300)" }}>{u.wau_charged.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>
    </div>
  );
}

window.Energy = Energy;
})();
