// 戰情總覽 — 倒數 / 能量條 / WCA Token / 關卡進度 / 建議下一步
(() => {
const { Panel, Badge, ProgressBar, SectionTitle, Divider } = window.WCATalentGameDesignSystem_377d00;

const STATUS_LABEL = {
  not_started: { text: "未啟動", tone: "neutral" },
  in_progress: { text: "進行中", tone: "gold" },
  complete: { text: "已完成", tone: "success" },
  locked: { text: "已鎖定", tone: "info" },
};

function Countdown({ target }) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  if (!target) return <span style={{ color: "var(--text-muted)", fontSize: 13 }}>倒數未設定</span>;
  const diff = new Date(target).getTime() - now;
  if (isNaN(diff)) return null;
  if (diff <= 0) return <span style={{ color: "var(--danger, #e07a6a)", fontWeight: 700, letterSpacing: ".15em" }}>時間到 · TIME'S UP</span>;
  const h = Math.floor(diff / 3600000), m = Math.floor((diff % 3600000) / 60000), s = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, "0");
  return (
    <span style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 18, color: "var(--gold-300)", textShadow: "0 0 12px rgba(212,175,55,.5)" }}>
      {pad(h)}:{pad(m)}:{pad(s)}
    </span>
  );
}

function Overview({ me }) {
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState("");
  React.useEffect(() => {
    api("/api/overview").then(setData).catch((e) => setErr(e.message));
  }, []);

  if (err) return <Panel header="戰情總覽"><div style={{ color: "var(--danger,#e07a6a)", padding: 20 }}>{err}</div></Panel>;
  if (!data) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>戰情載入中…</div>;

  const doneCount = data.modules.filter((m) => m.status === "complete" || m.status === "locked").length;
  const overallPct = Math.round((doneCount / data.modules.length) * 100);
  const next = data.modules.find((m) => m.status === "in_progress") || data.modules.find((m) => m.status === "not_started");
  const energy = data.energy.active;

  return (
    <div>
      <SectionTitle eyebrow="COMMAND CENTER" subtitle={data.team.name} align="left" size="h2">戰情總覽</SectionTitle>

      {/* 上排三卡：倒數 / 能量 / 軍餉 */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 16, margin: "18px 0" }}>
        <Panel header="作戰倒數">
          <div style={{ textAlign: "center", padding: "12px 0 6px" }}>
            <Countdown target={data.countdown_target} />
            <div style={{ color: "var(--text-muted)", fontSize: 11, marginTop: 10, letterSpacing: ".2em" }}>COUNTDOWN</div>
          </div>
        </Panel>
        <Panel header="AI 能量核心" glow={energy && energy.remaining_pct <= 10}>
          {energy ? (
            <div style={{ padding: "6px 0" }}>
              <ProgressBar value={energy.remaining_pct} max={100} label={`第 ${energy.seq} 顆核心`} />
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 12, color: "var(--text-muted)" }}>
                <span>剩餘 {energy.remaining_pct}%</span>
                <span>已持有 {data.energy.cores_total} 顆</span>
              </div>
              {energy.remaining_pct <= 10 && (
                <div style={{ color: "var(--danger,#e07a6a)", fontSize: 12, marginTop: 8 }}>能量即將耗盡——考慮用 WCA Token 添購新核心</div>
              )}
            </div>
          ) : (
            <div style={{ color: "var(--danger,#e07a6a)", padding: "10px 0", textAlign: "center" }}>
              能量耗盡 · AI 已鎖定<br />
              <span style={{ fontSize: 12, color: "var(--text-muted)" }}>用 {data.core_price_wca} WCA Token 購買新核心（能量頁施工中）</span>
            </div>
          )}
        </Panel>
        <Panel header="WCA 軍餉">
          <div style={{ textAlign: "center", padding: "10px 0 4px" }}>
            <span style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 22, color: "var(--gold-300)" }}>{data.wca_balance}</span>
            <span style={{ color: "var(--text-muted)", fontSize: 12, marginLeft: 8 }}>WCA</span>
            <div style={{ color: "var(--text-muted)", fontSize: 12, marginTop: 10 }}>新核心價格：{data.core_price_wca} WCA</div>
          </div>
        </Panel>
      </div>

      {/* 進度 + 下一步 */}
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16, alignItems: "start" }} className="sq-two-col">
        <Panel header={`關卡進度 ${doneCount} / ${data.modules.length}`}>
          <ProgressBar value={overallPct} max={100} style={{ marginBottom: 14 }} />
          <div>
            {data.modules.map((m) => {
              const st = STATUS_LABEL[m.status] || STATUS_LABEL.not_started;
              return (
                <div key={m.id} style={{
                  display: "flex", alignItems: "center", gap: 10, padding: "9px 4px",
                  borderBottom: "1px solid rgba(212,175,55,.12)",
                }}>
                  <span style={{ fontFamily: "Cinzel,serif", color: "var(--gold-500)", width: 22, fontSize: 13, textAlign: "center" }}>{m.id}</span>
                  <span style={{ flex: 1, fontSize: 14 }}>{m.title}
                    <span style={{ fontFamily: "Cinzel,serif", fontSize: 9, letterSpacing: ".2em", color: "var(--text-muted)", marginLeft: 8 }}>{m.en}</span>
                  </span>
                  <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{m.required_done}/{m.required_total}</span>
                  <Badge tone={st.tone} size="sm">{st.text}</Badge>
                </div>
              );
            })}
          </div>
        </Panel>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Panel header="建議下一步" glow>
            {next ? (
              <div style={{ padding: "4px 0" }}>
                <div style={{ fontFamily: '"Noto Serif TC",serif', fontWeight: 900, color: "var(--gold-300)", fontSize: 17, letterSpacing: ".08em" }}>
                  第 {next.id} 關 · {next.title}
                </div>
                <div style={{ color: "var(--text-secondary)", fontSize: 13, margin: "10px 0 4px", lineHeight: 1.7 }}>
                  交付物：{next.deliverable}
                </div>
                <div style={{ marginTop: 10 }}>
                  <a href={`#/quests/${next.id}`} style={{ fontSize: 13, fontWeight: 700, letterSpacing: ".08em" }}>前往此關 →</a>
                </div>
              </div>
            ) : (
              <div style={{ color: "var(--success,#7fc97f)", padding: "6px 0" }}>十關皆已完成——前往 Pitch 組裝台收尾。</div>
            )}
          </Panel>
          <Panel header="最終提交">
            {data.submission ? (
              <Badge tone="success">已鎖定 · {data.submission.locked_at}</Badge>
            ) : (
              <div style={{ color: "var(--text-muted)", fontSize: 13 }}>尚未提交</div>
            )}
          </Panel>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .sq-two-col { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

window.Overview = Overview;
})();
