// AdminGame — 遊戲總控台（控台官現場操作主介面）
(() => {
const { Panel, Badge, Button, SectionTitle, Tabs } = 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",
};
const thStyle = { padding: "8px 8px", borderBottom: "1px solid rgba(212,175,55,.3)", color: "var(--gold-300)", textAlign: "left", fontWeight: 600, whiteSpace: "nowrap" };
const selStyle = { ...inputStyle, width: "100%" };
const tdStyle = { padding: "8px 8px", borderBottom: "1px solid rgba(212,175,55,.10)", color: "var(--text-secondary)", verticalAlign: "middle" };
const W = (n) => (n / 10000).toFixed(1) + "萬"; // 元 → 萬
const toW = (n) => (Number(n) / 10000).toFixed(1);

// ── 重新整理鈕：成功後短暫顯示已同步（否則抓回同樣資料時畫面零變化，像沒反應）──
function RefreshBtn({ onClick }) {
  const [ok, setOk] = React.useState(false);
  const click = async () => {
    try { await onClick(); setOk(true); setTimeout(() => setOk(false), 1500); } catch {}
  };
  return <Button size="sm" variant="ghost" onClick={click}>{ok ? "✓ 已同步" : "重新整理"}</Button>;
}

// ── 確認彈層 ─────────────────────────────────────────────
function Confirm({ title, body, onConfirm, onCancel }) {
  return (
    <div onClick={onCancel} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(5,7,15,.82)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 400, maxWidth: "100%" }}>
        <Panel header={title} glow>
          <p style={{ fontSize: 14, color: "var(--text-secondary)", margin: "6px 0 18px", lineHeight: 1.6 }}>{body}</p>
          <div style={{ display: "flex", gap: 10 }}>
            <Button size="sm" onClick={onConfirm}>確認執行</Button>
            <Button size="sm" variant="ghost" onClick={onCancel}>取消</Button>
          </div>
        </Panel>
      </div>
    </div>
  );
}

// ── 通用訊息彈層 ──────────────────────────────────────────
function Msg({ title, body, onClose }) {
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(5,7,15,.82)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 440, maxWidth: "100%" }}>
        <Panel header={title} glow>
          <pre style={{ fontSize: 13, whiteSpace: "pre-wrap", color: "var(--text-primary)", fontFamily: "monospace", margin: "6px 0 14px", userSelect: "all" }}>{body}</pre>
          <Button size="sm" onClick={onClose}>知道了</Button>
        </Panel>
      </div>
    </div>
  );
}

// ═══════════════ 分頁 1：階段 ═══════════════════════════
const PHASES = ["setup","day1_game","team_up","angel_draw","hackathon","pre_a","ma_window","asset_lock","pitch","bet_window","settlement","reveal","day3_final"];
const PHASE_LABELS = { setup:"賽前準備", day1_game:"九域試煉", team_up:"組隊", angel_draw:"天使輪", hackathon:"黑客松", pre_a:"Pre-A 輪", ma_window:"併購窗口", asset_lock:"資產鎖定", pitch:"Final Pitch", bet_window:"押注窗口", settlement:"結算", reveal:"揭曉", day3_final:"個人清算" };

function TabPhase({ me }) {
  const canCtrl = !me || me.phase_ctrl !== false; // leader 直登唯讀；後端亦擋
  const [cur, setCur] = React.useState(null);
  const [confirm, setConfirm] = React.useState(null); // {phase}
  const load = () => api("/api/phase").then((d) => setCur(d.phase)).catch((e) => alert(e.message));
  React.useEffect(() => { load(); }, []);

  const doSet = async (phase, force) => {
    try {
      await api("/api/admin/phase", { method: "POST", body: { phase, force } });
      setCur(phase);
      setConfirm(null);
    } catch (e) {
      if (e.message && e.message.includes("need_force")) {
        setConfirm({ phase });
      } else {
        alert(e.message);
      }
    }
  };

  // 後端 409 附 need_force，但 util.js 只取 data.error——改帳辦法：先試，若 error 含「force」就彈確認
  const handleClick = async (phase) => {
    try {
      await api("/api/admin/phase", { method: "POST", body: { phase } });
      setCur(phase);
    } catch (e) {
      // e.message 是 "回退階段需要確認（force）" 等
      if (e.message && (e.message.includes("force") || e.message.includes("跳") || e.message.includes("回退"))) {
        setConfirm({ phase });
      } else {
        alert(e.message);
      }
    }
  };

  return (
    <div>
      <SectionTitle eyebrow="PHASE CONTROL" align="left" size="h2" subtitle={canCtrl ? "點擊按鈕切換當前階段" : "唯讀檢視——階段切換僅限控台官"}>階段控制</SectionTitle>
      {cur && (
        <div style={{ margin: "16px 0", padding: "16px 20px", background: "rgba(212,175,55,.08)", borderRadius: 8, border: "1px solid rgba(212,175,55,.3)", display: "inline-block" }}>
          <span style={{ fontSize: 12, color: "var(--text-muted)", letterSpacing: ".1em" }}>目前階段</span>
          <div style={{ fontSize: 26, fontWeight: 700, color: "var(--gold-300)", marginTop: 4 }}>{PHASE_LABELS[cur] || cur}</div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "monospace" }}>{cur}</div>
        </div>
      )}
      <Panel header="13 階段">
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 4 }}>
          {PHASES.map((ph, i) => (
            <button key={ph} disabled={!canCtrl} onClick={() => canCtrl && handleClick(ph)} style={{
              padding: "8px 14px", borderRadius: 6, cursor: canCtrl ? "pointer" : "not-allowed", fontSize: 13, fontWeight: ph === cur ? 700 : 400,
              opacity: canCtrl || ph === cur ? 1 : 0.45,
              background: ph === cur ? "var(--grad-gold)" : "var(--navy-850)",
              color: ph === cur ? "var(--navy-950)" : "var(--text-secondary)",
              border: ph === cur ? "none" : "1px solid rgba(212,175,55,.25)",
              boxShadow: ph === cur ? "var(--glow-gold-sm)" : "none",
              transition: "all .2s",
            }}>
              <span style={{ fontSize: 11, opacity: .6, marginRight: 4 }}>{i + 1}.</span>
              {PHASE_LABELS[ph]}
            </button>
          ))}
        </div>
        <div style={{ marginTop: 12 }}><RefreshBtn onClick={load} /></div>
      </Panel>
      {confirm && (
        <Confirm
          title="跳關 / 回退確認"
          body={`即將強制切換到「${PHASE_LABELS[confirm.phase]}」。此操作會跳過或倒退中間階段，請確認無誤再執行。`}
          onConfirm={() => doSet(confirm.phase, true)}
          onCancel={() => setConfirm(null)}
        />
      )}
    </div>
  );
}

