// 關卡工作區 — 左：知識卡｜中：輸入表單（autosave）｜右：AI 教練
(() => {
const { Panel, Badge, Button, ProgressBar } = window.WCATalentGameDesignSystem_377d00;

// 依 2026-07-19 真實校準（P50–P75，核心容量 100k WAU）
const COST_HINT = { explain: "約 1%", completeness: "約 2%", socratic: "3–4%", structure: "12–18%", challenge: "8–12%", next_step: "8–15%", crosscheck: "9–12%", pitch: "10–15%" };
const TASK_LABEL = {
  explain: "快速解釋", completeness: "完整度檢查", socratic: "蘇格拉底追問",
  structure: "結構化整理", challenge: "反方挑戰", next_step: "下一步建議",
  crosscheck: "跨關卡一致性", pitch: "Pitch 組裝",
};
const FACT_OPTIONS = ["事實為主", "含假設", "待驗證"];

// ---------- 小元件 ----------
function Collapsible({ title, children, defaultOpen = false, accent }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ border: "1px solid rgba(212,175,55,.18)", borderRadius: 6, marginBottom: 8, overflow: "hidden" }}>
      <button onClick={() => setOpen(!open)} style={{
        width: "100%", textAlign: "left", background: open ? "rgba(212,175,55,.08)" : "transparent",
        border: "none", color: accent || "var(--gold-300)", padding: "10px 12px", cursor: "pointer",
        fontSize: 13, fontWeight: 700, letterSpacing: ".05em", display: "flex", justifyContent: "space-between",
      }}>
        <span>{title}</span><span style={{ color: "var(--text-muted)" }}>{open ? "−" : "+"}</span>
      </button>
      {open && <div style={{ padding: "4px 12px 12px", fontSize: 13, lineHeight: 1.8, color: "var(--text-secondary)" }}>{children}</div>}
    </div>
  );
}

function SectionBlock({ title, color, children }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 11, letterSpacing: ".18em", color, fontWeight: 700, marginBottom: 5 }}>{title}</div>
      <div style={{ fontSize: 13, lineHeight: 1.8, color: "var(--text-secondary)" }}>{children}</div>
    </div>
  );
}

// ---------- AI 回覆渲染 ----------
function AiPayload({ payload, requestId, module, onAdopted }) {
  if (!payload) return null;
  const list = (arr) => (
    <ul style={{ margin: "4px 0", paddingLeft: 18 }}>{arr.map((x, i) => <li key={i} style={{ marginBottom: 4 }}>{typeof x === "string" ? x : JSON.stringify(x)}</li>)}</ul>
  );
  return (
    <div>
      {payload.understood && <SectionBlock title="◆ 我理解的內容" color="var(--gold-300)">{payload.understood}</SectionBlock>}
      {payload.evidence && payload.evidence.length > 0 && <SectionBlock title="◆ 已有證據" color="var(--success, #7fc97f)">{list(payload.evidence)}</SectionBlock>}
      {payload.assumptions && payload.assumptions.length > 0 && <SectionBlock title="◆ 仍是推測" color="var(--warning, #e0b04c)">{list(payload.assumptions)}</SectionBlock>}
      {payload.gaps && payload.gaps.length > 0 && <SectionBlock title="◆ 關鍵缺口／矛盾" color="var(--danger, #e07a6a)">{list(payload.gaps)}</SectionBlock>}
      {payload.questions && payload.questions.length > 0 && <SectionBlock title="◆ 教練的追問" color="var(--info, #4db6e8)">{list(payload.questions)}</SectionBlock>}
      {payload.next_steps && payload.next_steps.length > 0 && (
        <SectionBlock title="◆ 建議下一步" color="var(--gold-300)">
          <ol style={{ margin: "4px 0", paddingLeft: 18 }}>
            {payload.next_steps.map((s, i) => (
              <li key={i} style={{ marginBottom: 6 }}>
                {typeof s === "string" ? s : <span>{s.action}{s.why && <span style={{ color: "var(--text-muted)" }}>——{s.why}</span>}</span>}
              </li>
            ))}
          </ol>
        </SectionBlock>
      )}
      {payload.draft && payload.draft.length > 0 && (
        <SectionBlock title="◆ 建議寫入的草稿（採納才會生效）" color="var(--gold-300)">
          {payload.draft.map((d, i) => (
            <DraftCard key={i} draft={d} requestId={requestId} module={module} onAdopted={onAdopted} />
          ))}
        </SectionBlock>
      )}
      {payload.confidence && (
        <div style={{ fontSize: 12, color: "var(--text-muted)", borderTop: "1px solid rgba(212,175,55,.15)", paddingTop: 8 }}>
          信心：{payload.confidence.level}｜{payload.confidence.reason}
        </div>
      )}
    </div>
  );
}

