/* ============================================================
   Fynch AI — slides_close.jsx  (slides 35–36)
   Next step + session export (compiles all workshop outputs).
   ============================================================ */
(function () {
  function buildBrief() {
    const s = FynchStore.get();
    const agg = FynchStore.agg;
    const stages = s.ws1.stages;
    const heat = stages.map((st) => ({ stage: st.name, friction: +agg.ws2StageScore(s, st.id).toFixed(2), systems: st.systems.length }));
    const facts = s.ws3.facts.map((f) => ({ fact: f.fact, primary: f.primary, confidence: f.conf, importance: f.importance, blocksQuote: f.quote, blocksMemo: f.memo }));
    const buildBuy = SEED().LAYERS.map((l) => ({ layer: l.layer, tally: agg.ws4Tally(s, l.id), complexity: l.complexity }));
    return {
      session: s.meta.code, generated: new Date().toISOString(),
      participants: Object.values(s.participants).map((p) => ({ name: p.name, role: p.role })),
      workflowMap: stages,
      frictionHeatmap: heat,
      trustMap: facts,
      buildBuyHybrid: buildBuy,
      roiAssumptions: s.ws5,
      pilotRecommendation: "90-minute sample deal review — confirm workflow, run one package, map facts & evidence, define pilot scope & metrics.",
    };
  }
  function SEED() { return window.FYNCH_SEED; }
  function exportBrief() {
    const blob = new Blob([JSON.stringify(buildBrief(), null, 2)], { type: "application/json" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "fynch_session_brief_" + FynchStore.code() + ".json";
    document.body.appendChild(a); a.click(); a.remove();
  }
  window.fynchExportBrief = exportBrief;

  /* ---- Slide 35 — recommended next step ---- */
  function NextStep() {
    const [copied, setCopied] = useState(false);
    const agenda = ["Confirm target workflow", "Review one representative deal package", "Map required facts & evidence", "Compare current vs AI-assisted process", "Identify pilot scope", "Define success metrics"];
    const attendees = [["Underwriting lead", "people"], ["Credit / investment decision-maker", "shield"], ["Operations / process owner", "grid"], ["Technology / AI stakeholder", "spark"], ["Security / data stakeholder", "lock"]];
    function copyInvite() {
      const body = ["CRE Underwriting — Sample Deal Review (90 min)", "", "Goal: run one representative deal package through the workflow and pilot fact list from our working session.", "", "Agenda:", ...agenda.map((a, i) => `  ${i + 1}. ${a}`), "", "Suggested attendees:", ...attendees.map((a) => `  • ${a[0]}`), "", "We'll share the required document checklist and priority fact list in advance."].join("\n");
      try { navigator.clipboard.writeText(body); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (e) {}
    }
    return (
      <div className="slide-pad">
        <SlideHead kicker="Recommended next step" h2="A 90-minute sample deal review." />
        <div className="cols c2 grow" style={{ alignItems: "stretch" }}>
          <div className="card pad" data-rise>
            <div className="label-meta" style={{ marginBottom: 16 }}>Agenda</div>
            <div className="stack" style={{ gap: 11 }}>
              {agenda.map((t, i) => <div key={t} style={{ display: "flex", gap: 14, alignItems: "center" }}><span className="numbadge" style={{ width: 30, height: 30, fontSize: 14 }}>{i + 1}</span><span style={{ fontSize: 17, color: "var(--ink-800)" }}>{t}</span></div>)}
            </div>
            <div className="label-meta" style={{ margin: "20px 0 12px", paddingTop: 18, borderTop: "1px solid var(--line-200)" }}>Suggested attendees</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "9px 18px" }}>
              {attendees.map(([t, ic]) => <div key={t} style={{ display: "flex", gap: 9, alignItems: "center", fontSize: 15, color: "var(--ink-700)" }}><span style={{ color: "var(--brand-500)" }}><Icon name={ic} size={17} /></span>{t}</div>)}
            </div>
          </div>
          <div className="stack gap-m" data-rise style={{ "--i": 1 }}>
            <div className="card pad">
              <div className="label-meta" style={{ marginBottom: 14 }}>Choose a path</div>
              <div className="stack" style={{ gap: 10 }}>
                {[["A", "Sample deal review", "Run one real package through the pilot fact list", true], ["B", "Technical / security review", "Architecture, data handling, permissions", false], ["C", "Internal alignment first", "We reconvene once the right people are set", false]].map(([k, t, d, primary]) => (
                  <div key={k} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", borderRadius: 10, border: "1px solid " + (primary ? "var(--brand-500)" : "var(--line-200)"), background: primary ? "var(--brand-50)" : "var(--surface)" }}>
                    <span className="numbadge" style={{ width: 34, height: 34, fontSize: 16, background: primary ? "var(--brand-500)" : "transparent", color: primary ? "#fff" : "var(--brand-600)", border: primary ? "0" : "2px solid var(--brand-300)" }}>{k}</span>
                    <div style={{ flex: 1 }}><div style={{ fontSize: 18, fontWeight: 600, color: "var(--ink-900)" }}>{t}{primary && <span style={{ marginLeft: 10, fontSize: 12, fontWeight: 600, color: "var(--brand-600)", background: "#fff", border: "1px solid var(--brand-200)", borderRadius: 9999, padding: "2px 9px" }}>recommended</span>}</div><div style={{ fontSize: 14.5, color: "var(--ink-500)", marginTop: 2 }}>{d}</div></div>
                  </div>
                ))}
              </div>
            </div>
            <div className="card pad" style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <span className="numbadge big" style={{ background: "var(--brand-50)", color: "var(--brand-600)" }}><Icon name="calendar" size={28} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 18, fontWeight: 600 }}>Hold 90 minutes — next week or the week after</div>
                <div style={{ fontSize: 14.5, color: "var(--ink-500)", marginTop: 3 }}>Attendees above. We send the package list in advance.</div>
              </div>
              <button className="btn primary" onClick={copyInvite}><Icon name="download" size={16} />{copied ? "Copied" : "Copy invite"}</button>
            </div>
            <div style={{ fontSize: 15, color: "var(--ink-500)" }}>Not "do you want a follow-up" — <b>who should be in the room?</b></div>
          </div>
        </div>
        <Foot no={35} section="Close" />
      </div>
    );
  }

  /* ---- Slide 36 — close (dark) ---- */
  const LINES = [["Documents", "are the input."], ["Facts", "are the asset."], ["Evidence", "creates trust."], ["Workflow", "creates adoption."], ["Audit", "creates institutional control."]];
  const EXPORTS = ["Workflow map", "Friction heatmap", "Disagreement view", "Source-to-fact trust map", "Pilot fact list", "Product capability fit map", "Build / buy / hybrid matrix", "ROI assumptions", "Pilot recommendation", "Open questions"];
  function Close() {
    return (
      <div className="slide-pad" style={{ justifyContent: "space-between" }}>
        <div data-rise>
          <Kicker>The close</Kicker>
          <h2 className="slide-h2" style={{ fontSize: 52, marginTop: 14, maxWidth: 1300 }}>Underwriting rebuilt around evidence.</h2>
        </div>
        <div className="cols c2-wide-l" data-rise style={{ "--i": 1, gap: 56, alignItems: "center" }}>
          <div className="stack" style={{ gap: 14 }}>
            {LINES.map(([a, b]) => (
              <div key={a} style={{ fontSize: 30, lineHeight: 1.25 }}><b style={{ color: "#f4f7fc", fontWeight: 600 }}>{a}</b> <span style={{ color: "#8696b3" }}>{b}</span></div>
            ))}
          </div>
          <div className="card" style={{ padding: "22px 26px" }}>
            <div className="label-meta" style={{ color: "#7f9bc4", marginBottom: 14 }}>Session export includes</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "9px 18px", marginBottom: 18 }}>
              {EXPORTS.map((e) => <div key={e} style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 14.5, color: "#c4cfdf" }}><Icon name="check" size={14} style={{ color: "var(--brand-300)" }} />{e}</div>)}
            </div>
            <button className="btn primary" onClick={exportBrief} style={{ width: "100%", justifyContent: "center" }}><Icon name="download" size={16} />Export session brief</button>
          </div>
        </div>
        <div data-rise style={{ "--i": 2 }}>
          <FlowBand compact showDesc={false} />
          <div style={{ marginTop: 22, fontSize: 22, color: "#aab6cc" }}>Who should join the sample deal review?</div>
        </div>
        <Foot no={36} section="Close" />
      </div>
    );
  }

  window.registerSlides([
    { no: 35, section: "Close", Comp: NextStep },
    { no: 36, section: "Close", dark: true, Comp: Close },
  ]);
})();
