/* ============================================================
   Fynch AI — workshop1.jsx  (slides 7–11)  — v2, elevated
   Deal-cycle mapper + shared workshop chrome (WsHeader).
   ============================================================ */
(function () {
  const SEED = window.FYNCH_SEED;
  const SEV = ["None", "Low", "Med", "High"];
  const SYS_ICON = { "Email": "mail", "Excel": "table", "Word": "doc", "PowerPoint": "present", "OneDrive / SharePoint": "cloud", "Data room": "lock", "CRM": "people", "Internal DB": "database", "Loan origination": "bank", "Vendor portal": "window", "Custom tool": "grid", "Manual judgment": "bulb" };

  /* ---- shared workshop chrome ---- */
  function WsHeader({ n, title, sub, wsKey, right }) {
    const store = useStore();
    const locked = FynchStore.isLocked(wsKey);
    const count = FynchStore.participantCount();
    const now = Date.now();
    const people = Object.values(store.participants || {}).filter((p) => now - (p.lastSeen || 0) < 90000).slice(0, 6);
    const initials = (nm) => (nm || "?").split(/\s+/).map((w) => w[0]).join("").slice(0, 2).toUpperCase();
    return (
      <Reveal variant="up" className="ws-head">
        <div className="left">
          <div className="ws-badge"><span className="num">{n}</span>Workshop {n}</div>
          <h2 className="slide-h2" style={{ fontSize: 48 }}>{title}</h2>
          {sub && <p className="lead" style={{ fontSize: 23, marginTop: 2 }}>{sub}</p>}
        </div>
        <div className="ws-controls">
          {right}
          {people.length > 0 && <div className="ws-avatars">{people.map((p, i) => <span key={i} className="ws-av" title={p.name + " · " + p.role}>{initials(p.name)}</span>)}{count > people.length && <span className="ws-av more">+{count - people.length}</span>}</div>}
          <div className="session-pill"><span className="live"></span><b>Live</b><span className="code">{FynchStore.code()}</span><span className="ppl"><Icon name="people" size={15} />{count}</span></div>
          <button className={"lock-toggle" + (locked ? " locked" : "")} onClick={() => FynchStore.toggleLock(wsKey)}><Icon name={locked ? "lock" : "unlock"} size={16} />{locked ? "Locked" : "Open"}</button>
        </div>
      </Reveal>
    );
  }
  window.WsHeader = WsHeader;

  /* ============================================================
     Slide 7 — intro: anatomy of a stage (dark, distinct graphic)
     ============================================================ */
  const ANATOMY = [["Owner", "Who is accountable here", "people"], ["Inputs", "What arrives at this stage", "doc"], ["Systems", "Where the work actually happens", "grid"], ["Output", "What leaves, ready for next", "arrowR"], ["Bottleneck", "Where it stalls or waits", "flag"], ["Risk", "What breaks if it's wrong", "shield"]];
  function Intro1() {
    return (
      <div className="slide-pad">
        <div className="cols" style={{ gridTemplateColumns: "0.9fr 1.1fr", gap: 64, flex: 1, alignItems: "center" }}>
          <div>
            <Reveal variant="up" className="ws-badge" style={{ color: "var(--brand-300)", marginBottom: 24 }}><span className="num">1</span>WORKSHOP ONE</Reveal>
            <Reveal variant="up" delay={80} as="h2" className="slide-h2" style={{ fontSize: 68 }}>Map the current deal cycle.</Reveal>
            <Reveal variant="up" delay={160} as="p" className="lead" style={{ marginTop: 20, fontSize: 28 }}>We map one representative deal — first signal to final decision — and make it wrong until it's right.</Reveal>
            <Reveal variant="up" delay={240} style={{ marginTop: 28, display: "inline-flex", alignItems: "center", gap: 12, color: "#8696b3", fontSize: 19 }}>
              <Icon name="people" size={20} /><span>Live on screen — call out the defaults and we'll edit them in real time.</span>
            </Reveal>
          </div>
          <Reveal variant="right" delay={200}>
            <div className="anatomy-card">
              <div className="anatomy-head"><span className="anatomy-ix">05</span><span className="anatomy-name">Document intake</span><span className="anatomy-sev">High friction</span></div>
              <div className="anatomy-grid">
                {ANATOMY.map((a, i) => (
                  <div key={a[0]} className="anatomy-field" style={{ "--ld": 360 + i * 110 + "ms" }}>
                    <span className="af-ic"><Icon name={a[2]} size={18} /></span>
                    <div><div className="af-label">{a[0]}</div><div className="af-desc">{a[1]}</div></div>
                  </div>
                ))}
              </div>
              <div className="anatomy-foot">Six dimensions · captured for every stage</div>
            </div>
          </Reveal>
        </div>
        <Foot no={7} section="Workshop 1" />
      </div>
    );
  }

  /* ============================================================
     Slide 8 — interactive mapper (friendlier, bigger)
     ============================================================ */
  function StageCard({ stage, index, total, locked }) {
    const ref = useRef(null);
    function patch(fn) { FynchStore.update((s) => { const st = s.ws1.stages.find((x) => x.id === stage.id); if (st) fn(st); }); }
    function move(dir) { FynchStore.update((s) => { const arr = s.ws1.stages; const to = index + dir; if (to < 0 || to >= arr.length) return; const [m] = arr.splice(index, 1); arr.splice(to, 0, m); }); }
    return (
      <div className="stage-card" ref={ref}
        draggable={!locked}
        onDragStart={(e) => { e.dataTransfer.setData("text/plain", String(index)); ref.current.classList.add("dragging"); }}
        onDragEnd={() => ref.current && ref.current.classList.remove("dragging")}
        onDragOver={(e) => { e.preventDefault(); ref.current.classList.add("drop-target"); }}
        onDragLeave={() => ref.current.classList.remove("drop-target")}
        onDrop={(e) => { e.preventDefault(); ref.current.classList.remove("drop-target"); const from = parseInt(e.dataTransfer.getData("text/plain"), 10); if (!isNaN(from)) FynchStore.update((s) => { const arr = s.ws1.stages; const [m] = arr.splice(from, 1); arr.splice(index, 0, m); }); }}>
        <div className="sc-head">
          <span className="sc-order">{String(index + 1).padStart(2, "0")}</span>
          <span className="sc-name" contentEditable={!locked} suppressContentEditableWarning onBlur={(e) => patch((st) => (st.name = e.target.innerText.trim()))}>{stage.name}</span>
          {!locked && (
            <div className="sc-move">
              <button onClick={() => move(-1)} disabled={index === 0} title="Move earlier"><Icon d="M15 18l-6-6 6-6" size={15} /></button>
              <button onClick={() => move(1)} disabled={index === total - 1} title="Move later"><Icon d="M9 6l6 6-6 6" size={15} /></button>
              <button onClick={() => FynchStore.update((s) => { s.ws1.stages = s.ws1.stages.filter((x) => x.id !== stage.id); })} title="Remove" className="rm"><Icon d="M3 6h18M8 6V4h8v2m-9 0v14a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V6" size={15} /></button>
            </div>
          )}
        </div>
        <div className="sc-body">
          {[["Owner", "owner"], ["Inputs", "inputs"], ["Output", "output"], ["Bottleneck", "bottleneck"], ["Risk", "risk"]].map(([lab, key]) => (
            <div key={key} className="sc-field"><span className="fl">{lab}</span><span className="fv" contentEditable={!locked} suppressContentEditableWarning onBlur={(e) => patch((st) => (st[key] = e.target.innerText.trim()))}>{stage[key]}</span></div>
          ))}
          <div className="sc-field"><span className="fl">Systems</span>
            <div className="sc-tags">{SEED.SYSTEM_TAGS.map((t) => { const on = stage.systems.includes(t); return <span key={t} className={"systag" + (on ? " on" : "")} onClick={() => !locked && patch((st) => { st.systems = on ? st.systems.filter((x) => x !== t) : [...st.systems, t]; })}>{t}</span>; })}</div>
          </div>
        </div>
        <div className="sc-foot">
          <span className="fl">Friction</span>
          <div className="sev-seg">{SEV.map((s, lvl) => <button key={s} className={stage.sev === lvl ? "on lv" + lvl : ""} onClick={() => !locked && patch((st) => (st.sev = lvl))}>{s}</button>)}</div>
        </div>
      </div>
    );
  }
  function DealFlow() {
    const store = useStore();
    const locked = FynchStore.isLocked("ws1");
    const stages = store.ws1.stages;
    return (
      <div className="slide-pad">
        <div className="ws">
          <WsHeader n="1" wsKey="ws1" title="Current deal flow" sub="Use the arrows to reorder · click any field to edit · set friction per stage" />
          <Reveal variant="up" delay={120} className="pipeline" style={{ flex: 1 }}>
            {stages.map((st, i) => <StageCard key={st.id} stage={st} index={i} total={stages.length} locked={locked} />)}
            {!locked && <button className="add-stage" onClick={() => FynchStore.update((s) => { s.ws1.stages.push({ id: "s" + Date.now(), name: "New stage", owner: "—", inputs: "—", systems: [], output: "—", bottleneck: "—", risk: "—", sev: 0 }); })} title="Add stage"><Icon name="plus" size={26} /></button>}
          </Reveal>
        </div>
        <Foot no={8} section="Workshop 1" />
      </div>
    );
  }

  /* ============================================================
     Slide 9 — where the work lives (system constellation)
     ============================================================ */
  function WorkLives() {
    const store = useStore();
    const tally = {};
    store.ws1.stages.forEach((st) => st.systems.forEach((sy) => { tally[sy] = (tally[sy] || 0) + 1; }));
    const probes = ["What makes a package ready to screen?", "What makes a deal ready to quote?", "What makes a memo committee-ready?", "Where do conflicting facts get resolved?", "Where do assumptions get approved?", "What's painful to audit later?"];
    const ranked = SEED.SYSTEM_TAGS.map((t) => [t, tally[t] || 0]).sort((a, b) => b[1] - a[1]);
    const maxc = Math.max(1, ...ranked.map((r) => r[1]));
    return (
      <div className="slide-pad">
        <Reveal variant="up"><div className="eyebrow-row" style={{ marginBottom: 8 }}><Kicker>Workshop 1 · live</Kicker></div></Reveal>
        <Reveal variant="up" delay={70} as="h2" className="slide-h2" style={{ marginBottom: 8 }}>Where does the work actually live?</Reveal>
        <Reveal variant="up" delay={130} as="p" className="lead" style={{ marginBottom: 28, fontSize: 24 }}>Not about criticizing email or Excel — about seeing where facts are created, copied, changed, or lost.</Reveal>
        <div className="cols grow" style={{ gridTemplateColumns: "1.25fr 1fr", gap: 40, alignItems: "stretch", minHeight: 0 }}>
          <Reveal variant="up" delay={160} className="card" style={{ padding: "26px 30px", display: "flex", flexDirection: "column" }}>
            <div className="label-meta" style={{ marginBottom: 20 }}>Systems touching one deal — bar = stages using it</div>
            <div className="stack" style={{ gap: 10, flex: 1, justifyContent: "center" }}>
              {ranked.map(([t, c]) => (
                <div key={t} style={{ display: "grid", gridTemplateColumns: "46px 186px 1fr 34px", alignItems: "center", gap: 14, opacity: c ? 1 : 0.5 }}>
                  <span style={{ width: 42, height: 42, borderRadius: 10, display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto", background: c ? "var(--brand-50)" : "var(--canvas)", border: "1px solid " + (c ? "var(--brand-200)" : "var(--line-200)"), color: c ? "var(--brand-600)" : "var(--ink-400)" }}><Icon name={SYS_ICON[t] || "grid"} size={21} /></span>
                  <span style={{ fontSize: 18, fontWeight: c ? 600 : 500, color: c ? "var(--ink-800)" : "var(--ink-400)" }}>{t}</span>
                  <span style={{ height: 16, borderRadius: 9999, background: "var(--line-100)", overflow: "hidden" }}><span style={{ display: "block", height: "100%", width: (c / maxc) * 100 + "%", background: c ? "var(--brand-500)" : "transparent", borderRadius: 9999, transition: "width .5s" }}></span></span>
                  <span className="mono" style={{ fontSize: 16, color: c ? "var(--brand-600)" : "var(--ink-300)", textAlign: "right", fontWeight: 600 }}>{c || "—"}</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--line-200)", fontSize: 19, color: "var(--ink-600)" }}><b style={{ color: "var(--ink-900)", fontSize: 24 }}>{Object.keys(tally).length}</b> distinct systems touch a single deal today.</div>
          </Reveal>
          <Reveal variant="up" delay={220} className="card" style={{ padding: "26px 30px", display: "flex", flexDirection: "column" }}>
            <div className="label-meta" style={{ marginBottom: 18 }}>Probe questions</div>
            <ul className="q-list" style={{ gap: 15 }}>{probes.map((q) => <li key={q} style={{ fontSize: 21 }}>{q}</li>)}</ul>
            <div style={{ marginTop: "auto", paddingTop: 18, background: "var(--brand-500)", borderRadius: 10, padding: "16px 18px", color: "#fff", fontSize: 19, lineHeight: 1.4 }}>What happens when the package is <b>incomplete</b> but the deal is still <b>interesting</b>?</div>
          </Reveal>
        </div>
        <Foot no={9} section="Workshop 1" />
      </div>
    );
  }

  /* ============================================================
     Slide 10 — what the map shows (big stats)
     ============================================================ */
  function MapShows() {
    const store = useStore();
    const stages = store.ws1.stages;
    const topFriction = [...stages].filter((s) => s.sev > 0).sort((a, b) => b.sev - a.sev).slice(0, 3);
    const systemsSet = new Set(); stages.forEach((s) => s.systems.forEach((x) => systemsSet.add(x)));
    let handoffs = 0; for (let i = 1; i < stages.length; i++) if (stages[i].owner !== stages[i - 1].owner) handoffs++;
    const manual = stages.filter((s) => s.systems.includes("Manual judgment")).length;
    return (
      <div className="slide-pad">
        <Reveal variant="up"><div className="eyebrow-row" style={{ marginBottom: 8 }}><Kicker>Workshop 1 · output</Kicker></div></Reveal>
        <Reveal variant="up" delay={70} as="h2" className="slide-h2" style={{ marginBottom: 34 }}>What the map already tells us.</Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 24, marginBottom: 30 }}>
          {[[stages.length, "stages mapped", "var(--ink-900)"], [handoffs, "ownership handoffs", "var(--review-fg)"], [systemsSet.size, "distinct systems", "var(--brand-600)"], [manual, "manual-judgment steps", "var(--conflict-fg)"]].map(([n, l, c], i) => (
            <Reveal key={l} variant="up" delay={120 + i * 80} className="card" style={{ padding: "26px 28px" }}>
              <span className="bignum" style={{ color: c, fontSize: 72 }}><CountUp to={n} /></span>
              <div style={{ fontSize: 19, color: "var(--ink-500)", marginTop: 8 }}>{l}</div>
            </Reveal>
          ))}
        </div>
        <div className="cols grow" style={{ gridTemplateColumns: "1fr 1fr", gap: 32, alignItems: "stretch", minHeight: 0 }}>
          <Reveal variant="up" delay={420} className="card" style={{ padding: "26px 30px" }}>
            <div className="label-meta" style={{ marginBottom: 18 }}>Highest-friction stages</div>
            {topFriction.length === 0 ? <div className="muted" style={{ fontSize: 20 }}>Set friction on the deal flow and the ranking appears here.</div> : (
              <div className="stack" style={{ gap: 14 }}>{topFriction.map((s, i) => <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 16 }}><span className="numbadge" style={{ width: 40, height: 40 }}>{i + 1}</span><span style={{ fontSize: 23, fontWeight: 600 }}>{s.name}</span><span style={{ marginLeft: "auto" }} className={"complexity-band cb-" + (s.sev >= 3 ? "high" : s.sev === 2 ? "med" : "low")}>{["", "Low", "Med", "High"][s.sev]}</span></div>)}</div>
            )}
          </Reveal>
          <Reveal variant="up" delay={500} className="card" style={{ padding: "28px 32px", background: "var(--brand-500)", borderColor: "var(--brand-500)", display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <div style={{ color: "rgba(255,255,255,.8)", fontSize: 16, fontWeight: 600, letterSpacing: ".5px", textTransform: "uppercase", marginBottom: 12 }}>Before we prescribe anything</div>
            <div style={{ color: "#fff", fontSize: 28, fontWeight: 500, lineHeight: 1.35 }}>This is already a useful view of your operating model — in your own words. Every handoff is a place facts get copied or lost.</div>
          </Reveal>
        </div>
        <Foot no={10} section="Workshop 1" />
      </div>
    );
  }

  /* ============================================================
     Slide 11 — proof: workspace screenshot slot
     ============================================================ */
  function Proof1() {
    return (
      <div className="slide-pad">
        <SolvesTag solves="Workflow fragmentation" status="live" />
        <Reveal variant="up" style={{ maxWidth: 1180, marginBottom: 22 }}><Kicker>Micro-proof</Kicker><h1 className="slide-title" style={{ fontSize: 38, marginTop: 8 }}>The workflow becomes one deal workspace.</h1></Reveal>
        <div className="grow" style={{ minHeight: 0 }}>
          <ScreenSlot label="Deal Workspace — Overview" tab="Property record · key facts · documents · review · quotes · outputs" note="Drop the Harborview workspace overview here. Overlay labels: Intake · Package completeness · Fact review · Quote readiness · Memo output · Audit trail." />
        </div>
        <Foot no={11} section="Product proof 1" />
      </div>
    );
  }

  window.registerSlides([
    { no: 7, section: "Workshop 1", dark: true, Comp: Intro1 },
    { no: 8, section: "Workshop 1", ws: "ws1", Comp: DealFlow },
    { no: 9, section: "Workshop 1", ws: "ws1", Comp: WorkLives },
    { no: 10, section: "Workshop 1", ws: "ws1", Comp: MapShows },
    { no: 11, section: "Product proof 1", Comp: Proof1 },
  ]);
})();