function DraftCard({ draft, requestId, module, onAdopted }) {
  const [state, setState] = React.useState(""); // "" | "adopted" | "busy"
  const valid = module.fields.some((f) => f.id === draft.field_id);
  const adopt = async (mode) => {
    setState("busy");
    try {
      await api("/api/ai/adopt", { method: "POST", body: { request_id: requestId, field_id: draft.field_id, text: draft.content, mode } });
      setState("adopted");
      onAdopted && onAdopted(draft.field_id, mode, draft.content);
    } catch (e) { alert(e.message); setState(""); }
  };
  return (
    <div style={{ background: "var(--navy-950)", border: "1px solid rgba(212,175,55,.25)", borderRadius: 6, padding: "10px 12px", marginBottom: 8 }}>
      <div style={{ fontSize: 12, color: "var(--gold-300)", fontWeight: 700, marginBottom: 4 }}>→ {draft.field_label || draft.field_id}</div>
      <div style={{ fontSize: 13, whiteSpace: "pre-wrap", marginBottom: 8 }}>{draft.content}</div>
      {state === "adopted" ? (
        <Badge tone="success" size="sm">已採納</Badge>
      ) : valid ? (
        <div style={{ display: "flex", gap: 8 }}>
          <Button size="sm" disabled={state === "busy"} onClick={() => adopt("replace")}>採納（覆蓋）</Button>
          <Button size="sm" variant="ghost" disabled={state === "busy"} onClick={() => adopt("append")}>附加在後</Button>
        </div>
      ) : (
        <span style={{ fontSize: 11, color: "var(--text-muted)" }}>（無對應欄位，請手動複製）</span>
      )}
    </div>
  );
}

// ---------- BMC 九宮格畫布（第 5 關）----------
function BmcCanvas({ module, fields }) {
  const val = (id) => {
    const f = fields[id];
    return f && f.value && f.value.trim() ? f.value.trim() : "";
  };
  const CELLS = [
    { id: "kp", label: "關鍵夥伴", en: "KP", area: "kp" },
    { id: "ka", label: "關鍵活動", en: "KA", area: "ka" },
    { id: "kr", label: "關鍵資源", en: "KR", area: "kr" },
    { id: "vp", label: "價值主張", en: "VP", area: "vp", hero: true },
    { id: "cr", label: "客戶關係", en: "CR", area: "cr" },
    { id: "ch", label: "通路", en: "CH", area: "ch" },
    { id: "cs", label: "客戶細分", en: "CS", area: "cs" },
    { id: "cost", label: "成本結構", en: "COST", area: "cost" },
    { id: "rev", label: "收入來源", en: "REV", area: "rev" },
  ];
  return (
    <div>
      <div className="sq-bmc" style={{
        display: "grid", gap: 6,
        gridTemplateAreas: '"kp ka vp cr cs" "kp kr vp ch cs" "cost cost cost rev rev"',
        gridTemplateColumns: "1fr 1fr 1.2fr 1fr 1fr",
        gridTemplateRows: "minmax(90px,auto) minmax(90px,auto) minmax(70px,auto)",
      }}>
        {CELLS.map((c) => (
          <div key={c.id} style={{
            gridArea: c.area, background: c.hero ? "rgba(212,175,55,.10)" : "var(--navy-950)",
            border: "1px solid " + (c.hero ? "var(--gold-500)" : "rgba(212,175,55,.25)"),
            borderRadius: 4, padding: "8px 9px", minWidth: 0,
          }}>
            <div style={{ fontSize: 11, color: "var(--gold-300)", fontWeight: 700, letterSpacing: ".06em", marginBottom: 4 }}>
              {c.label} <span style={{ fontFamily: "Cinzel,serif", fontSize: 8, color: "var(--text-muted)", letterSpacing: ".15em" }}>{c.en}</span>
            </div>
            <div style={{ fontSize: 11.5, lineHeight: 1.6, color: val(c.id) ? "var(--text-secondary)" : "var(--text-muted)", whiteSpace: "pre-wrap", maxHeight: 120, overflow: "auto" }}>
              {val(c.id) || "（未填）"}
            </div>
          </div>
        ))}
      </div>
      <style>{`
        @media (max-width: 1080px) {
          .sq-bmc { grid-template-areas: "vp vp" "kp ka" "kr cr" "ch cs" "cost rev" !important; grid-template-columns: 1fr 1fr !important; grid-template-rows: auto !important; }
        }
      `}</style>
    </div>
  );
}

