// 導師：輔導團隊 dashboard（唯讀）
(() => {
const { Panel, Badge, Button, ProgressBar, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const fmtWan = (n) => (n / 10000).toLocaleString() + " 萬";

function ContentModal({ teamId, onClose }) {
  const [data, setData] = React.useState(null);
  React.useEffect(() => { api(`/api/mentor/teams/${teamId}/content`).then(setData).catch(() => {}); }, [teamId]);
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(5,7,15,.8)", overflow: "auto", padding: "40px 16px" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 860, margin: "0 auto", background: "var(--navy-900)", border: "1px solid var(--gold-700)", borderRadius: 10, padding: "24px 28px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <div style={{ fontFamily: '"Noto Serif TC",serif', fontWeight: 900, fontSize: 20, color: "var(--gold-300)" }}>
            {data ? data.team_name : ""} · 關卡內容（唯讀）
          </div>
          <Button variant="ghost" onClick={onClose}>關閉</Button>
        </div>
        {!data ? <div style={{ color: "var(--text-muted)", padding: 30, textAlign: "center" }}>載入中…</div> :
          data.modules.map((m) => (
            <div key={m.id} style={{ marginBottom: 20 }}>
              <div style={{ color: "var(--gold-500)", fontWeight: 700, letterSpacing: ".08em", borderBottom: "1px solid var(--border-default)", paddingBottom: 6, marginBottom: 8 }}>
                {m.id}. {m.title} <span style={{ fontSize: 11, color: "var(--text-muted)", fontFamily: "Cinzel,serif" }}>{m.en}</span>
              </div>
              {m.fields.map((f) => (
                <div key={f.id} style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 2 }}>
                    {f.label}{f.fact_status ? <span style={{ marginLeft: 6, color: "var(--gold-300)" }}>〔{f.fact_status}〕</span> : null}
                  </div>
                  <div style={{ fontSize: 13.5, color: f.value ? "var(--text-primary)" : "var(--text-muted)", whiteSpace: "pre-wrap", background: "rgba(5,7,15,.5)", borderRadius: 6, padding: "8px 10px" }}>
                    {f.value || "（未填）"}
                  </div>
                </div>
              ))}
            </div>
          ))}
      </div>
    </div>
  );
}

function TeamCard({ t }) {
  const [showContent, setShowContent] = React.useState(false);
  const done = t.modules.filter((m) => m.status === "complete" || m.status === "locked").length;
  return (
    <Panel header={t.name + (t.sponsor_topic ? " · " + t.sponsor_topic : "")}>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 12 }}>
        {t.status === "merged" && <Badge tone="neutral">已併購</Badge>}
        {t.merged_from.length > 0 && <Badge tone="gold">併購存續隊</Badge>}
        {t.submitted_at ? <Badge tone="gold">已提交 {String(t.submitted_at).slice(5, 16)}</Badge> : <Badge tone="neutral">未提交</Badge>}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", letterSpacing: ".1em" }}>公司帳戶</div>
          <div style={{ fontSize: 22, color: "var(--gold-300)", fontWeight: 700 }}>{fmtWan(t.balance)}</div>
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", letterSpacing: ".1em" }}>AI 出擊</div>
          <div style={{ fontSize: 22, color: "var(--text-primary)", fontWeight: 700 }}>{t.ai_calls} <span style={{ fontSize: 12, color: "var(--text-muted)" }}>次</span></div>
        </div>
        <div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", letterSpacing: ".1em" }}>能量核心</div>
          <div style={{ fontSize: 22, color: "var(--text-primary)", fontWeight: 700 }}>
            {t.energy.active ? t.energy.active.remaining_pct + "%" : "耗盡"}
            <span style={{ fontSize: 12, color: "var(--text-muted)" }}>（共 {t.energy.cores_total} 顆）</span>
          </div>
        </div>
      </div>
      <div style={{ marginBottom: 12 }}>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
          <span>關卡進度</span><span>{done}/10</span>
        </div>
        <ProgressBar value={done} max={10} />
      </div>
      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 11, color: "var(--text-muted)", letterSpacing: ".1em", marginBottom: 6 }}>成員</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {t.members.map((m, i) => (
            <Badge key={i} tone="neutral">{m.position || "—"}｜{m.display_name}{m.dept ? "（" + m.dept + "）" : ""}</Badge>
          ))}
        </div>
      </div>
      {t.captable && (
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, color: "var(--text-muted)", letterSpacing: ".1em", marginBottom: 6 }}>股權</div>
          {t.captable.map((e, i) => (
            <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, padding: "3px 0", borderBottom: "1px solid rgba(212,175,55,.08)" }}>
              <span style={{ color: "var(--text-secondary)" }}>{e.name}{e.position ? "（" + e.position + "）" : ""}</span>
              <span style={{ color: "var(--gold-300)", fontWeight: 700 }}>{e.pct}%</span>
            </div>
          ))}
        </div>
      )}
      <Button onClick={() => setShowContent(true)}>查看關卡內容</Button>
      {showContent && <ContentModal teamId={t.id} onClose={() => setShowContent(false)} />}
    </Panel>
  );
}

function MentorDash({ me }) {
  const [teams, setTeams] = React.useState(null);
  React.useEffect(() => {
    api("/api/mentor/teams").then(setTeams).catch(() => setTeams([]));
    const iv = setInterval(() => api("/api/mentor/teams").then(setTeams).catch(() => {}), 30000);
    return () => clearInterval(iv);
  }, []);
  return (
    <div style={{ maxWidth: 1080, margin: "0 auto" }}>
      <SectionTitle eyebrow="MENTOR" align="left" size="h2" subtitle={"導師：" + (me.display_name || "")}>輔導團隊</SectionTitle>
      {!teams ? (
        <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center", letterSpacing: ".15em" }}>載入中…</div>
      ) : teams.length === 0 ? (
        <Panel header="尚未指派輔導團隊">
          <div style={{ color: "var(--text-muted)", padding: "24px 0", textAlign: "center" }}>
            組隊（team_up）階段由控台官配位後，這裡會出現你輔導的隊伍。<br />
            投資功能請走左側「投資下單」。
          </div>
        </Panel>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(340px, 1fr))", gap: 18, marginTop: 16 }}>
          {teams.map((t) => <TeamCard key={t.id} t={t} />)}
        </div>
      )}
    </div>
  );
}

window.MentorDash = MentorDash;
})();
