// Admin — 戰情監控（隊伍列表＋管理動作）與活動設定
(() => {
const { Panel, Badge, Button, ProgressBar, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const inputStyle = {
  background: "var(--navy-950)", border: "1px solid rgba(212,175,55,.28)", borderRadius: 6,
  color: "var(--text-primary)", padding: "8px 10px", fontSize: 13, outline: "none", boxSizing: "border-box",
};

function AdminMonitor() {
  const [teams, setTeams] = React.useState(null);
  const [msg, setMsg] = React.useState(null); // {title, body}
  const [newName, setNewName] = React.useState("");
  const [newCode, setNewCode] = React.useState("");
  const load = () => api("/api/admin/teams").then(setTeams).catch((e) => alert(e.message));
  React.useEffect(() => { load(); }, []);

  const createTeam = async () => {
    try {
      const r = await api("/api/admin/teams", { method: "POST", body: { name: newName, code: newCode } });
      setMsg({ title: "隊伍已建立", body: `帳號：${r.username}\n密碼：${r.password}\n\n請抄下來交給隊伍——密碼只顯示這一次。` });
      setNewName(""); setNewCode("");
      load();
    } catch (e) { alert(e.message); }
  };
  const resetPw = async (t) => {
    if (!confirm(`重設「${t.name}」的密碼？舊密碼將立即失效。`)) return;
    const r = await api(`/api/admin/teams/${t.id}/reset-password`, { method: "POST" });
    setMsg({ title: t.name + " 新密碼", body: `帳號：${t.code}\n密碼：${r.password}\n\n請抄下來交給隊伍。` });
  };
  const adjustTokens = async (t) => {
    const delta = prompt(`調整「${t.name}」的 WCA Token（正數加、負數扣）：`);
    if (!delta) return;
    const note = prompt("調整原因（會留稽核紀錄）：");
    if (!note) return;
    try {
      const r = await api(`/api/admin/teams/${t.id}/tokens`, { method: "POST", body: { delta: Number(delta), note } });
      alert(`完成。目前餘額：${r.balance} WCA`);
      load();
    } catch (e) { alert(e.message); }
  };
  const grantCore = async (t) => {
    if (!confirm(`免費補發一顆能量核心給「${t.name}」？（正常途徑是隊伍用 WCA 購買，此功能救急用）`)) return;
    await api(`/api/admin/teams/${t.id}/grant-core`, { method: "POST" });
    load();
  };

  if (!teams) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>載入中…</div>;

  return (
    <div>
      <SectionTitle eyebrow="WAR ROOM" align="left" size="h2" subtitle="全隊即時戰況">戰情監控</SectionTitle>

      <div style={{ margin: "18px 0" }}>
        <Panel header="建立新隊伍">
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
            <input style={{ ...inputStyle, width: 200 }} placeholder="隊名（例：滅菌小隊）" value={newName} onChange={(e) => setNewName(e.target.value)} />
            <input style={{ ...inputStyle, width: 180 }} placeholder="帳號代碼（例：team1）" value={newCode} onChange={(e) => setNewCode(e.target.value)} />
            <Button size="sm" onClick={createTeam}>建立（自動配發初始能量與軍餉）</Button>
          </div>
        </Panel>
      </div>

      <Panel header={`隊伍總表（${teams.length}）`}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 860 }}>
            <thead>
              <tr style={{ color: "var(--gold-300)", textAlign: "left" }}>
                {["隊伍", "帳號", "關卡進度", "能量", "軍餉", "AI 次數 / WAU / 失敗", "提交", "動作"].map((h) => (
                  <th key={h} style={{ padding: "8px 8px", borderBottom: "1px solid rgba(212,175,55,.3)" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {teams.map((t) => {
                const e = t.energy.active;
                return (
                  <tr key={t.id} style={{ borderBottom: "1px solid rgba(212,175,55,.12)", color: "var(--text-secondary)" }}>
                    <td style={{ padding: "8px" , fontWeight: 700, color: "var(--gold-100,#f2ead2)" }}>{t.name}</td>
                    <td style={{ padding: "8px", fontFamily: "monospace" }}>{t.code}</td>
                    <td style={{ padding: "8px", minWidth: 120 }}>
                      <ProgressBar value={t.modules_done} max={10} height={8} showValue={false} />
                      <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{t.modules_done}/10 關</span>
                    </td>
                    <td style={{ padding: "8px" }}>
                      {e ? (
                        <span style={{ color: e.remaining_pct <= 10 ? "var(--danger,#e07a6a)" : "inherit" }}>
                          {e.remaining_pct}%（第 {e.seq} 顆）
                        </span>
                      ) : (
                        <span style={{ color: "var(--danger,#e07a6a)" }}>耗盡</span>
                      )}
                    </td>
                    <td style={{ padding: "8px" }}>{t.wca_balance} WCA</td>
                    <td style={{ padding: "8px" }}>
                      {t.ai_calls} 次 / {t.ai_wau.toLocaleString()} / {t.ai_failed > 0 ? <span style={{ color: "var(--danger,#e07a6a)" }}>{t.ai_failed}</span> : 0}
                    </td>
                    <td style={{ padding: "8px" }}>{t.submitted ? <Badge tone="info" size="sm">已提交</Badge> : <span style={{ color: "var(--text-muted)" }}>—</span>}</td>
                    <td style={{ padding: "8px", whiteSpace: "nowrap" }}>
                      <Button size="sm" variant="ghost" onClick={() => adjustTokens(t)}>±Token</Button>{" "}
                      <Button size="sm" variant="ghost" onClick={() => grantCore(t)}>補核心</Button>{" "}
                      <Button size="sm" variant="ghost" onClick={() => resetPw(t)}>重設密碼</Button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10 }}>
          <Button size="sm" variant="ghost" onClick={load}>重新整理</Button>
        </div>
      </Panel>

      {msg && (
        <div onClick={() => setMsg(null)} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(5,7,15,.75)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: 380, maxWidth: "100%" }}>
            <Panel header={msg.title} glow>
              <pre style={{ fontSize: 14, whiteSpace: "pre-wrap", color: "var(--text-primary)", fontFamily: "monospace", margin: "6px 0 14px" }}>{msg.body}</pre>
              <Button size="sm" onClick={() => setMsg(null)}>知道了</Button>
            </Panel>
          </div>
        </div>
      )}
    </div>
  );
}

const SETTING_META = [
  ["event_name", "活動名稱", "text"],
  ["countdown_target", "倒數目標時間（例：2026-08-15T09:00:00+08:00）", "text"],
  ["core_capacity_wau", "能量核心容量（WAU）", "number"],
  ["core_price_wca", "新核心售價（WCA）", "number"],
  ["initial_wca", "每隊初始 WCA", "number"],
  ["initial_cores", "每隊初始核心數", "number"],
  ["rate_limit_per_min", "每隊每分鐘 AI 上限", "number"],
  ["max_output_tokens", "單次輸出上限（一般任務）", "number"],
  ["max_output_tokens_long", "單次輸出上限（跨關卡/Pitch）", "number"],
  ["model_default", "預設模型", "text"],
  ["model_light", "輕量模型", "text"],
  ["multiplier_default", "預設模型倍率", "text"],
  ["multiplier_light", "輕量模型倍率", "text"],
];

function AdminSettings() {
  const [vals, setVals] = React.useState(null);
  const [saved, setSaved] = React.useState(false);
  const [pw, setPw] = React.useState("");
  React.useEffect(() => { api("/api/admin/settings").then(setVals).catch((e) => alert(e.message)); }, []);
  if (!vals) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>載入中…</div>;

  const save = async () => {
    try {
      await api("/api/admin/settings", { method: "PUT", body: vals });
      setSaved(true); setTimeout(() => setSaved(false), 2500);
    } catch (e) { alert(e.message); }
  };
  const changePw = async () => {
    try {
      await api("/api/admin/change-password", { method: "POST", body: { password: pw } });
      alert("admin 密碼已更新"); setPw("");
    } catch (e) { alert(e.message); }
  };

  return (
    <div>
      <SectionTitle eyebrow="RULES OF ENGAGEMENT" align="left" size="h2" subtitle="改動立即生效；新隊伍才吃初始值">活動設定</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 16, marginTop: 18, alignItems: "start" }}>
        <Panel header="參數">
          {SETTING_META.map(([key, label, type]) => (
            <div key={key} style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>{label}</div>
              <input type={type} style={{ ...inputStyle, width: "100%" }} value={vals[key] ?? ""}
                onChange={(e) => setVals({ ...vals, [key]: e.target.value })} />
            </div>
          ))}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 14 }}>
            <Button size="sm" onClick={save}>儲存設定</Button>
            {saved && <span style={{ color: "var(--success,#7fc97f)", fontSize: 13 }}>已儲存 ✓</span>}
          </div>
        </Panel>
        <Panel header="admin 密碼">
          <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>至少 8 字。改完舊密碼立即失效。</div>
          <input type="password" style={{ ...inputStyle, width: "100%", marginBottom: 10 }} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="新密碼" />
          <Button size="sm" onClick={changePw}>更新密碼</Button>
        </Panel>
      </div>
    </div>
  );
}

window.AdminMonitor = AdminMonitor;
window.AdminSettings = AdminSettings;
})();
