// Score — 評審評分＋企業特別獎志願單
(() => {
const { Panel, Badge, Button, 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: "6px 8px", fontSize: 13, outline: "none", boxSizing: "border-box",
};

function ScoreCard({ team, dimensions, dimMax, onSaved }) {
  const [bd, setBd] = React.useState(() => {
    const init = {};
    for (const d of dimensions) init[d] = team.breakdown ? (team.breakdown[d] ?? 0) : 0;
    return init;
  });
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [saved, setSaved] = React.useState(false);

  const total = dimensions.reduce((s, d) => s + Number(bd[d] || 0), 0);

  const save = async () => {
    setSaving(true);
    setErr(null);
    try {
      await api("/api/scores", { method: "POST", body: { team_id: team.id, breakdown: bd } });
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      onSaved && onSaved();
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ padding: "14px 16px", borderRadius: 10, border: "1px solid rgba(212,175,55,.2)", background: "rgba(212,175,55,.04)", marginBottom: 12 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <span style={{ fontWeight: 700, color: "var(--gold-100,#f2ead2)", fontSize: 15 }}>{team.name}</span>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {team.scored && <Badge tone="info" size="sm">已評</Badge>}
          <span style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 16, color: "var(--gold-300)" }}>
            {total}
          </span>
          <span style={{ fontSize: 11, color: "var(--text-muted)" }}>/ {dimMax * dimensions.length}</span>
        </div>
      </div>
      {team.sponsor_topic && (
        <div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: 10 }}>{team.sponsor_topic}</div>
      )}

      {/* 各構面評分滑桿 */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 10, marginBottom: 12 }}>
        {dimensions.map((d) => {
          const val = Number(bd[d] || 0);
          return (
            <div key={d}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
                <span>{d}</span>
                <span style={{ color: "var(--gold-300)", fontWeight: 700 }}>{val} / {dimMax}</span>
              </div>
              {/* 滑桿 */}
              <input
                type="range" min={0} max={dimMax} step={1} value={val}
                onChange={(e) => setBd({ ...bd, [d]: Number(e.target.value) })}
                style={{ width: "100%", accentColor: "var(--gold-400,#c9a227)", cursor: "pointer" }}
              />
              {/* 數字微調 */}
              <input
                type="number" min={0} max={dimMax} value={val}
                onChange={(e) => {
                  const v = Math.max(0, Math.min(dimMax, Number(e.target.value) || 0));
                  setBd({ ...bd, [d]: v });
                }}
                style={{ ...inputStyle, width: "100%", marginTop: 4, textAlign: "center" }}
              />
            </div>
          );
        })}
      </div>

      {err && <div style={{ fontSize: 12, color: "var(--danger,#e07a6a)", marginBottom: 8 }}>{err}</div>}
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Button size="sm" onClick={save} disabled={saving}>{saving ? "儲存中…" : "儲存評分"}</Button>
        {saved && <span style={{ fontSize: 12, color: "var(--success,#7fc97f)" }}>已儲存 ✓</span>}
      </div>
    </div>
  );
}

function Score({ me }) {
  const [data, setData] = React.useState(null);
  const [phase, setPhase] = React.useState(null);
  const [prefs, setPrefs] = React.useState([null, null, null]); // 志願1/2/3
  const [prefSaving, setPrefSaving] = React.useState(false);
  const [prefMsg, setPrefMsg] = React.useState(null);

  const load = () => api("/api/scores/mine").then((d) => {
    setData(d);
    // 塞入已有的志願序
    const sp = d.special_pref || [];
    setPrefs([sp[0] || null, sp[1] || null, sp[2] || null]);
  }).catch((e) => alert(e.message));

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

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

  const isOpen = ["pitch", "bet_window"].includes(phase) || !phase;
  const teams = data.teams || [];
  const dims = data.dimensions || [];
  const dimMax = data.dimension_max || 10;

  const savePrefs = async () => {
    const ids = prefs.filter((x) => x !== null && x !== "").map(Number);
    if (ids.length === 0) { setPrefMsg({ ok: false, text: "請至少填一個志願" }); return; }
    // 不允許重複
    if (new Set(ids).size !== ids.length) { setPrefMsg({ ok: false, text: "志願序不能重複" }); return; }
    setPrefSaving(true);
    setPrefMsg(null);
    try {
      await api("/api/scores/special-pref", { method: "POST", body: { team_ids: ids } });
      setPrefMsg({ ok: true, text: "志願單已送出" });
      load();
    } catch (e) {
      setPrefMsg({ ok: false, text: e.message });
    } finally {
      setPrefSaving(false);
    }
  };

  const scored = teams.filter((t) => t.scored).length;

  return (
    <div style={{ maxWidth: 720, margin: "0 auto" }}>
      <SectionTitle eyebrow="JUDGE" align="left" size="h2" subtitle="Pitch 評分">評審評分</SectionTitle>

      <div style={{ margin: "10px 0 16px", padding: "12px 16px", background: "rgba(212,175,55,.08)", border: "1px solid rgba(212,175,55,.3)", borderRadius: 8, fontSize: 13, color: "var(--gold-200,#e8d5a3)", fontWeight: 600 }}>
        本場評分僅供參考評語，不進總分——總分 100% 由 A 輪投資構成（出題企業 40／其他企業 20／導師 20／來賓 20）
      </div>

      {!isOpen && (
        <div style={{ margin: "14px 0", padding: "12px 16px", background: "rgba(224,122,106,.12)", borderRadius: 8, color: "var(--danger,#e07a6a)", fontSize: 13 }}>
          目前非評分階段，評分功能暫停。Pitch 或 WCAX 認購窗口期開放。
        </div>
      )}

      <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "18px 0 12px" }}>
        <div style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 22, color: "var(--gold-300)" }}>{scored}</div>
        <div style={{ fontSize: 13, color: "var(--text-muted)" }}>/ {teams.length} 隊已評分</div>
        {scored === teams.length && teams.length > 0 && (
          <Badge tone="gold" size="sm">全部完成</Badge>
        )}
      </div>

      {/* 逐隊評分卡 */}
      {teams.map((t) => (
        <ScoreCard key={t.id} team={t} dimensions={dims} dimMax={dimMax} onSaved={load} />
      ))}

      {/* 企業特別獎志願單 */}
      <div style={{ marginTop: 24 }}>
        <Panel header="企業特別獎志願單">
          <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 14 }}>
            選出您希望獲得企業特別獎的隊伍（最多三個志願，依序排列）。可修改。
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 14 }}>
            {[0, 1, 2].map((idx) => (
              <div key={idx} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 48, fontSize: 13, color: "var(--gold-300)", flexShrink: 0, fontWeight: 700 }}>
                  志願 {idx + 1}
                </span>
                <select
                  style={{ ...inputStyle, flex: 1 }}
                  value={prefs[idx] ?? ""}
                  onChange={(e) => {
                    const np = [...prefs];
                    np[idx] = e.target.value === "" ? null : Number(e.target.value);
                    setPrefs(np);
                  }}>
                  <option value="">— 不填 —</option>
                  {teams.map((t) => (
                    <option key={t.id} value={t.id}>{t.name}</option>
                  ))}
                </select>
              </div>
            ))}
          </div>
          {prefMsg && (
            <div style={{ marginBottom: 10, fontSize: 13,
              color: prefMsg.ok ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)" }}>
              {prefMsg.text}
            </div>
          )}
          <Button size="sm" onClick={savePrefs} disabled={prefSaving}>
            {prefSaving ? "送出中…" : "送出志願單"}
          </Button>
        </Panel>
      </div>
    </div>
  );
}

window.Score = Score;
})();