// ═══════════════ 分頁 2：人員 ═══════════════════════════
const ROLE_ZH = { student:"學員", mentor:"導師", judge:"評審", gate:"關主", audience:"觀眾", screen:"大螢幕" };
const ROLE_KEYS = Object.keys(ROLE_ZH);

function TabUsers() {
  const [text, setText] = React.useState("");
  const [users, setUsers] = React.useState(null);
  const [created, setCreated] = React.useState(null); // [{name,role,username,password}]
  const [resetting, setResetting] = React.useState(null); // {id,username,display_name}
  const [resetInput, setResetInput] = React.useState(""); // 重設密碼的自訂輸入（留空＝隨機）

  const load = () => api("/api/admin/users").then(setUsers).catch((e) => alert(e.message));
  React.useEffect(() => { load(); }, []);

  const submit = async () => {
    const lines = text.trim().split("\n").filter(Boolean);
    if (!lines.length) return alert("請輸入人員清單");
    const userList = [];
    for (const ln of lines) {
      const parts = ln.split(",").map((s) => s.trim());
      const [name, roleRaw, dept, pw] = parts;
      if (!name || !roleRaw) return alert(`格式錯誤：${ln}`);
      const role = ROLE_KEYS.find((k) => ROLE_ZH[k] === roleRaw || k === roleRaw);
      if (!role) return alert(`角色無效：${roleRaw}（可用：${Object.values(ROLE_ZH).join("/")}）`);
      userList.push({ name, role, dept: dept || "", password: pw || "" });
    }
    try {
      const r = await api("/api/admin/users", { method: "POST", body: { users: userList } });
      setCreated(r.users);
      setText("");
      load();
    } catch (e) { alert(e.message); }
  };

  const resetPw = async (u, pw) => {
    setResetting(null);
    try {
      const r = await api(`/api/admin/users/${u.id}/reset-password`, { method: "POST", body: pw ? { password: pw } : {} });
      setCreated([{ name: u.display_name, role: u.role, username: u.username, password: r.password }]);
    } catch (e) { alert(e.message); }
  };

  return (
    <div>
      <SectionTitle eyebrow="ROSTER" align="left" size="h2" subtitle="批次建帳號、查全員">人員管理</SectionTitle>
      <Panel header="批次建帳號" style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>每行一人：<code style={{ color: "var(--gold-300)" }}>姓名,角色,系別(選填),密碼(選填 4–30 字)</code>　角色：{Object.entries(ROLE_ZH).map(([k,v]) => `${v}=${k}`).join(" / ")}<br/>密碼留空＝自動產生；沒有系別但要自訂密碼時，系別留空要保留逗號（例：<code style={{ color: "var(--gold-300)" }}>陳博士,導師,,abc123</code>）</div>
        <textarea
          style={{ ...inputStyle, width: "100%", height: 120, resize: "vertical", display: "block", marginBottom: 10 }}
          placeholder={"王小明,學員,醫,0312\n陳博士,導師"}
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
        <Button size="sm" onClick={submit}>建立帳號</Button>
      </Panel>

      {created && (
        <Panel header={`帳號已建立（${created.length} 人）— 請立即複製保存，密碼只顯示這一次`} glow>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, marginTop: 6 }}>
              <thead>
                <tr>{["姓名","角色","帳號","密碼"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
              </thead>
              <tbody>
                {created.map((u) => (
                  <tr key={u.username}>
                    <td style={tdStyle}>{u.name}</td>
                    <td style={tdStyle}><Badge tone="info" size="sm">{ROLE_ZH[u.role] || u.role}</Badge></td>
                    <td style={{ ...tdStyle, fontFamily: "monospace" }}>{u.username}</td>
                    <td style={{ ...tdStyle, fontFamily: "monospace", color: "var(--gold-200)", userSelect: "all" }}>{u.password}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <Button size="sm" variant="ghost" style={{ marginTop: 10 }} onClick={() => setCreated(null)}>收起</Button>
        </Panel>
      )}

      <Panel header={`全員名單（${users ? users.length : "…"}）`}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 700 }}>
            <thead>
              <tr>{["角色","姓名","帳號","系別","職位","隊伍","餘額（元）","動作"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {(users || []).map((u) => (
                <tr key={u.id}>
                  <td style={tdStyle}><Badge tone="info" size="sm">{ROLE_ZH[u.role] || u.role}</Badge></td>
                  <td style={{ ...tdStyle, fontWeight: 600, color: "var(--gold-100,#f2ead2)" }}>{u.display_name}</td>
                  <td style={{ ...tdStyle, fontFamily: "monospace" }}>{u.username}</td>
                  <td style={tdStyle}>{u.dept || "—"}</td>
                  <td style={tdStyle}>{u.position || "—"}</td>
                  <td style={tdStyle}>{u.team_name || u.day1_team_name || "—"}</td>
                  <td style={tdStyle}>{u.balance != null ? u.balance.toLocaleString() : "—"}</td>
                  <td style={tdStyle}>
                    <Button size="sm" variant="ghost" onClick={() => { setResetInput(""); setResetting(u); }}>重設密碼</Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10 }}><RefreshBtn onClick={load} /></div>
      </Panel>

      {resetting && (
        <div onClick={() => setResetting(null)} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(5,7,15,.82)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: 400, maxWidth: "100%" }}>
            <Panel header={`重設「${resetting.display_name}」的密碼`} glow>
              <p style={{ fontSize: 13.5, color: "var(--text-secondary)", margin: "6px 0 10px", lineHeight: 1.6 }}>確認後舊密碼立即失效，新密碼只顯示一次，請抄下來。</p>
              <input
                style={{ ...inputStyle, width: "100%", marginBottom: 14 }}
                placeholder="自訂新密碼 4–30 字（留空＝自動產生）"
                value={resetInput}
                onChange={(e) => setResetInput(e.target.value)}
              />
              <div style={{ display: "flex", gap: 10 }}>
                <Button size="sm" onClick={() => resetPw(resetting, resetInput.trim())}>確認執行</Button>
                <Button size="sm" variant="ghost" onClick={() => setResetting(null)}>取消</Button>
              </div>
            </Panel>
          </div>
        </div>
      )}
    </div>
  );
}

// ═══════════════ 分頁 3：Day1 賽程 ═══════════════════════
function TabDay1() {
  const [name, setName] = React.useState("");
  const [selectedIds, setSelectedIds] = React.useState([]);
  const [day1Teams, setDay1Teams] = React.useState(null);
  const [matches, setMatches] = React.useState(null);
  const [matchTeams, setMatchTeams] = React.useState([]);
  const [allUsers, setAllUsers] = React.useState([]);
  const [fixing, setFixing] = React.useState(null); // {match, newWinner}

  const loadAll = () => {
    api("/api/admin/day1-teams").then(setDay1Teams).catch((e) => alert(e.message));
    api("/api/gate/matches").then((d) => { setMatches(d.matches); setMatchTeams(d.teams); }).catch((e) => alert(e.message));
    api("/api/admin/users").then((u) => setAllUsers(u.filter((x) => x.role === "student"))).catch(() => {});
  };
  React.useEffect(() => { loadAll(); }, []);

  const createTeam = async () => {
    if (!name.trim()) return alert("隊名必填");
    try {
      await api("/api/admin/day1-teams", { method: "POST", body: { name: name.trim(), member_ids: selectedIds } });
      setName(""); setSelectedIds([]);
      loadAll();
    } catch (e) { alert(e.message); }
  };

  const doFix = async () => {
    if (!fixing) return;
    try {
      await api(`/api/admin/match/${fixing.match.id}/fix`, { method: "POST", body: { winner: fixing.newWinner } });
      setFixing(null);
      loadAll();
    } catch (e) { alert(e.message); }
  };

  const removeMember = async (t, m) => {
    if (!window.confirm(`把「${m.display_name}」移出「${t.name}」？（回到未分隊名單）`)) return;
    try {
      await api(`/api/admin/users/${m.id}`, { method: "PATCH", body: { day1_team_id: null } });
      loadAll();
    } catch (e) { alert(e.message); }
  };

  const addMember = async (t, accountId) => {
    try {
      await api(`/api/admin/users/${accountId}`, { method: "PATCH", body: { day1_team_id: t.id } });
      loadAll();
    } catch (e) { alert(e.message); }
  };

  // 按輪次分組
  const byRound = {};
  (matches || []).forEach((m) => {
    byRound[m.round] = byRound[m.round] || [];
    byRound[m.round].push(m);
  });
  const teamMap = {};
  matchTeams.forEach((t) => { teamMap[t.id] = t.name; });

  const toggleId = (id) => setSelectedIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]);
  const availUsers = allUsers.filter((u) => !u.day1_team_id); // 已入隊者不再列入可選

  return (
    <div>
      <SectionTitle eyebrow="DAY1 ARENA" align="left" size="h2" subtitle="九域試煉小隊＋戰績">九域試煉</SectionTitle>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 16, marginBottom: 16 }}>
        <Panel header="建立 Day1 小隊">
          <input style={{ ...inputStyle, width: "100%", marginBottom: 10 }} placeholder="隊名" value={name} onChange={(e) => setName(e.target.value)} />
          <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}>從學員中多選成員（未分隊 {availUsers.length} 人）：</div>
          <div style={{ maxHeight: 180, overflowY: "auto", border: "1px solid rgba(212,175,55,.2)", borderRadius: 6, padding: 8, marginBottom: 10 }}>
            {allUsers.length === 0 && <div style={{ color: "var(--text-muted)", fontSize: 12 }}>尚無學員帳號</div>}
            {allUsers.length > 0 && availUsers.length === 0 && <div style={{ color: "var(--text-muted)", fontSize: 12 }}>全部學員都已分隊</div>}
            {availUsers.map((u) => (
              <label key={u.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0", cursor: "pointer", fontSize: 13 }}>
                <input type="checkbox" checked={selectedIds.includes(u.id)} onChange={() => toggleId(u.id)} />
                <span style={{ color: selectedIds.includes(u.id) ? "var(--gold-200)" : "var(--text-secondary)" }}>{u.display_name} {u.dept ? `(${u.dept})` : ""}</span>
              </label>
            ))}
          </div>
          <Button size="sm" onClick={createTeam}>建立小隊</Button>
        </Panel>

        <Panel header={`已建小隊（${day1Teams ? day1Teams.length : "…"}）`}>
          {(day1Teams || []).map((t) => (
            <div key={t.id} style={{ marginBottom: 8, padding: "8px 10px", background: "rgba(212,175,55,.06)", borderRadius: 6, border: "1px solid rgba(212,175,55,.15)" }}>
              <div style={{ fontWeight: 700, color: "var(--gold-200)", fontSize: 13 }}>{t.name} <span style={{ fontFamily: "monospace", fontWeight: 400, color: "var(--text-muted)", fontSize: 11 }}>{t.code}</span></div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 6 }}>
                {(t.members || []).map((m) => (
                  <span key={m.id} style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 12, color: "var(--text-secondary)", background: "rgba(212,175,55,.10)", border: "1px solid rgba(212,175,55,.2)", borderRadius: 12, padding: "2px 8px" }}>
                    {m.display_name}
                    <span title="移出小隊" onClick={() => removeMember(t, m)} style={{ cursor: "pointer", color: "var(--text-muted)", fontWeight: 700, padding: "0 2px" }}>✕</span>
                  </span>
                ))}
                {(t.members || []).length === 0 && <span style={{ fontSize: 12, color: "var(--text-muted)" }}>（無成員）</span>}
              </div>
              {availUsers.length > 0 && (
                <select style={{ ...selStyle, width: "100%", marginTop: 8, fontSize: 12 }} value="" onChange={(e) => e.target.value && addMember(t, Number(e.target.value))}>
                  <option value="">＋ 加入成員（未分隊 {availUsers.length} 人）</option>
                  {availUsers.map((u) => <option key={u.id} value={u.id}>{u.display_name} {u.dept ? `(${u.dept})` : ""}</option>)}
                </select>
              )}
            </div>
          ))}
          {(!day1Teams || !day1Teams.length) && <div style={{ color: "var(--text-muted)", fontSize: 12 }}>尚無小隊</div>}
        </Panel>
      </div>

      <Panel header="戰績矩陣">
        {Object.keys(byRound).length === 0 && <div style={{ color: "var(--text-muted)", fontSize: 13 }}>尚無戰績</div>}
        {Object.keys(byRound).sort((a, b) => Number(a) - Number(b)).map((round) => (
          <div key={round} style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 12, color: "var(--gold-300)", marginBottom: 6, letterSpacing: ".08em" }}>第 {round} 輪</div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ borderCollapse: "collapse", fontSize: 12.5 }}>
                <thead>
                  <tr>
                    {["場地","隊伍 A","隊伍 B","勝方","改判"].map((h) => <th key={h} style={{ ...thStyle, minWidth: 80 }}>{h}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {byRound[round].map((m) => (
                    <tr key={m.id}>
                      <td style={tdStyle}>{m.court}</td>
                      <td style={tdStyle}>{teamMap[m.team_a] || m.team_a}</td>
                      <td style={tdStyle}>{teamMap[m.team_b] || m.team_b}</td>
                      <td style={{ ...tdStyle, color: "var(--gold-200)", fontWeight: 600 }}>{teamMap[m.winner] || m.winner}</td>
                      <td style={tdStyle}>
                        <Button size="sm" variant="ghost" onClick={() => {
                          const newW = m.winner === m.team_a ? m.team_b : m.team_a;
                          setFixing({ match: m, newWinner: newW, teamMap });
                        }}>改判</Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ))}
        <RefreshBtn onClick={loadAll} />
      </Panel>

      {fixing && (
        <Confirm
          title="改判確認"
          body={`將「${fixing.match.round}輪${fixing.match.court}場」勝方改為「${fixing.teamMap[fixing.newWinner] || fixing.newWinner}」？原先入帳將沖銷並重新計算。`}
          onConfirm={doFix}
          onCancel={() => setFixing(null)}
        />
      )}
    </div>
  );
}

