// Gate — 關主 九域試煉輸入（手機優先，大按鈕單欄）
(() => {
const { Panel, Badge, Button, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const MAX_ROUNDS = 8;
const MAX_COURTS = 5;

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 Gate({ me }) {
  const [phase, setPhase] = React.useState(null);
  const [round, setRound] = React.useState(null);
  const [court, setCourt] = React.useState(null);
  const [teams, setTeams] = React.useState([]);
  const [matches, setMatches] = React.useState([]);
  const [gameWin, setGameWin] = React.useState(0);
  const [teamA, setTeamA] = React.useState(null);
  const [teamB, setTeamB] = React.useState(null);
  const [winner, setWinner] = React.useState(null);
  const [confirm, setConfirm] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [msg, setMsg] = React.useState(null);

  // 輪詢 phase
  React.useEffect(() => {
    const load = () => api("/api/phase").then((d) => setPhase(d.phase)).catch(() => {});
    load();
    const t = setInterval(load, 10000);
    return () => clearInterval(t);
  }, []);

  // 載入該輪比賽
  const loadRound = (r) => {
    setRound(r);
    setCourt(null);
    setTeamA(null);
    setTeamB(null);
    setWinner(null);
    api(`/api/gate/matches?round=${r}`)
      .then((d) => {
        setTeams(d.teams || []);
        setMatches(d.matches || []);
        setGameWin(d.game_win || 0);
      })
      .catch((e) => alert(e.message));
  };

  const isOpen = phase === "day1_game";
  const teamName = (id) => (teams.find((t) => t.id === id) || {}).name || "？";

  const submit = async () => {
    setLoading(true);
    try {
      await api("/api/gate/match", {
        method: "POST",
        body: { round, court, team_a: teamA, team_b: teamB, winner },
      });
      setMsg({ ok: true, text: `第 ${round} 輪第 ${court} 場已記錄。` });
      setConfirm(false);
      setCourt(null); setTeamA(null); setTeamB(null); setWinner(null);
      loadRound(round);
    } catch (e) {
      setConfirm(false);
      if (e.message && e.message.includes("已輸入過")) {
        setMsg({ ok: false, text: "已輸入過，找控台官改判。" });
      } else {
        setMsg({ ok: false, text: e.message });
      }
    } finally {
      setLoading(false);
    }
  };

  const bigBtnBase = {
    display: "flex", alignItems: "center", justifyContent: "center",
    borderRadius: 10, cursor: "pointer", fontWeight: 700, fontSize: 18,
    padding: "18px 0", border: "2px solid rgba(212,175,55,.35)",
    background: "rgba(212,175,55,.07)", color: "var(--gold-300)",
    transition: "background .15s, border-color .15s",
    userSelect: "none", width: "100%", boxSizing: "border-box",
  };
  const bigBtnSel = { ...bigBtnBase, background: "rgba(212,175,55,.25)", borderColor: "var(--gold-400)", color: "#fff" };
  const bigBtnDanger = { ...bigBtnBase, borderColor: "rgba(224,122,106,.5)", color: "var(--danger,#e07a6a)", background: "rgba(224,122,106,.1)" };
  const bigBtnDangerSel = { ...bigBtnDanger, background: "rgba(224,122,106,.25)", borderColor: "var(--danger,#e07a6a)", color: "#fff" };

  const step = !round ? 1 : !court ? 2 : (!teamA || !teamB) ? 3 : !winner ? 4 : 5;

  return (
    <div style={{ maxWidth: 560, margin: "0 auto", padding: "0 4px" }}>
      <SectionTitle eyebrow="GATE KEEPER" align="left" size="h2" subtitle="九域試煉比賽輸入">關主控台</SectionTitle>

      {!isOpen && (
        <div style={{ margin: "14px 0 10px", padding: "12px 16px", background: "rgba(224,122,106,.12)", borderRadius: 8, color: "var(--danger,#e07a6a)", fontSize: 13 }}>
          目前階段非試煉時段，提交按鈕已停用。當控台切換至試煉階段後自動開放。
        </div>
      )}

      {msg && (
        <div style={{ margin: "14px 0", padding: "12px 16px", borderRadius: 8,
          background: msg.ok ? "rgba(127,201,127,.12)" : "rgba(224,122,106,.12)",
          color: msg.ok ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)", fontSize: 14 }}>
          {msg.text}
          <span onClick={() => setMsg(null)} style={{ float: "right", cursor: "pointer", opacity: .6 }}>✕</span>
        </div>
      )}

      {/* Step 1 選輪次 */}
      <Panel header={`步驟 1 — 選輪次${round ? `（已選：第 ${round} 輪）` : ""}`}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
          {Array.from({ length: MAX_ROUNDS }, (_, i) => i + 1).map((r) => (
            <div key={r} style={round === r ? bigBtnSel : bigBtnBase} onClick={() => loadRound(r)}>
              {r}
            </div>
          ))}
        </div>
      </Panel>

      {round && (
        <Panel header={`步驟 2 — 選場地${court ? `（已選：第 ${court} 場）` : ""}`}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10 }}>
            {Array.from({ length: MAX_COURTS }, (_, i) => i + 1).map((c) => {
              const done = matches.find((m) => m.court === c);
              return (
                <div key={c}
                  style={done ? { ...bigBtnBase, opacity: .45 } : court === c ? bigBtnSel : bigBtnBase}
                  onClick={() => { setCourt(c); setTeamA(null); setTeamB(null); setWinner(null); }}>
                  {c}
                  {done && <br />}
                  {done && <span style={{ fontSize: 10, opacity: .7 }}>已輸</span>}
                </div>
              );
            })}
          </div>
        </Panel>
      )}

      {round && court && teams.length > 0 && (
        <Panel header="步驟 3 — 選對戰兩隊">
          <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 10 }}>點選 A 隊再點 B 隊，順序不影響結果</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {teams.map((t) => {
              const isA = teamA === t.id;
              const isB = teamB === t.id;
              const style = isA
                ? { ...bigBtnSel, fontSize: 15, padding: "14px 0" }
                : isB
                ? { ...bigBtnDangerSel, fontSize: 15, padding: "14px 0" }
                : { ...bigBtnBase, fontSize: 15, padding: "14px 0" };
              return (
                <div key={t.id} style={style} onClick={() => {
                  if (isA) { setTeamA(null); if (winner === t.id) setWinner(null); return; }
                  if (isB) { setTeamB(null); if (winner === t.id) setWinner(null); return; }
                  if (!teamA) { setTeamA(t.id); }
                  else if (!teamB && teamA !== t.id) { setTeamB(t.id); }
                }}>
                  {t.name}
                  {isA && <span style={{ marginLeft: 8, fontSize: 12, opacity: .7 }}>（A）</span>}
                  {isB && <span style={{ marginLeft: 8, fontSize: 12, opacity: .7 }}>（B）</span>}
                </div>
              );
            })}
          </div>
        </Panel>
      )}

      {round && court && teamA && teamB && (
        <Panel header="步驟 4 — 選勝方">
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[teamA, teamB].map((tid) => (
              <div key={tid}
                style={winner === tid
                  ? { ...bigBtnSel, fontSize: 16, padding: "20px 0", borderColor: "var(--gold-400)" }
                  : { ...bigBtnBase, fontSize: 16, padding: "20px 0" }}
                onClick={() => setWinner(tid)}>
                🏆 {teamName(tid)}
                {winner === tid && <span style={{ marginLeft: 8, fontSize: 13 }}>勝</span>}
              </div>
            ))}
          </div>
        </Panel>
      )}

      {round && court && teamA && teamB && winner && (
        <div style={{ marginTop: 16 }}>
          <Button
            disabled={!isOpen || loading}
            onClick={() => setConfirm(true)}
            style={{ width: "100%", fontSize: 16, padding: "16px 0" }}>
            確認送出
          </Button>
          {!isOpen && <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 6, textAlign: "center" }}>目前非試煉階段，暫停提交</div>}
        </div>
      )}

      {/* 確認彈層 */}
      {confirm && (
        <div onClick={() => setConfirm(false)}
          style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(5,7,15,.8)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: 380, maxWidth: "100%" }}>
            <Panel header="確認輸入" glow>
              <div style={{ fontSize: 16, lineHeight: 2, color: "var(--text-primary)", margin: "8px 0 16px" }}>
                <div>第 <strong>{round}</strong> 輪　第 <strong>{court}</strong> 場</div>
                <div>{teamName(teamA)} <span style={{ color: "var(--text-muted)" }}>vs</span> {teamName(teamB)}</div>
                <div>勝方：<strong style={{ color: "var(--gold-300)", fontSize: 18 }}>{teamName(winner)}</strong></div>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <Button onClick={submit} disabled={loading}>{loading ? "送出中…" : "確定送出"}</Button>
                <Button variant="ghost" onClick={() => setConfirm(false)}>取消</Button>
              </div>
            </Panel>
          </div>
        </div>
      )}

      {/* 本輪已輸場次 */}
      {round && matches.length > 0 && (
        <div style={{ marginTop: 20 }}>
          <Panel header={`第 ${round} 輪已輸場次（${matches.length}）`}>
            {matches.map((m) => {
              const a = teams.find((t) => t.id === m.team_a);
              const b = teams.find((t) => t.id === m.team_b);
              const w = teams.find((t) => t.id === m.winner);
              return (
                <div key={m.id} style={{ padding: "8px 4px", borderBottom: "1px solid rgba(212,175,55,.12)", fontSize: 13, color: "var(--text-secondary)", display: "flex", justifyContent: "space-between" }}>
                  <span>第 {m.court} 場：{a ? a.name : m.team_a} vs {b ? b.name : m.team_b}</span>
                  <span style={{ color: "var(--gold-300)", fontWeight: 700 }}>勝：{w ? w.name : m.winner}</span>
                </div>
              );
            })}
          </Panel>
        </div>
      )}
    </div>
  );
}

window.Gate = Gate;
})();