// ---------- 欄位 ----------
function Field({ module, field, data, onChange, savedAt, locked }) {
  const val = data ? data.value : "";
  const fact = data ? data.fact_status : "";
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 4, flexWrap: "wrap" }}>
        <label style={{ fontWeight: 700, fontSize: 14, color: "var(--gold-100, #f2ead2)", letterSpacing: ".04em" }}>
          {field.label}{field.required && <span style={{ color: "var(--danger,#e07a6a)" }}> *</span>}
        </label>
        {savedAt && <span style={{ fontSize: 11, color: "var(--success,#7fc97f)" }}>已儲存 {savedAt}</span>}
      </div>
      <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.7, marginBottom: 6 }}>{field.hint}</div>
      <textarea
        rows={field.multiline === false ? 1 : 3}
        value={val}
        placeholder={field.example}
        disabled={locked}
        onChange={(e) => onChange(field.id, e.target.value, fact)}
        style={{
          width: "100%", boxSizing: "border-box", background: "var(--navy-950)",
          border: "1px solid rgba(212,175,55,.28)", borderRadius: 6, color: "var(--text-primary)",
          padding: "10px 12px", fontSize: 14, lineHeight: 1.7, fontFamily: '"Noto Sans TC",sans-serif',
          resize: "vertical", outline: "none",
        }}
        onFocus={(e) => { e.target.style.borderColor = "var(--gold-500)"; }}
        onBlur={(e) => { e.target.style.borderColor = "rgba(212,175,55,.28)"; }}
      />
      {field.fact_flag && (
        <div style={{ display: "flex", gap: 6, marginTop: 6, alignItems: "center" }}>
          <span style={{ fontSize: 11, color: "var(--text-muted)" }}>這格內容：</span>
          {FACT_OPTIONS.map((opt) => (
            <button key={opt} disabled={locked} onClick={() => !locked && onChange(field.id, val, fact === opt ? "" : opt)} style={{
              background: fact === opt ? "linear-gradient(180deg,#e6c96b,#b8912b)" : "transparent",
              color: fact === opt ? "#1a1406" : "var(--text-muted)",
              border: "1px solid " + (fact === opt ? "var(--gold-300)" : "rgba(212,175,55,.25)"),
              borderRadius: 999, fontSize: 11, padding: "3px 10px", cursor: "pointer",
            }}>{opt}</button>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------- 主畫面 ----------
function ModuleView({ id }) {
  const [module, setModule] = React.useState(null);
  const [fields, setFields] = React.useState({});
  const [locked, setLocked] = React.useState(false);
  const [savedAt, setSavedAt] = React.useState({});
  const [energy, setEnergy] = React.useState(null);
  const [wca, setWca] = React.useState(null);
  const [corePrice, setCorePrice] = React.useState(null);
  const [aiBusy, setAiBusy] = React.useState(false);
  const [aiResult, setAiResult] = React.useState(null);
  const [aiErr, setAiErr] = React.useState("");
  const [history, setHistory] = React.useState([]);
  const [explainTerm, setExplainTerm] = React.useState("");
  const [tab, setTab] = React.useState("form"); // mobile: learn | form | ai
  const timers = React.useRef({});

  const loadEnergy = () =>
    api("/api/overview").then((d) => { setEnergy(d.energy); setWca(d.wca_balance); setCorePrice(d.core_price_wca); }).catch(() => {});

  React.useEffect(() => {
    if (!window._modulesCache) window._modulesCache = api("/api/content/modules");
    window._modulesCache.then((ms) => {
      const m = ms.find((x) => x.id === Number(id));
      setModule(m);
      if (m && m.knowledge_cards.length) setExplainTerm(m.knowledge_cards[0].term);
    });
    api(`/api/team/module/${id}`).then((d) => { setFields(d.fields || {}); setLocked(d.status === "locked"); });
    api(`/api/ai/history?module_id=${id}`).then(setHistory).catch(() => {});
    loadEnergy();
  }, [id]);

  const onChange = (fieldId, value, factStatus) => {
    setFields((prev) => ({ ...prev, [fieldId]: { value, fact_status: factStatus } }));
    clearTimeout(timers.current[fieldId]);
    timers.current[fieldId] = setTimeout(async () => {
      try {
        await api(`/api/team/module/${id}/field`, { method: "PUT", body: { field_id: fieldId, value, fact_status: factStatus } });
        setSavedAt((p) => ({ ...p, [fieldId]: new Date().toLocaleTimeString("zh-TW", { hour12: false }) }));
      } catch (e) { console.error(e); }
    }, 1200);
  };

  const runAi = async (taskType) => {
    setAiBusy(true); setAiErr(""); setAiResult(null);
    try {
      const extra = taskType === "explain" ? { term: explainTerm } : undefined;
      const r = await api("/api/ai/run", {
        method: "POST",
        body: { module_id: Number(id), task_type: taskType, client_nonce: (crypto.randomUUID ? crypto.randomUUID() : String(Date.now() + Math.random())), extra },
      });
      setAiResult(r);
      api(`/api/ai/history?module_id=${id}`).then(setHistory).catch(() => {});
      loadEnergy();
    } catch (e) { setAiErr(e.message); }
    setAiBusy(false);
  };

  const buyCore = async () => {
    if (!confirm(`用 ${corePrice} WCA Token 購買新能量核心？`)) return;
    try { await api("/api/energy/buy", { method: "POST" }); await loadEnergy(); setAiErr(""); }
    catch (e) { alert(e.message); }
  };

  const onAdopted = (fieldId, mode, content) => {
    setFields((prev) => {
      const old = prev[fieldId] || { value: "", fact_status: "" };
      const value = mode === "append" && old.value ? old.value + "\n\n" + content : content;
      return { ...prev, [fieldId]: { ...old, value } };
    });
    setSavedAt((p) => ({ ...p, [fieldId]: new Date().toLocaleTimeString("zh-TW", { hour12: false }) }));
  };

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

  const requiredTotal = module.fields.filter((f) => f.required).length;
  const requiredDone = module.fields.filter((f) => f.required && fields[f.id] && fields[f.id].value && fields[f.id].value.trim()).length;
  const remainingPct = energy && energy.active ? energy.active.remaining_pct : 0;
  const depleted = energy && !energy.active;

  const learnCol = (
    <div>
      <Panel header="本關任務">
        <div style={{ fontStyle: "italic", color: "var(--gold-300)", fontSize: 13, marginBottom: 10, lineHeight: 1.7 }}>「{module.rpg_line}」</div>
        <div style={{ fontSize: 13, lineHeight: 1.8, color: "var(--text-secondary)" }}>{module.purpose}</div>
        <div style={{ fontSize: 12, lineHeight: 1.7, color: "var(--text-muted)", marginTop: 10, borderLeft: "2px solid var(--danger,#e07a6a)", paddingLeft: 10 }}>
          不做的代價：{module.affects}
        </div>
      </Panel>
      <div style={{ height: 14 }} />
      <Panel header="知識卡">
        {module.knowledge_cards.map((k, i) => (
          <Collapsible key={i} title={`${k.term}（${k.en}）`}>
            <div>{k.plain}</div>
            <div style={{ marginTop: 6, color: "var(--info,#4db6e8)" }}>牙科例：{k.dental_example}</div>
          </Collapsible>
        ))}
      </Panel>
      <div style={{ height: 14 }} />
      <Panel header="好與壞的範例">
        <Collapsible title={"◆ " + module.good_example.title} accent="var(--success,#7fc97f)">
          <div style={{ whiteSpace: "pre-wrap" }}>{module.good_example.content}</div>
          <div style={{ marginTop: 6, color: "var(--success,#7fc97f)" }}>為什麼好：{module.good_example.why}</div>
        </Collapsible>
        <Collapsible title={"◆ " + module.bad_example.title} accent="var(--danger,#e07a6a)">
          <div style={{ whiteSpace: "pre-wrap" }}>{module.bad_example.content}</div>
          <div style={{ marginTop: 6, color: "var(--danger,#e07a6a)" }}>為什麼危險：{module.bad_example.why}</div>
        </Collapsible>
      </Panel>
      <div style={{ height: 14 }} />
      <Panel header="完成標準">
        <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.9, color: "var(--text-secondary)" }}>
          {module.done_definition.map((d, i) => <li key={i}>{d}</li>)}
        </ul>
        <div style={{ marginTop: 10, fontSize: 12, color: "var(--gold-300)" }}>交付物：{module.deliverable}</div>
      </Panel>
    </div>
  );

  const formCol = (
    <div>
      {locked && (
        <div style={{
          border: "1px solid var(--info,#4db6e8)", borderRadius: 6, padding: "10px 14px", marginBottom: 14,
          color: "var(--info,#4db6e8)", fontSize: 13, background: "rgba(77,182,232,.08)",
        }}>
          ⛨ 已最終提交鎖定——內容唯讀。需要修改請到 Pitch 組裝台「重新開啟」。
        </div>
      )}
      {module.bmc && (
        <div style={{ marginBottom: 14 }}>
          <Panel header="商業模式九宮格 · 即時畫布">
            <BmcCanvas module={module} fields={fields} />
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 8 }}>下方欄位填寫後即時映到畫布。</div>
          </Panel>
        </div>
      )}
      <Panel header={`輸入工作區（必填 ${requiredDone}/${requiredTotal}）`}>
        <div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: 16, lineHeight: 1.6 }}>
          ⛨ 自動儲存，全隊共用。請勿輸入可識別病患或個人的資料（姓名、病歷號、電話）。
        </div>
        {module.fields.map((f) => (
          <Field key={f.id} module={module} field={f} data={fields[f.id]} onChange={onChange} savedAt={savedAt[f.id]} locked={locked} />
        ))}
      </Panel>
    </div>
  );

  const aiCol = (
    <div>
      <Panel header="AI 能量" glow={remainingPct <= 10}>
        {energy && energy.active ? (
          <div>
            <ProgressBar value={remainingPct} max={100} height={10} label={`第 ${energy.active.seq} 顆核心`} />
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 6 }}>剩餘 {remainingPct}%｜軍餉 {wca} WCA</div>
          </div>
        ) : (
          <div style={{ textAlign: "center", padding: "4px 0" }}>
            <div style={{ color: "var(--danger,#e07a6a)", marginBottom: 8, fontSize: 13 }}>能量耗盡 · AI 已鎖定</div>
            <Button size="sm" onClick={buyCore}>用 {corePrice} WCA 購買新核心</Button>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 6 }}>軍餉 {wca} WCA</div>
          </div>
        )}
      </Panel>
      <div style={{ height: 14 }} />
      <Panel header="AI 教練">
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {module.ai_tasks.filter((t) => t !== "pitch").map((t) => (
            <div key={t} style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Button size="sm" style={{ flex: 1, justifyContent: "flex-start" }} disabled={aiBusy || depleted || locked} onClick={() => runAi(t)}>
                {TASK_LABEL[t] || t}
              </Button>
              <span style={{ fontSize: 10, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{COST_HINT[t] || ""}</span>
            </div>
          ))}
          {module.ai_tasks.includes("explain") && (
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12 }}>
              <span style={{ color: "var(--text-muted)" }}>解釋名詞：</span>
              <select value={explainTerm} onChange={(e) => setExplainTerm(e.target.value)} style={{
                background: "var(--navy-950)", color: "var(--text-primary)", border: "1px solid rgba(212,175,55,.28)",
                borderRadius: 4, padding: "4px 8px", fontSize: 12,
              }}>
                {module.knowledge_cards.map((k) => <option key={k.term} value={k.term}>{k.term}</option>)}
              </select>
            </div>
          )}
        </div>
        {aiBusy && (
          <div style={{ textAlign: "center", padding: "18px 0", color: "var(--gold-300)", fontSize: 13, letterSpacing: ".2em" }}>
            ◆ 教練分析中… ◆
          </div>
        )}
        {aiErr && <div style={{ color: "var(--danger,#e07a6a)", fontSize: 13, marginTop: 12, lineHeight: 1.7 }}>{aiErr}</div>}
        {aiResult && (
          <div style={{ marginTop: 14, borderTop: "1px solid rgba(212,175,55,.2)", paddingTop: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10 }}>
              <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>
            <AiPayload payload={aiResult.payload} requestId={aiResult.request_id} module={module} onAdopted={onAdopted} />
          </div>
        )}
      </Panel>
      {history.length > 0 && (
        <div>
          <div style={{ height: 14 }} />
          <Panel header={`本關 AI 紀錄（${history.length}）`}>
            {history.map((h) => (
              <Collapsible key={h.id} title={`${h.task_label} · ${h.created_at.slice(5, 16)}${h.adopted_status === "adopted" ? " ✓已採納" : ""}`}>
                <AiPayload payload={h.payload} requestId={h.id} module={module} onAdopted={onAdopted} />
              </Collapsible>
            ))}
          </Panel>
        </div>
      )}
    </div>
  );

  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <a href="#/quests" style={{ fontSize: 13, textDecoration: "none" }}>← 關卡列表</a>
        <span style={{ fontFamily: '"Noto Serif TC",serif', fontWeight: 900, fontSize: 22, color: "var(--gold-300)", letterSpacing: ".08em" }}>
          第 {module.id} 關 · {module.title}
        </span>
        <span style={{ fontFamily: "Cinzel,serif", fontSize: 10, letterSpacing: ".3em", color: "var(--text-muted)" }}>{module.en}</span>
      </div>

      {/* 手機分頁切換 */}
      <div className="sq-tabs" style={{ display: "none", gap: 8, marginBottom: 14 }}>
        {[["learn", "學習"], ["form", "填寫"], ["ai", "AI 教練"]].map(([k, label]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            flex: 1, padding: "8px 0", borderRadius: 999, cursor: "pointer", fontSize: 13, letterSpacing: ".1em",
            background: tab === k ? "linear-gradient(180deg,#e6c96b,#b8912b)" : "transparent",
            color: tab === k ? "#1a1406" : "var(--text-muted)",
            border: "1px solid " + (tab === k ? "var(--gold-300)" : "rgba(212,175,55,.25)"),
            fontWeight: tab === k ? 700 : 400,
          }}>{label}</button>
        ))}
      </div>

      <div className="sq-module-grid" style={{ display: "grid", gridTemplateColumns: "290px 1fr 320px", gap: 16, alignItems: "start" }}>
        <div className={"sq-col sq-col-learn" + (tab === "learn" ? " sq-active" : "")}>{learnCol}</div>
        <div className={"sq-col sq-col-form" + (tab === "form" ? " sq-active" : "")}>{formCol}</div>
        <div className={"sq-col sq-col-ai" + (tab === "ai" ? " sq-active" : "")}>{aiCol}</div>
      </div>
      <style>{`
        @media (max-width: 1080px) {
          .sq-module-grid { grid-template-columns: 1fr !important; }
          .sq-tabs { display: flex !important; }
          .sq-col { display: none; }
          .sq-col.sq-active { display: block; }
        }
      `}</style>
    </div>
  );
}

window.ModuleView = ModuleView;
window.AiPayload = AiPayload;
})();