// ═══════════════ 分頁 4：組隊 ════════════════════════════
function TabTeamUp() {
  const [teams, setTeams] = React.useState(null);
  const [allUsers, setAllUsers] = React.useState([]);
  const [form, setForm] = React.useState({ name: "", members: [{account_id:"",position:"CEO"},{account_id:"",position:"CPO"},{account_id:"",position:"CBO"}], mentor_account_id: "", sponsor_topic: "", sponsor_account_id: "" });

  const load = () => {
    api("/api/admin/startup-teams").then(setTeams).catch((e) => alert(e.message));
    api("/api/admin/users").then(setAllUsers).catch(() => {});
  };
  React.useEffect(() => { load(); }, []);

  const students = allUsers.filter((u) => u.role === "student" && !u.team_id); // 已進創業隊者不再列入可選
  const mentors = allUsers.filter((u) => u.role === "mentor");
  const judgesAll = allUsers.filter((u) => u.role === "judge");

  const updateMember = (i, field, val) => {
    const ms = [...form.members];
    ms[i] = { ...ms[i], [field]: val };
    // 選人時自動帶出他的既定職位（第一列固定 CEO 不帶），仍可手動改
    if (field === "account_id" && i > 0 && val) {
      const u = allUsers.find((x) => x.id === Number(val));
      if (u && ["CPO", "CBO", "COO", "CFO"].includes(u.position)) ms[i].position = u.position;
    }
    setForm({ ...form, members: ms });
  };

  const submit = async () => {
    if (!form.name.trim()) return alert("隊名必填");
    const members = form.members.filter((m) => m.account_id).map((m) => ({ account_id: Number(m.account_id), position: m.position }));
    if (!members.length) return alert("至少選一位學員");
    if (new Set(members.map((m) => m.position)).size !== members.length) return alert("職位不可重複：另兩位請從 CPO/CBO/COO/CFO 選不同職位");
    if (new Set(members.map((m) => m.account_id)).size !== members.length) return alert("同一位學員不可重複選入");
    try {
      await api("/api/admin/startup-teams", { method: "POST", body: {
        name: form.name.trim(),
        members,
        mentor_account_id: form.mentor_account_id ? Number(form.mentor_account_id) : null,
        sponsor_topic: form.sponsor_topic,
        sponsor_account_id: form.sponsor_account_id ? Number(form.sponsor_account_id) : null,
      }});
      setForm({ name: "", members: [{account_id:"",position:"CEO"},{account_id:"",position:"CPO"},{account_id:"",position:"CBO"}], mentor_account_id: "", sponsor_topic: "", sponsor_account_id: "" });
      load();
    } catch (e) { alert(e.message); }
  };


  return (
    <div>
      <SectionTitle eyebrow="STARTUP TEAMS" align="left" size="h2" subtitle="建立創業隊＋查全隊">組隊管理</SectionTitle>
      <Panel header="建立創業隊" style={{ marginBottom: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 14 }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>隊名</div>
            <input style={{ ...inputStyle, width: "100%" }} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="例：滅菌公司" />
          </div>
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>企業題目</div>
            <input style={{ ...inputStyle, width: "100%" }} value={form.sponsor_topic} onChange={(e) => setForm({ ...form, sponsor_topic: e.target.value })} placeholder="企業出題題目" />
          </div>
        </div>

        <div style={{ marginTop: 14, marginBottom: 6, fontSize: 12, color: "var(--gold-300)" }}>學員（3 人：CEO 必有，另兩位從 CPO/CBO/COO/CFO 任選不重複）</div>
        {form.members.map((m, i) => (
          <div key={i} style={{ display: "flex", gap: 10, marginBottom: 8, alignItems: "center" }}>
            <span style={{ fontSize: 12, color: "var(--text-muted)", width: 40, textAlign: "right" }}>{i === 0 ? "CEO" : `成員${i + 1}`}</span>
            <select style={{ ...selStyle, flex: 1 }} value={m.account_id} onChange={(e) => updateMember(i, "account_id", e.target.value)}>
              <option value="">— 選學員 —</option>
              {students.map((u) => <option key={u.id} value={u.id}>{u.display_name}{u.position ? `［${u.position}］` : ""} {u.dept ? `(${u.dept})` : ""}</option>)}
            </select>
            <select style={{ ...selStyle, width: 90 }} disabled={i === 0} value={m.position} onChange={(e) => updateMember(i, "position", e.target.value)}>
              {(i === 0 ? ["CEO"] : ["CPO", "CBO", "COO", "CFO"]).map((p) => <option key={p} value={p}>{p}</option>)}
            </select>
          </div>
        ))}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 10 }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>導師</div>
            <select style={selStyle} value={form.mentor_account_id} onChange={(e) => setForm({ ...form, mentor_account_id: e.target.value })}>
              <option value="">— 選導師 —</option>
              {mentors.map((u) => <option key={u.id} value={u.id}>{u.display_name}</option>)}
            </select>
          </div>
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>出題企業（評審帳號）</div>
            <select style={selStyle} value={form.sponsor_account_id} onChange={(e) => setForm({ ...form, sponsor_account_id: e.target.value })}>
              <option value="">— 選出題企業 —</option>
              {judgesAll.map((u) => <option key={u.id} value={u.id}>{u.display_name}</option>)}
            </select>
          </div>
        </div>

        <div style={{ marginTop: 14 }}><Button size="sm" onClick={submit}>建立創業隊</Button></div>
      </Panel>

      <Panel header={`創業隊列表（${teams ? teams.length : "…"}）`}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 760 }}>
            <thead>
              <tr>{["隊名","成員/職位","導師","餘額","狀態","企業題","出題企業"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {(teams || []).map((t) => (
                <tr key={t.id}>
                  <td style={{ ...tdStyle, fontWeight: 700, color: "var(--gold-100,#f2ead2)" }}>{t.name}<br/><span style={{ fontFamily: "monospace", fontSize: 10, color: "var(--text-muted)" }}>{t.code}</span></td>
                  <td style={tdStyle}>
                    {(t.members || []).map((m) => (
                      <div key={m.id} style={{ fontSize: 11 }}><Badge tone="info" size="sm">{m.position}</Badge> {m.display_name}</div>
                    ))}
                  </td>
                  <td style={tdStyle}>{t.mentor ? t.mentor.display_name : "—"}</td>
                  <td style={tdStyle}>{W(t.balance)}</td>
                  <td style={tdStyle}>
                    {t.merged_from && t.merged_from.length > 0 ? <Badge tone="warn" size="sm">已併購</Badge> : <Badge tone="success" size="sm">{t.status || "active"}</Badge>}
                  </td>
                  <td style={{ ...tdStyle, maxWidth: 180, whiteSpace: "normal", fontSize: 11 }}>{t.sponsor_topic || "—"}</td>
                  <td style={{ ...tdStyle, fontSize: 11 }}>{t.sponsor ? t.sponsor.display_name : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10 }}><RefreshBtn onClick={load} /></div>
      </Panel>
    </div>
  );
}

// ═══════════════ 分頁 5：天使 ════════════════════════════
function TabAngel() {
  const [funds, setFunds] = React.useState(null);
  const [teams, setTeams] = React.useState(null);
  const [selFund, setSelFund] = React.useState("");
  const [selTeam, setSelTeam] = React.useState("");
  const [random, setRandom] = React.useState(false);
  const [finalizeConfirm, setFinalizeConfirm] = React.useState(false);
  const [initConfirm, setInitConfirm] = React.useState(false);

  const load = () => {
    api("/api/admin/angel").then(setFunds).catch((e) => alert(e.message));
    api("/api/admin/startup-teams").then(setTeams).catch(() => {});
  };
  React.useEffect(() => { load(); }, []);

  const doInit = async () => {
    setInitConfirm(false);
    try {
      await api("/api/admin/angel/init", { method: "POST" });
      load();
    } catch (e) { alert(e.message); }
  };

  const doAssign = async () => {
    if (!selTeam) return alert("請選擇隊伍");
    if (!random && !selFund) return alert("請選擇天使包（或勾選「隨機」）");
    try {
      await api("/api/admin/angel/assign", { method: "POST", body: { fund_id: random ? undefined : Number(selFund), team_id: Number(selTeam), random: random || undefined } });
      setSelFund(""); setSelTeam(""); setRandom(false);
      load();
    } catch (e) { alert(e.message); }
  };

  const doFinalize = async () => {
    setFinalizeConfirm(false);
    try {
      await api("/api/admin/angel/finalize", { method: "POST" });
      alert("初始資產已鎖定！");
      load();
    } catch (e) { alert(e.message); }
  };

  const unassigned = (funds || []).filter((f) => !f.team_id);
  const assigned = (funds || []).filter((f) => !!f.team_id);

  return (
    <div>
      <SectionTitle eyebrow="ANGEL ROUND" align="left" size="h2" subtitle="盲抽天使包→鎖初始資產">天使輪</SectionTitle>

      <div style={{ marginBottom: 14 }}>
        <Button size="sm" onClick={() => setInitConfirm(true)}>一鍵初始化 10 包（冪等，已存在會拒絕）</Button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16 }}>
        <Panel header="天使包清單">
          {(funds || []).length === 0 && <div style={{ color: "var(--text-muted)", fontSize: 13 }}>尚未初始化</div>}
          {(funds || []).map((f) => (
            <div key={f.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "7px 0", borderBottom: "1px solid rgba(212,175,55,.10)", fontSize: 13 }}>
              <span style={{ color: "var(--gold-200)" }}>{f.name}</span>
              <span style={{ fontFamily: "monospace", marginLeft: 8 }}>{W(f.amount)}</span>
              <span style={{ fontSize: 11, color: f.team_id ? "var(--success,#7fc97f)" : "var(--text-muted)" }}>
                {f.team_id ? (f.team_name || "已分配") : "未抽"}
                {f.confirmed_by ? "（已確認）" : ""}
              </span>
            </div>
          ))}
        </Panel>

        <Panel header="指派天使包">
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>目標隊伍</div>
            <select style={{ ...inputStyle, width: "100%" }} value={selTeam} onChange={(e) => setSelTeam(e.target.value)}>
              <option value="">— 選創業隊 —</option>
              {(teams || []).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
          </div>
          <div style={{ marginBottom: 10 }}>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-secondary)", cursor: "pointer", marginBottom: 8 }}>
              <input type="checkbox" checked={random} onChange={(e) => setRandom(e.target.checked)} />
              隨機抽一包（未指派中隨機）
            </label>
            {!random && (
              <>
                <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>指定天使包</div>
                <select style={{ ...inputStyle, width: "100%" }} value={selFund} onChange={(e) => setSelFund(e.target.value)}>
                  <option value="">— 選天使包 —</option>
                  {unassigned.map((f) => <option key={f.id} value={f.id}>{f.name}（{W(f.amount)}）</option>)}
                </select>
              </>
            )}
          </div>
          <Button size="sm" onClick={doAssign}>指派</Button>
        </Panel>
      </div>

      <div style={{ marginTop: 20 }}>
        <Panel header="鎖定初始資產（不可逆）" glow>
          <p style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 12 }}>
            全隊天使包確認無誤後，點擊下方按鈕：個人 Token 轉公司錢包、天使注資、建 cap table、鎖快照。此操作<strong style={{ color: "var(--danger,#e07a6a)" }}>不可撤回</strong>。
          </p>
          <Button onClick={() => setFinalizeConfirm(true)}>一鍵定案（鎖初始資產）</Button>
        </Panel>
      </div>

      {initConfirm && <Confirm title="初始化天使包" body="將依活動設定建立 10 個天使包。已存在則拒絕（冪等）。" onConfirm={doInit} onCancel={() => setInitConfirm(false)} />}
      {finalizeConfirm && (
        <Confirm
          title="⚠ 鎖定初始資產（不可逆）"
          body="執行後：個人 Token 轉入公司、天使包注資、cap table v1 建立、快照鎖定。確認所有隊伍天使包都已正確指派再執行。"
          onConfirm={doFinalize}
          onCancel={() => setFinalizeConfirm(false)}
        />
      )}
    </div>
  );
}

