/* ============================================================
   Fynch AI — workshop3.jsx  (slides 17–19)
   Source-to-fact trust map → Pilot Fact List.
   Reads/writes FynchStore.ws3.facts.
   ============================================================ */
(function () {
  const SEED = window.FYNCH_SEED;
  const isRisk = (f) => f.conf <= 2 && (f.importance === "Critical" || f.importance === "High");

  /* ---- Slide 17 — intro ---- */
  function Intro3() {
    const facts = ["Some facts are informational.", "Some need review.", "Some block a quote.", "Some block a memo."];
    return (
      <div className="slide-pad" style={{ justifyContent: "center" }}>
        <div className="ws-badge" data-rise style={{ color: "var(--brand-300)", marginBottom: 22 }}><span className="num">3</span>WORKSHOP THREE</div>
        <h2 className="slide-h2" data-rise style={{ "--i": 1, fontSize: 64, maxWidth: 1300 }}>Build the source-to-fact trust map.</h2>
        <p className="lead" data-rise style={{ "--i": 2, marginTop: 18, fontSize: 27 }}>We pressure-test the facts that actually matter — which need evidence, and where human judgment stays in the loop.</p>
        <div data-rise style={{ "--i": 3, marginTop: 44, display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14 }}>
          {facts.map((t, i) => (
            <div key={i} className="card" style={{ padding: "22px 20px", display: "flex", flexDirection: "column", gap: 12 }}>
              <span className="numbadge ghost">{i + 1}</span>
              <span style={{ fontSize: 19, color: "#dbe4f1", lineHeight: 1.35 }}>{t}</span>
            </div>
          ))}
        </div>
        <div data-rise style={{ "--i": 4, marginTop: 30 }}>
          <div className="label-meta" style={{ color: "#5b6b86", marginBottom: 12 }}>For each critical fact</div>
          <WordFlowDark words={["Primary source", "Backup source", "Confidence", "Reviewer", "Importance", "What breaks if wrong"]} />
        </div>
        <Foot no={17} section="Workshop 3" />
      </div>
    );
  }
  function WordFlowDark({ words }) {
    return <div style={{ display: "flex", gap: 14, flexWrap: "wrap", fontFamily: "var(--font-mono)", fontSize: 17, color: "#8696b3" }}>{words.map((w, i) => <React.Fragment key={w}>{i > 0 && <span style={{ color: "var(--brand-400)" }}>·</span>}<span style={{ color: "#c4cfdf" }}>{w}</span></React.Fragment>)}</div>;
  }

  /* ---- Slide 18 — trust table ---- */
  function TrustMap() {
    const store = useStore();
    const locked = FynchStore.isLocked("ws3");
    const [filter, setFilter] = useState("all");
    const facts = store.ws3.facts;
    function patch(id, fn) { FynchStore.update((s) => { const f = s.ws3.facts.find((x) => x.id === id); if (f) fn(f); }); }
    const filtered = facts.filter((f) => {
      if (filter === "quote") return f.quote;
      if (filter === "memo") return f.memo;
      if (filter === "review") return f.importance === "Critical" || f.importance === "High";
      if (filter === "risk") return isRisk(f);
      return true;
    });
    const coverage = Math.round((facts.filter((f) => f.conf >= 4).length / facts.length) * 100);
    const FILTERS = [["all", "All facts"], ["quote", "Quote blockers"], ["memo", "Memo blockers"], ["review", "Review required"], ["risk", "Low conf · high importance"]];
    return (
      <div className="slide-pad">
        <div className="ws" style={{ gap: 14 }}>
          <WsHeader n="3" wsKey="ws3" title="Critical fact trust map" sub="Click confidence pips · toggle blockers · rows turn red when low confidence meets high importance"
            right={<button className="btn primary sm" onClick={() => { location.hash = "19"; }}>Generate Pilot Fact List<Icon name="arrowR" size={15} /></button>} />
          <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }} data-rise>
            <div className="coverage-meter"><span className="label-meta">Evidence coverage</span><span className="bar"><span className="fill" style={{ width: coverage + "%" }}></span></span><b style={{ fontVariantNumeric: "tabular-nums" }}>{coverage}%</b></div>
            <div style={{ display: "flex", gap: 7, marginLeft: "auto", flexWrap: "wrap" }}>
              {FILTERS.map(([k, l]) => <button key={k} className={"btn sm " + (filter === k ? "primary" : "secondary")} onClick={() => setFilter(k)}>{l}</button>)}
            </div>
          </div>
          <div className="trust-tbl grow" data-rise style={{ "--i": 1, overflow: "auto", border: "1px solid var(--line-200)", borderRadius: 8, background: "var(--surface)" }}>
            <table>
              <thead>
                <tr>
                  <th>Fact</th><th>Primary</th><th>Secondary</th><th className="c">Confidence</th><th>Reviewer</th><th className="c">Importance</th><th className="c">Quote</th><th className="c">Memo</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((f) => (
                  <tr key={f.id} className={isRisk(f) ? "risk" : ""}>
                    <td className="fact">{f.fact}</td>
                    <td>{f.primary}</td>
                    <td style={{ color: "var(--ink-500)" }}>{f.secondary}</td>
                    <td className="c">
                      <span className="conf-pip">{[1, 2, 3, 4, 5].map((p) => <span key={p} className={"p" + (f.conf >= p ? " on " + (f.conf <= 2 ? "lo" : f.conf === 3 ? "md" : "") : "")} onClick={() => !locked && patch(f.id, (x) => (x.conf = p))}></span>)}</span>
                    </td>
                    <td>{f.reviewer || (f.importance === "Critical" ? "Senior credit" : "Analyst")}</td>
                    <td className="c">
                      <select className="imp-select" value={f.importance} disabled={locked} onChange={(e) => patch(f.id, (x) => (x.importance = e.target.value))} style={{ maxWidth: 110 }}>
                        {SEED.IMPORTANCE.map((o) => <option key={o}>{o}</option>)}
                      </select>
                    </td>
                    <td className="c"><span className={"blocker-dot" + (f.quote ? " on" : "")} onClick={() => !locked && patch(f.id, (x) => (x.quote = !x.quote))}>{f.quote ? "Y" : "—"}</span></td>
                    <td className="c"><span className={"blocker-dot" + (f.memo ? " on" : "")} onClick={() => !locked && patch(f.id, (x) => (x.memo = !x.memo))}>{f.memo ? "Y" : "—"}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <Foot no={18} section="Workshop 3" />
      </div>
    );
  }

  /* ---- Slide 19 — Pilot Fact List (auto-output) ---- */
  function PilotList() {
    const store = useStore();
    const facts = store.ws3.facts;
    const priority = facts.filter((f) => f.importance === "Critical" || f.importance === "High" || f.quote || f.memo || isRisk(f));
    const quoteBlockers = facts.filter((f) => f.quote);
    const memoBlockers = facts.filter((f) => f.memo);
    const reviewReq = facts.filter((f) => isRisk(f));
    return (
      <div className="slide-pad">
        <SlideHead kicker="Workshop 3 · output" h2="Pilot fact list." sub="Generated from the trust map — the starting requirements for a sample deal review." />
        <div className="cols c2-wide-r grow" style={{ alignItems: "stretch" }}>
          <div className="stack gap-m" data-rise>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              {[[priority.length, "priority facts"], [quoteBlockers.length, "quote blockers"], [memoBlockers.length, "memo blockers"], [reviewReq.length, "require human review"]].map(([n, l]) => (
                <div key={l} className="auto-panel" style={{ padding: "18px 20px" }}><div className="auto-stat"><span className="n">{n}</span><span className="l">{l}</span></div></div>
              ))}
            </div>
            <div className="card pad" style={{ background: "var(--brand-500)", borderColor: "var(--brand-500)" }}>
              <div style={{ color: "rgba(255,255,255,.8)", fontSize: 13, fontWeight: 600, letterSpacing: ".5px", textTransform: "uppercase", marginBottom: 8 }}>Already a pilot artifact</div>
              <div style={{ color: "#fff", fontSize: 20, fontWeight: 500, lineHeight: 1.4 }}>It tells us what to extract, what evidence to show, and where people stay in the review loop.</div>
            </div>
          </div>
          <div className="doc-preview" data-rise style={{ "--i": 1, height: "100%" }}>
            <div className="doc-bar"><span className="dot" style={{ background: "#f87171" }}></span><span className="dot" style={{ background: "#fbbf24" }}></span><span className="dot" style={{ background: "#34d399" }}></span><span className="fn">pilot_fact_list.pdf</span></div>
            <div className="doc-body">
              <h3>Priority Fact List — Sample Deal Review</h3>
              <p className="doc-sub">{priority.length} facts · evidence standard · reviewer · blockers</p>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
                <thead><tr>{["Fact", "Required source", "Reviewer", "Conf", "Blocks"].map((h) => <th key={h} style={{ textAlign: "left", padding: "7px 8px", fontSize: 10.5, letterSpacing: ".5px", textTransform: "uppercase", color: "var(--ink-400)", borderBottom: "1px solid var(--line-200)" }}>{h}</th>)}</tr></thead>
                <tbody>
                  {priority.slice(0, 14).map((f) => (
                    <tr key={f.id}>
                      <td style={{ padding: "7px 8px", fontWeight: 600, borderBottom: "1px solid var(--line-100)" }}>{f.fact}</td>
                      <td style={{ padding: "7px 8px", color: "var(--ink-600)", borderBottom: "1px solid var(--line-100)" }}>{f.primary}</td>
                      <td style={{ padding: "7px 8px", color: "var(--ink-600)", borderBottom: "1px solid var(--line-100)" }}>{f.importance === "Critical" ? "Senior credit" : "Analyst"}</td>
                      <td style={{ padding: "7px 8px", borderBottom: "1px solid var(--line-100)", color: f.conf <= 2 ? "var(--conflict-fg)" : "var(--approved-fg)", fontWeight: 600 }}>{(f.conf / 5).toFixed(2)}</td>
                      <td style={{ padding: "7px 8px", borderBottom: "1px solid var(--line-100)" }}>{[f.quote && "Quote", f.memo && "Memo"].filter(Boolean).join(" · ") || "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {priority.length > 14 && <div style={{ marginTop: 10, fontSize: 12, color: "var(--ink-400)", fontFamily: "var(--font-mono)" }}>+ {priority.length - 14} more facts in export</div>}
            </div>
          </div>
        </div>
        <Foot no={19} section="Workshop 3" />
      </div>
    );
  }

  window.registerSlides([
    { no: 17, section: "Workshop 3", dark: true, Comp: Intro3 },
    { no: 18, section: "Workshop 3", ws: "ws3", Comp: TrustMap },
    { no: 19, section: "Workshop 3", ws: "ws3", Comp: PilotList },
  ]);
})();
