// Pitch 組裝台 — 大綱預覽 / AI 組裝 / 唯讀連結 / 最終提交鎖定
(() => {
const { Panel, Badge, Button, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

function Pitch() {
  const [m9, setM9] = React.useState(null);
  const [fields, setFields] = React.useState({});
  const [locked, setLocked] = React.useState(false);
  const [share, setShare] = React.useState(null);
  const [aiBusy, setAiBusy] = React.useState(false);
  const [aiResult, setAiResult] = React.useState(null);
  const [aiErr, setAiErr] = React.useState("");

  const load = () => {
    if (!window._modulesCache) window._modulesCache = api("/api/content/modules");
    window._modulesCache.then((ms) => setM9(ms.find((x) => x.id === 9)));
    api("/api/team/module/9").then((d) => { setFields(d.fields || {}); setLocked(d.status === "locked"); });
  };
  React.useEffect(() => { load(); }, []);

  const runAi = async (taskType) => {
    setAiBusy(true); setAiErr(""); setAiResult(null);
    try {
      const r = await api("/api/ai/run", {
        method: "POST",
        body: { module_id: 9, task_type: taskType, client_nonce: (crypto.randomUUID ? crypto.randomUUID() : String(Date.now() + Math.random())) },
      });
      setAiResult(r);
    } catch (e) { setAiErr(e.message); }
    setAiBusy(false);
  };

  const onAdopted = () => api("/api/team/module/9").then((d) => setFields(d.fields || {}));

  const makeShare = async () => {
    const r = await api("/api/team/share", { method: "POST" });
    const url = location.origin + r.url;
    setShare(url);
    try { await navigator.clipboard.writeText(url); } catch {}
  };

  const submit = async () => {
    if (!confirm("最終提交後，全部十關將鎖定為唯讀，評審看到的就是這一版。確定提交？")) return;
    try { await api("/api/team/submit", { method: "POST" }); load(); } catch (e) { alert(e.message); }
  };

  const reopen = async () => {
    const reason = prompt("重新開啟會解除鎖定並留下紀錄。請寫原因：");
    if (!reason) return;
    try { await api("/api/team/reopen", { method: "POST", body: { reason } }); load(); } catch (e) { alert(e.message); }
  };

  if (!m9) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>組裝台啟動中…</div>;

  const filledCount = m9.fields.filter((f) => fields[f.id] && fields[f.id].value && fields[f.id].value.trim()).length;

  return (
    <div>
      <SectionTitle eyebrow="FINAL TRIAL" align="left" size="h2" subtitle="讓評審在七分鐘內相信你們走過的每一步">Pitch 組裝台</SectionTitle>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start", marginTop: 18 }} className="sq-pitch-grid">
        {/* 左：大綱 */}
        <Panel header={`Pitch 大綱（${filledCount}/${m9.fields.length} 段）`}>
          {locked && (
            <div style={{ border: "1px solid var(--info,#4db6e8)", borderRadius: 6, padding: "8px 12px", marginBottom: 14, color: "var(--info,#4db6e8)", fontSize: 13, background: "rgba(77,182,232,.08)" }}>
              ⛨ 已最終提交——此為評審看到的版本
            </div>
          )}
          {m9.fields.map((f, i) => {
            const v = fields[f.id] && fields[f.id].value ? fields[f.id].value.trim() : "";
            return (
              <div key={f.id} style={{ marginBottom: 14, borderLeft: "2px solid " + (v ? "var(--gold-500)" : "rgba(212,175,55,.2)"), paddingLeft: 12 }}>
                <div style={{ display: "flex", gap: 8, alignItems: "baseline", marginBottom: 3 }}>
                  <span style={{ fontFamily: "Cinzel,serif", fontSize: 11, color: "var(--gold-500)" }}>{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ fontWeight: 700, fontSize: 14, color: "var(--gold-100,#f2ead2)" }}>{f.label}</span>
                </div>
                <div style={{ fontSize: 13, lineHeight: 1.8, whiteSpace: "pre-wrap", color: v ? "var(--text-secondary)" : "var(--text-muted)" }}>
                  {v || "（未填——到第 9 關填寫，或用右側 AI 組裝草稿）"}
                </div>
              </div>
            );
          })}
          <div style={{ marginTop: 6 }}>
            <a href="#/quests/9" style={{ fontSize: 13 }}>→ 到第 9 關編輯各段內容</a>
          </div>
        </Panel>

        {/* 右：行動 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Panel header="AI 組裝" glow={!locked}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.7, marginBottom: 10 }}>
              AI 只會用你們各關卡「實際填寫」的內容組裝草稿；素材不足的段落會直說缺什麼。
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <Button size="sm" disabled={aiBusy || locked} onClick={() => runAi("pitch")}>Pitch 組裝（約 5–8%）</Button>
              <Button size="sm" variant="ghost" disabled={aiBusy || locked} onClick={() => runAi("crosscheck")}>先做跨關卡一致性檢查（約 5–8%）</Button>
            </div>
            {aiBusy && <div style={{ textAlign: "center", padding: "16px 0", color: "var(--gold-300)", fontSize: 13, letterSpacing: ".2em" }}>◆ 組裝中… ◆</div>}
            {aiErr && <div style={{ color: "var(--danger,#e07a6a)", fontSize: 13, marginTop: 10, lineHeight: 1.7 }}>{aiErr}</div>}
            {aiResult && (
              <div style={{ marginTop: 12, borderTop: "1px solid rgba(212,175,55,.2)", paddingTop: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                  <Badge tone="gold" size="sm">{aiResult.task_label}{aiResult.mock ? "（測試模式）" : ""}</Badge>
                  <span style={{ fontSize: 11, color: "var(--text-muted)" }}>消耗 {aiResult.wau_charged} WAU</span>
                </div>
                <window.AiPayload payload={aiResult.payload} requestId={aiResult.request_id} module={m9} onAdopted={onAdopted} />
              </div>
            )}
          </Panel>

          <Panel header="評審連結">
            <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.7, marginBottom: 10 }}>
              唯讀成果頁，給導師與評審。提交前顯示即時內容；提交後固定為鎖定版本。
            </div>
            <Button size="sm" variant="ghost" onClick={makeShare}>產生／複製連結</Button>
            {share && <div style={{ fontSize: 11, color: "var(--success,#7fc97f)", marginTop: 8, wordBreak: "break-all" }}>已複製：{share}</div>}
          </Panel>

          <Panel header="最終提交" glow={locked}>
            {locked ? (
              <div>
                <Badge tone="info">已鎖定</Badge>
                <div style={{ fontSize: 12, color: "var(--text-muted)", margin: "10px 0" }}>十關已鎖定為唯讀。需要修改？</div>
                <Button size="sm" variant="ghost" onClick={reopen}>重新開啟（須留原因）</Button>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.7, marginBottom: 10 }}>
                  提交後十關全部鎖定，評審連結固定為此版本。
                </div>
                <Button size="sm" onClick={submit}>最終提交 · 鎖定</Button>
              </div>
            )}
          </Panel>
        </div>
      </div>
      <style>{`
        @media (max-width: 980px) { .sq-pitch-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

window.Pitch = Pitch;
})();