// ═══════════════ 分頁 6：併購 ════════════════════════════
function TabMA() {
  const [deals, setDeals] = React.useState(null);
  const [approving, setApproving] = React.useState(null);

  const load = () => api("/api/ma/pending").then(setDeals).catch((e) => alert(e.message));
  React.useEffect(() => { load(); }, []);

  const doApprove = async () => {
    if (!approving) return;
    try {
      await api(`/api/admin/ma/${approving.id}/approve`, { method: "POST" });
      setApproving(null);
      load();
    } catch (e) { alert(e.message); }
  };

  const STATUS_ZH = { proposed: "提案中", accepted: "雙方同意", approved: "已核准", rejected: "已拒絕" };

  return (
    <div>
      <SectionTitle eyebrow="M&A" align="left" size="h2" subtitle="審核雙方 CEO 已同意的併購案">併購審核</SectionTitle>
      <Panel header={`待審併購案（${deals ? deals.length : "…"}）`}>
        {(!deals || !deals.length) && <div style={{ color: "var(--text-muted)", fontSize: 13 }}>無待審案件</div>}
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
            <thead>
              <tr>{["ID","提案隊","目標隊","狀態","動作"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {(deals || []).map((d) => (
                <tr key={d.id}>
                  <td style={{ ...tdStyle, fontFamily: "monospace" }}>#{d.id}</td>
                  <td style={{ ...tdStyle, color: "var(--gold-200)" }}>{d.proposer_name}</td>
                  <td style={tdStyle}>{d.target_name}</td>
                  <td style={tdStyle}><Badge tone={d.status === "accepted" ? "warn" : "info"} size="sm">{STATUS_ZH[d.status] || d.status}</Badge></td>
                  <td style={tdStyle}>
                    {d.status === "accepted" && (
                      <Button size="sm" onClick={() => setApproving(d)}>核准生效</Button>
                    )}
                    {d.status !== "accepted" && <span style={{ color: "var(--text-muted)", fontSize: 12 }}>需雙方 CEO 確認</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10 }}><RefreshBtn onClick={load} /></div>
      </Panel>
      {approving && (
        <Confirm
          title={`核准「${approving.proposer_name}」併購「${approving.target_name}」`}
          body="核准後股份合併、公司帳戶整合、被併隊伍標記 merged。此操作不可逆，請確認雙方 CEO 均已同意。"
          onConfirm={doApprove}
          onCancel={() => setApproving(null)}
        />
      )}
    </div>
  );
}

// ═══════════════ 分頁 7：資金總表 ════════════════════════
function TabEconomy() {
  const [eco, setEco] = React.useState(null);
  const [orders, setOrders] = React.useState(null);

  const load = () => {
    api("/api/admin/economy").then(setEco).catch((e) => alert(e.message));
    api("/api/admin/investments").then((d) => setOrders(d.orders)).catch((e) => alert(e.message));
  };
  React.useEffect(() => { load(); }, []);

  return (
    <div>
      <SectionTitle eyebrow="ECONOMY" align="left" size="h2" subtitle="各隊資金狀況＋投資明細（12:30 上大螢幕前核對）">資金總表</SectionTitle>
      <Panel header="各隊總覽" style={{ marginBottom: 16 }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 700 }}>
            <thead>
              <tr>{["隊名","餘額","Pre-A","A 輪","押注(鎖)","得票"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {((eco && eco.teams) || []).map((t) => (
                <tr key={t.id} style={{ opacity: t.status !== "active" ? .5 : 1 }}>
                  <td style={{ ...tdStyle, fontWeight: 700, color: "var(--gold-100,#f2ead2)" }}>
                    {t.name}
                    {t.merged_from && t.merged_from.length > 0 && <Badge tone="warn" size="sm" style={{ marginLeft: 6 }}>已併</Badge>}
                  </td>
                  <td style={tdStyle}>{W(t.balance)}</td>
                  <td style={tdStyle}>{W(t.pre_a)}</td>
                  <td style={tdStyle}>{W(t.a_round)}</td>
                  <td style={tdStyle}>{W(t.bets_out)}</td>
                  <td style={tdStyle}>{t.votes}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {eco && <div style={{ marginTop: 10, fontSize: 12, color: "var(--text-muted)" }}>個人錢包合計：{W(eco.person_total)}　Escrow：{W(eco.escrow_balance)}</div>}
        <div style={{ marginTop: 10 }}><RefreshBtn onClick={load} /></div>
      </Panel>

      <Panel header={`投資明細（${orders ? orders.length : "…"} 筆）`}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
            <thead>
              <tr>{["投資人","類型","隊伍","輪次","金額","狀態"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {(orders || []).map((o) => (
                <tr key={o.id} style={{ opacity: o.status === "active" ? 1 : .4 }}>
                  <td style={tdStyle}>{o.investor_name}</td>
                  <td style={tdStyle}>{o.investor_type}</td>
                  <td style={{ ...tdStyle, color: "var(--gold-200)" }}>{o.team_name}</td>
                  <td style={tdStyle}><Badge tone="info" size="sm">{o.round}</Badge></td>
                  <td style={{ ...tdStyle, fontFamily: "monospace" }}>{W(o.amount)}</td>
                  <td style={tdStyle}><Badge tone={o.status === "active" ? "success" : "default"} size="sm">{o.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Panel>
    </div>
  );
}

// ═══════════════ 分頁 8：結算 ════════════════════════════
const CSV_TABLES = ["transactions","investments","bets","scores","votes","cap_tables","settlement_input"];

function TabSettle() {
  const [result, setResult] = React.useState(null);
  const [runId, setRunId] = React.useState(null);
  const [snapping, setSnapping] = React.useState(false);
  const [commitConfirm, setCommitConfirm] = React.useState(false);

  const doSnapshot = async () => {
    setSnapping(true);
    try {
      const r = await api("/api/admin/snapshot", { method: "POST" });
      alert("快照完成！" + JSON.stringify(r.snapshot).slice(0, 80) + "…");
    } catch (e) { alert(e.message); }
    setSnapping(false);
  };

  const doDryRun = async () => {
    try {
      const r = await api("/api/admin/settle", { method: "POST" });
      setResult(r.result);
      setRunId(r.run_id);
    } catch (e) { alert(e.message); }
  };

  const doCommit = async () => {
    setCommitConfirm(false);
    try {
      await api(`/api/admin/settle/${runId}/commit`, { method: "POST" });
      alert("結算已正式 Commit！Run #" + runId);
    } catch (e) { alert(e.message); }
  };

  const rec = result && result.reconciliation;
  const allGreen = rec && rec.supply_check_pass && rec.personal_check_pass;

  return (
    <div>
      <SectionTitle eyebrow="SETTLEMENT" align="left" size="h2" subtitle="快照→Dry-run→確認→Commit">結算</SectionTitle>

      {result && result.warnings && result.warnings.length > 0 && (
        <div style={{ margin: "0 0 14px", padding: "12px 16px", background: "rgba(224,122,106,.12)", border: "1px solid rgba(224,122,106,.4)", borderRadius: 8 }}>
          <div style={{ fontSize: 12, color: "var(--danger,#e07a6a)", fontWeight: 700, marginBottom: 6 }}>⚠ 結算警告（請在 Commit 前修正）</div>
          {result.warnings.map((w, i) => <div key={i} style={{ fontSize: 12, color: "var(--text-secondary)", marginTop: 4 }}>{w}</div>)}
        </div>
      )}

      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 16 }}>
        <Button size="sm" onClick={doSnapshot} disabled={snapping}>資產快照</Button>
        <Button size="sm" onClick={doDryRun}>結算 Dry-run</Button>
      </div>

      {result && (
        <div>
          <Panel header="Dry-run 結果" style={{ marginBottom: 14 }}>
            {rec && (
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 6, letterSpacing: ".08em" }}>軋帳結果</div>
                <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                  {[
                    ["Supply 平衡", rec.supply_check_pass],
                    ["個人清算平衡", rec.personal_check_pass],
                  ].map(([label, ok]) => (
                    <div key={label} style={{ padding: "8px 14px", borderRadius: 6, background: ok ? "rgba(127,201,127,.12)" : "rgba(224,122,106,.12)", border: `1px solid ${ok ? "rgba(127,201,127,.4)" : "rgba(224,122,106,.4)"}`, fontSize: 13 }}>
                      <span style={{ color: ok ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)" }}>{ok ? "✓" : "✗"} {label}</span>
                    </div>
                  ))}
                </div>
                {rec.wallet_total != null && <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 8 }}>Wallet Total: {toW(rec.wallet_total)}萬　Supply: {toW(rec.total_supply || 0)}萬　Delta: {rec.supply_delta ?? "—"}</div>}
              </div>
            )}

            {result.exits && result.exits.length > 0 && (
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 12, color: "var(--gold-300)", marginBottom: 6 }}>出場排名</div>
                {result.exits.map((e, i) => (
                  <div key={i} style={{ fontSize: 13, padding: "3px 0", color: "var(--text-secondary)" }}>
                    {i + 1}. {e.team_name} — {W(e.liquidation_value)} {e.exit_tier ? `[${e.exit_tier}]` : ""}
                  </div>
                ))}
              </div>
            )}

            {result.medals && (
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 12, color: "var(--gold-300)", marginBottom: 6 }}>獎項</div>
                {result.medals.map((m, i) => <div key={i} style={{ fontSize: 13, color: "var(--gold-200)" }}>{m.label}: {m.team_name}</div>)}
                {result.growth_award && <div style={{ fontSize: 13, color: "var(--text-secondary)" }}>成長獎: {result.growth_award.team_name}</div>}
                {result.popular_award && <div style={{ fontSize: 13, color: "var(--text-secondary)" }}>人氣獎: {result.popular_award.team_name}</div>}
              </div>
            )}

            {allGreen ? (
              <div style={{ marginTop: 16 }}>
                <Button onClick={() => setCommitConfirm(true)}>正式 Commit 結算（Run #{runId}）</Button>
              </div>
            ) : (
              <div style={{ marginTop: 12, fontSize: 13, color: "var(--danger,#e07a6a)" }}>軋帳未全綠，請先排查再 commit。</div>
            )}
          </Panel>
        </div>
      )}

      <Panel header="CSV 匯出">
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 4 }}>
          {CSV_TABLES.map((t) => (
            <a key={t} href={`/api/admin/export/csv?table=${t}`} download style={{ display: "inline-block", padding: "6px 12px", borderRadius: 6, background: "var(--navy-850)", border: "1px solid rgba(212,175,55,.25)", color: "var(--gold-300)", fontSize: 12, textDecoration: "none" }}>{t}</a>
          ))}
        </div>
      </Panel>

      {commitConfirm && (
        <Confirm
          title={`正式 Commit 結算 Run #${runId}`}
          body="此操作不可逆：寫入 bet_payout/bet_forfeit/liquidation 交易，原先結果將被沖銷。確認軋帳已全綠再執行。"
          onConfirm={doCommit}
          onCancel={() => setCommitConfirm(false)}
        />
      )}
    </div>
  );
}

// ═══════════════ 分頁 9：揭曉 ════════════════════════════
function TabReveal() {
  const [board, setBoard] = React.useState(null);
  const [teams, setTeams] = React.useState(null);
  const [form, setForm] = React.useState({ mode: "blind", current_team_id: "", countdown_target: "" });

  const load = () => {
    api("/api/admin/board").catch(() => {}).then(() => {});
    api("/api/admin/settle/latest").then((d) => setBoard(d)).catch(() => {});
    api("/api/admin/startup-teams").then(setTeams).catch(() => {});
  };
  React.useEffect(() => { load(); }, []);

  const sendBoard = async (patch) => {
    try {
      await api("/api/admin/board", { method: "POST", body: patch });
      load();
    } catch (e) { alert(e.message); }
  };

  const step = board && board.result && board.result.reveal_sequence ? board.result.reveal_sequence.length : 0;

  return (
    <div>
      <SectionTitle eyebrow="REVEAL" align="left" size="h2" subtitle="控制大螢幕揭曉模式">揭曉控制</SectionTitle>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
        <Panel header="模式切換">
          <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
            <Button size="sm" onClick={() => sendBoard({ mode: "blind" })}>盲模式</Button>
            <Button size="sm" onClick={() => sendBoard({ mode: "reveal" })}>揭曉模式</Button>
          </div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>Pitch 進行中隊伍</div>
            <select style={{ ...inputStyle, width: "100%" }} value={form.current_team_id} onChange={(e) => {
              const v = e.target.value;
              setForm({ ...form, current_team_id: v });
              sendBoard({ current_team_id: Number(v) || "" });
            }}>
              <option value="">— 無 —</option>
              {(teams || []).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
          </div>

          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>倒數目標時間</div>
            <input type="datetime-local" style={{ ...inputStyle, width: "100%" }}
              value={form.countdown_target}
              onChange={(e) => setForm({ ...form, countdown_target: e.target.value })}
              onBlur={() => sendBoard({ countdown_target: form.countdown_target })}
            />
          </div>
        </Panel>

        <Panel header="逐步揭曉控制">
          <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 10 }}>
            {board ? `步驟：官方結算共 ${step} 步` : "尚無官方結算"}
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <Button size="sm" onClick={() => sendBoard({ step: Math.max(0, (board && board.run_id ? (Number((board.result && board.result.reveal_sequence && 0) || 0)) : 0) - 1) })} variant="ghost">← 上一步</Button>
            <Button size="sm" onClick={() => sendBoard({ step: (step || 0) + 1 })}>下一步 →</Button>
          </div>
          {board && board.result && board.result.reveal_sequence && (
            <div style={{ marginTop: 12 }}>
              <Button size="sm" variant="ghost" onClick={() => {
                api("/api/admin/settle/latest").then((d) => {
                  const cur = Number(d.result && d.result.board_step_cur) || 0;
                  sendBoard({ step: cur - 1 });
                }).catch(() => {});
              }}>重載 step</Button>
            </div>
          )}
        </Panel>
      </div>
    </div>
  );
}

// ═══════════════ 分頁 10：審計 ════════════════════════════
function TabAudit() {
  const [logs, setLogs] = React.useState(null);
  const [form, setForm] = React.useState({ owner_type: "company", team_id: "", account_id: "", amount: "", reason: "" });
  const [teams, setTeams] = React.useState(null);
  const [users, setUsers] = React.useState(null);

  const load = () => {
    api("/api/admin/audit").then(setLogs).catch((e) => alert(e.message));
    api("/api/admin/startup-teams").then(setTeams).catch(() => {});
    api("/api/admin/users").then(setUsers).catch(() => {});
  };
  React.useEffect(() => { load(); }, []);

  const doAdjust = async () => {
    if (!form.amount || !form.reason.trim()) return alert("金額與原因必填");
    if (form.owner_type === "company" && !form.team_id) return alert("請選隊伍");
    if (form.owner_type === "person" && !form.account_id) return alert("請選帳號");
    try {
      const body = { owner_type: form.owner_type, amount: Number(form.amount), reason: form.reason };
      if (form.owner_type === "company") body.team_id = Number(form.team_id);
      else body.account_id = Number(form.account_id);
      const r = await api("/api/admin/adjust", { method: "POST", body });
      alert("改帳完成。新餘額：" + r.balance.toLocaleString() + " 元");
      setForm({ owner_type: "company", team_id: "", account_id: "", amount: "", reason: "" });
      load();
    } catch (e) { alert(e.message); }
  };

  return (
    <div>
      <SectionTitle eyebrow="AUDIT" align="left" size="h2" subtitle="審計日誌＋admin 改帳">審計</SectionTitle>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 16, marginBottom: 16 }}>
        <Panel header="改帳（留審計紀錄）">
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>對象類型</div>
            <select style={{ ...inputStyle, width: "100%" }} value={form.owner_type} onChange={(e) => setForm({ ...form, owner_type: e.target.value, team_id: "", account_id: "" })}>
              <option value="company">公司（創業隊）</option>
              <option value="person">個人</option>
            </select>
          </div>

          {form.owner_type === "company" && (
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>選隊伍</div>
              <select style={{ ...inputStyle, width: "100%" }} value={form.team_id} onChange={(e) => setForm({ ...form, team_id: e.target.value })}>
                <option value="">— 選創業隊 —</option>
                {(teams || []).map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
              </select>
            </div>
          )}
          {form.owner_type === "person" && (
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>選帳號</div>
              <select style={{ ...inputStyle, width: "100%" }} value={form.account_id} onChange={(e) => setForm({ ...form, account_id: e.target.value })}>
                <option value="">— 選人員 —</option>
                {(users || []).map((u) => <option key={u.id} value={u.id}>{ROLE_ZH[u.role] || u.role} {u.display_name} ({u.username})</option>)}
              </select>
            </div>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 10, marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>金額（元，可負）</div>
              <input type="number" style={{ ...inputStyle, width: "100%" }} value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} placeholder="例：100000" />
            </div>
            <div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>原因（必填，留稽核紀錄）</div>
              <input style={{ ...inputStyle, width: "100%" }} value={form.reason} onChange={(e) => setForm({ ...form, reason: e.target.value })} placeholder="例：天使包輸入錯誤補正" />
            </div>
          </div>
          <Button size="sm" onClick={doAdjust}>執行改帳</Button>
        </Panel>
      </div>

      <Panel header={`審計日誌（最新 ${logs ? logs.length : "…"} 筆）`}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12, minWidth: 600 }}>
            <thead>
              <tr>{["時間","操作者","動作","明細"].map((h) => <th key={h} style={thStyle}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {(logs || []).map((l) => (
                <tr key={l.id}>
                  <td style={{ ...tdStyle, fontFamily: "monospace", whiteSpace: "nowrap", fontSize: 11 }}>{l.created_at}</td>
                  <td style={{ ...tdStyle, fontFamily: "monospace" }}>{l.actor}</td>
                  <td style={tdStyle}><Badge tone="info" size="sm">{l.action}</Badge></td>
                  <td style={{ ...tdStyle, maxWidth: 320, whiteSpace: "normal", fontSize: 11 }}>{typeof l.detail === "string" ? l.detail.slice(0, 200) : JSON.stringify(l.detail || {}).slice(0, 200)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10 }}><RefreshBtn onClick={load} /></div>
      </Panel>
    </div>
  );
}

// ═══════════════ 頂部階段資訊條 ══════════════════════════
function PhaseHeader() {
  const [info, setInfo] = React.useState(null);
  React.useEffect(() => {
    api("/api/phase").then(setInfo).catch(() => {});
  }, []);
  if (!info) return null;
  const idx = PHASES.indexOf(info.phase);
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 4, letterSpacing: ".1em" }}>目前階段</div>
      <div style={{ fontSize: 28, fontWeight: 700, color: "var(--gold-300)", marginBottom: 12 }}>
        {PHASE_LABELS[info.phase] || info.phase}
        <span style={{ fontSize: 12, fontFamily: "monospace", color: "var(--text-muted)", marginLeft: 10 }}>{info.phase}</span>
      </div>
      <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
        {PHASES.map((ph, i) => (
          <div key={ph} style={{
            padding: "4px 8px", borderRadius: 4, fontSize: 11,
            background: i < idx ? "rgba(127,201,127,.12)" : i === idx ? "var(--grad-gold)" : "rgba(255,255,255,.04)",
            color: i === idx ? "var(--navy-950)" : i < idx ? "var(--success,#7fc97f)" : "var(--text-muted)",
            border: `1px solid ${i === idx ? "transparent" : "rgba(212,175,55,.15)"}`,
            fontWeight: i === idx ? 700 : 400,
          }}>{i + 1}.{PHASE_LABELS[ph]}</div>
        ))}
      </div>
    </div>
  );
}

// ═══════════════ 主元件 ══════════════════════════════════
const TABS = [
  { id: "phase",   label: "階段" },
  { id: "users",   label: "人員" },
  { id: "day1",    label: "Day1 賽程" },
  { id: "teamup",  label: "組隊" },
  { id: "angel",   label: "天使" },
  { id: "ma",      label: "併購" },
  { id: "economy", label: "資金總表" },
  { id: "settle",  label: "結算" },
  { id: "reveal",  label: "揭曉" },
  { id: "audit",   label: "審計" },
];

function AdminGame({ me }) {
  const [tab, setTab] = React.useState("phase");

  const content = {
    phase:   <TabPhase me={me} />,
    users:   <TabUsers />,
    day1:    <TabDay1 />,
    teamup:  <TabTeamUp />,
    angel:   <TabAngel />,
    ma:      <TabMA />,
    economy: <TabEconomy />,
    settle:  <TabSettle />,
    reveal:  <TabReveal />,
    audit:   <TabAudit />,
  };

  return (
    <div>
      {me && me.admin_readonly && (
        <div style={{ margin: "0 0 14px", padding: "10px 16px", borderRadius: 8, border: "1px solid rgba(232,176,75,.5)", background: "rgba(232,176,75,.10)", color: "var(--gold-300)", fontSize: 13, letterSpacing: ".04em" }}>
          👁 唯讀模式——你是戰情控制台 leader 直登：所有資料可查看，但操作（切階段/建帳/結算/改帳等）會被系統拒絕，需要時請找控台官。
        </div>
      )}
      <PhaseHeader />
      <div style={{ marginBottom: 18, overflowX: "auto" }}>
        <Tabs items={TABS} value={tab} onChange={setTab} variant="underline" />
      </div>
      {content[tab]}
    </div>
  );
}

window.AdminGame = AdminGame;
})();
