// ═══════════════════════════════════════════════════════════════════
// INTELLIGENCE REPORT — the single universal shell for EVERY project.
//
// One layout, driven by the Report Schema (RPT-v3). The shell owns the
// chrome (header · SECTION selector · headline metrics) and the four
// UNIVERSAL section renderers — Thesis · Diligence · Readiness · Sources —
// which render identically for every asset class from a normalized
// `report` object. CLASS-SPECIFIC sections (subject · instrument ·
// underwriting) are supplied per project as render functions, exactly the
// design seam the schema declares (RS-10/11/12 — each class owns its own).
//
// A project registers its data: window.INTEL_REPORTS[projectId] = report.
// Universal sections are data-driven and render OPTIONAL sub-sections
// (entity stack, filing pipeline, …) only when the data is present — so
// richer classes lose nothing and leaner ones stay clean.
// ═══════════════════════════════════════════════════════════════════
(function () {
  const { useState } = React;
  window.INTEL_REPORTS = window.INTEL_REPORTS || {};

  // ── shared helpers ─────────────────────────────────────────────────
  const mono = (s, extra) => <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-4)", ...extra }}>{s}</span>;
  const card = (extra) => ({ border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", background: "var(--bg)", padding: "15px 17px", ...extra });
  const sevTone = (s) => ({ high: "err", med: "warn", low: "neutral" }[String(s).toLowerCase()] || "neutral");
  const SEV_COLOR = { high: "var(--err)", med: "var(--warn)", low: "var(--ink-4)" };
  const PRI_TONE = { P0: "err", P1: "warn", P2: "info" };
  const cell = (c, extra) => ({ background: "var(--bg)", padding: "9px 12px", fontSize: "var(--fs-xs)", color: c || "var(--ink-2)", lineHeight: 1.55, ...extra });
  const mkBadge = (CLASS) => ({ cls, short }) => { const m = (CLASS && CLASS[cls]) || {}; return <window.Pill tone={m.tone || "neutral"} title={m.note}>{short ? cls : (m.label || cls)}</window.Pill>; };

  // ── time-aware digest helpers ──────────────────────────────────────
  const isNew = (item) => !!(item && (item.new || item.isNew));
  const NewPill = ({ label }) => (
    <span style={{ fontFamily: "var(--mono)", fontSize: "7.5px", fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--bg)", background: "var(--accent)", borderRadius: "999px", padding: "1px 6px", whiteSpace: "nowrap", flex: "0 0 auto" }}>{label || "new"}</span>
  );
  const DIG_TONE = { new: "var(--accent)", updated: "var(--warn)", resolved: "var(--ok)" };
  const IMP_COLOR = { high: "var(--ok)", med: "var(--accent)", low: "var(--ink-4)" };
  const impTone = (s) => ({ high: "ok", med: "accent", low: "neutral" }[String(s).toLowerCase()] || "neutral");

  function Grid({ cols, headers, children, mb }) {
    return (
      <div style={{ border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden", marginBottom: mb == null ? 0 : mb }}>
        <div style={{ display: "grid", gridTemplateColumns: cols, gap: 1, background: "var(--rule)" }}>
          {headers.map((h, i) => <div key={i} style={{ background: "var(--bg-2)", padding: "8px 12px" }}><window.MonoLabel>{h}</window.MonoLabel></div>)}
          {children}
        </div>
      </div>
    );
  }

  // ── canonical slot order, paired index-for-index with groupsForClass ─
  const SLOTS = ["thesis", "subject", "instrument", "underwriting", "diligence", "readiness", "sources", "opportunities", "structure"];
  const CLASS_SLOTS = ["subject", "instrument", "underwriting"];
  // the four delivered parts — read from the schema, with a local fallback
  const FALLBACK_PARTS = [
    { id: "brief",     name: "Executive Brief",     cadence: "weekly",    slots: ["thesis"],                                classSpecific: false, sub: "verdict · thesis · findings · risks — opening with the change digest" },
    { id: "passport",  name: "Product Passport",    cadence: "monthly",   slots: ["subject", "instrument", "underwriting"], classSpecific: true,  sub: "the subject · the instrument · the model" },
    { id: "intel",     name: "Intelligence Report", cadence: "monthly",   slots: ["diligence", "structure", "sources"],     classSpecific: false, sub: "verification · contradictions · evidence gaps · structural relations · sourcing" },
    { id: "strategic", name: "Strategic Review",    cadence: "quarterly", slots: ["readiness", "opportunities"],            classSpecific: false, sub: "gates · ranked actions · opportunity register" },
  ];

  // ── time-aware change digest — what's new/updated since the last version
  function DigestStrip({ D }) {
    const dg = D.digest;
    if (!dg || !dg.items || !dg.items.length) return null;
    return (
      <div style={{ border: "1px solid var(--accent-bd)", borderLeft: "3px solid var(--accent)", borderRadius: "var(--r-3)", background: "var(--accent-bg)", padding: "13px 16px", marginBottom: "var(--s-5)" }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 9, flexWrap: "wrap", marginBottom: 9 }}>
          <span style={{ fontFamily: "var(--ui-display)", fontWeight: 700, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>What&rsquo;s New</span>
          <NewPill label={dg.items.filter((i) => i.status !== "updated").length + " new"} />
          {mono((dg.prev ? dg.prev + " → " : "") + (D.version || "current") + " · since " + (dg.since || dg.asOf || "last run"), { color: "var(--accent-lo)" })}
        </div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          {dg.items.map((it, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "58px 92px 1fr", gap: 10, alignItems: "baseline", borderTop: i ? "1px solid var(--accent-bd)" : "none", padding: "7px 0" }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: "8px", fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: DIG_TONE[it.status] || "var(--accent)" }}>{it.status || "new"}</span>
              <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--ink-4)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.where || it.ref}</span>
              <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.5 }}>{it.text}{it.ref && <span style={{ fontFamily: "var(--mono)", fontSize: "8px", color: "var(--ink-4)" }}> · {it.ref}</span>}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── UNIVERSAL · 08 — Opportunity Register (G8), symmetric to risk ──
  function OpportunitySection({ D }) {
    const ops = D.opportunities || [];
    if (!ops.length) {
      return (
        <div>
          <window.SectionHead sub="forward upside — surfaced by market research, each with evidence, confidence and a strategic-impact score">Opportunity Register</window.SectionHead>
          <div style={card({ background: "var(--bg-2)" })}><p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink-3)" }}>No opportunities logged yet — market research surfaces these as the deal develops.</p></div>
        </div>
      );
    }
    return (
      <div>
        <window.SectionHead sub="forward upside — symmetric to the risk register; each opportunity carries evidence, confidence and a strategic-impact score (RS-13)">Opportunity Register</window.SectionHead>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
          {ops.map((o) => (
            <div key={o.id} style={{ border: "1px solid var(--rule-soft)", borderRadius: "var(--r-2)", padding: "11px 13px", borderLeft: "3px solid " + (IMP_COLOR[String(o.impact).toLowerCase()] || "var(--accent)"), background: "var(--bg)" }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap", marginBottom: 5 }}>
                <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", color: "var(--ink-4)" }}>{o.id}</span>
                <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{o.title}</span>
                {isNew(o) && <NewPill />}
                <span style={{ marginLeft: "auto", display: "inline-flex", gap: 6, alignItems: "center" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: "8px", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-4)", border: "1px solid var(--rule-hard)", borderRadius: "999px", padding: "1px 7px" }}>{o.cat}</span>
                  <window.Pill tone={impTone(o.impact)}>{o.impact} impact</window.Pill>
                </span>
              </div>
              <p style={{ margin: "0 0 7px", fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.5 }}>{o.desc}</p>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                {mono("confidence")}
                <span style={{ flex: 1, height: 5, background: "var(--bg-3)", borderRadius: 3, overflow: "hidden" }}><span style={{ display: "block", width: (o.conf || 0) + "%", height: "100%", background: "var(--accent)", borderRadius: 3 }}></span></span>
                <span style={{ fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 600, color: "var(--accent-lo)" }}>{o.conf}/100</span>
              </div>
              {o.evidence && <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 8, alignItems: "baseline" }}>{mono("evidence")}<span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.5 }}>{o.evidence}</span></div>}
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── UNIVERSAL · 01 — Thesis & Verdict (G1) ─────────────────────────
  function ThesisSection({ D }) {
    const Badge = mkBadge(D.CLASS);
    const v = D.verdict || {};
    return (
      <div>
        {D.metrics && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(" + D.metrics.length + ", 1fr)", gap: 1, background: "var(--rule)", border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden", marginBottom: "var(--s-5)" }}>
            {D.metrics.map(([l, vv, s]) => (
              <div key={l} style={{ background: "var(--bg)", padding: "12px 14px" }}>
                {mono(l, { display: "block", marginBottom: 5 })}
                <div style={{ fontFamily: "var(--ui-display)", fontWeight: 700, fontSize: "19px", lineHeight: 1, letterSpacing: "-0.01em", color: vv === "—" ? "var(--ink-4)" : "var(--ink)", whiteSpace: "nowrap" }}>{vv}</div>
                <div style={{ marginTop: 4, fontSize: "var(--fs-xs)", color: "var(--ink-4)", lineHeight: 1.45 }}>{s}</div>
              </div>
            ))}
          </div>
        )}
        <div style={{ ...card({ borderColor: "var(--warn)", borderLeftWidth: 3, background: "var(--bg-2)", padding: "18px 20px" }), display: "grid", gridTemplateColumns: "1fr 240px", gap: 22, alignItems: "center", marginBottom: "var(--s-5)" }}>
          <div>
            {mono("platform verdict · generated from " + (D.kbLen || 0) + " sourced facts", { display: "block", marginBottom: 8 })}
            <p style={{ margin: "0 0 7px", fontFamily: "var(--ui-display)", fontWeight: 700, fontSize: "var(--fs-lg)", color: "var(--ink)", lineHeight: 1.25 }}>{v.headline}</p>
            <p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink-2)", lineHeight: 1.6 }}>{v.body}</p>
          </div>
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
              {mono("confidence")}
              <span style={{ fontFamily: "var(--mono)", fontSize: "11px", fontWeight: 700, color: "var(--accent-lo)" }}>{v.confidence} / 100</span>
            </div>
            <div style={{ height: 7, background: "var(--bg-3)", borderRadius: 4, overflow: "hidden" }}>
              <div style={{ width: (v.confidence || 0) + "%", height: "100%", background: "var(--accent)", borderRadius: 4 }}></div>
            </div>
            {v.pills && (
              <div style={{ display: "flex", gap: 5, flexWrap: "wrap", marginTop: 10 }}>
                {v.pills.map(([k, vv]) => (
                  <span key={k} style={{ display: "inline-flex", alignItems: "baseline", gap: 5, border: "1px solid var(--rule-hard)", borderRadius: "var(--r-1)", padding: "2px 7px", background: "var(--bg)" }}>
                    {mono(k)}<span style={{ fontFamily: "var(--mono)", fontSize: "10px", fontWeight: 600, color: "var(--ink)" }}>{vv}</span>
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>

        <window.SectionHead sub="the case for the deal — and the counterweight">Investment Thesis</window.SectionHead>
        <div style={card()}>
          <p style={{ margin: "0 0 12px", fontSize: "var(--fs-md)", fontWeight: 600, color: "var(--ink)", lineHeight: 1.45 }}>{D.thesis.headline}</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 28px" }}>
            {D.thesis.pillars.map((p, i) => (
              <div key={p.t} style={{ display: "grid", gridTemplateColumns: "92px 1fr", gap: 10, borderTop: i < 2 ? "none" : "1px solid var(--rule-soft)", padding: "9px 0" }}>
                <span style={{ fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--accent-lo)" }}>{p.t}</span>
                <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.55 }}>{p.d}</span>
              </div>
            ))}
          </div>
          {D.thesis.counterweight && <p style={{ margin: "12px 0 0", paddingTop: 12, borderTop: "1px solid var(--rule-soft)", fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.55, fontStyle: "italic" }}>{D.thesis.counterweight}</p>}
        </div>

        <window.SectionHead sub="material findings · classified — the full fact ledger lives in the Knowledge Base">What We Found</window.SectionHead>
        <div style={card()}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {D.findings.map((f, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 10, alignItems: "baseline", borderTop: i ? "1px solid var(--rule-soft)" : "none", padding: "8px 0" }}>
                <Badge cls={f.cls} />
                <span style={{ fontSize: "var(--fs-sm)", color: "var(--ink-2)", lineHeight: 1.55 }}>{f.text}</span>
              </div>
            ))}
          </div>
          {D.classCounts && (
            <div style={{ borderTop: "1px solid var(--rule-soft)", marginTop: 8, paddingTop: 10, display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
              {mono("fact ledger")}
              {Object.entries(D.classCounts).map(([k, n]) => n > 0 && (
                <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                  <Badge cls={k} short /><span style={{ fontFamily: "var(--mono)", fontSize: "10px", fontWeight: 600, color: "var(--ink-2)" }}>{n}</span>
                </span>
              ))}
            </div>
          )}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: D.asks ? "1fr 1fr" : "1fr", gap: 14, marginTop: "var(--s-5)" }}>
          {[["strengths", D.strengths, "var(--ok)"], D.asks ? ["asks before close", D.asks, "var(--info)"] : null].filter(Boolean).map(([t, list, color]) => (
            <div key={t} style={card()}>
              {mono(t, { display: "block", marginBottom: 8, color })}
              <div style={{ display: "flex", flexDirection: "column" }}>
                {list.map((s, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "10px 1fr", gap: 8, borderTop: i ? "1px solid var(--rule-soft)" : "none", padding: "7px 0" }}>
                    <span style={{ color, fontSize: 10, lineHeight: 1.8 }}>▪</span>
                    <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.55 }}>{s}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        {D.risks && D.risks.length > 0 && (
          <div>
            <window.SectionHead sub="the downside, rated — every item carries severity and a mitigation">Risk Register</window.SectionHead>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
              {D.risks.map((r) => (
                <div key={r.id} style={{ border: "1px solid var(--rule-soft)", borderRadius: "var(--r-2)", padding: "11px 13px", borderLeft: "3px solid " + (SEV_COLOR[String(r.sev).toLowerCase()] || "var(--ink-4)"), background: "var(--bg)" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap", marginBottom: 5 }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", color: "var(--ink-4)" }}>{r.id}</span>
                    <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{r.title}</span>
                    <span style={{ marginLeft: "auto", display: "inline-flex", gap: 6, alignItems: "center" }}>
                      <span style={{ fontFamily: "var(--mono)", fontSize: "8px", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-4)", border: "1px solid var(--rule-hard)", borderRadius: "999px", padding: "1px 7px" }}>{r.cat}</span>
                      <window.Pill tone={sevTone(r.sev)}>{r.sev}</window.Pill>
                    </span>
                  </div>
                  <p style={{ margin: "0 0 6px", fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.5 }}>{r.desc}</p>
                  {r.mitig && <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 8, alignItems: "baseline" }}>{mono("mitigation")}<span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.5 }}>{r.mitig}</span></div>}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  // ── UNIVERSAL · 05 — Diligence (G5) ────────────────────────────────
  function DiligenceSection({ D }) {
    const Badge = mkBadge(D.CLASS);
    const dg = D.diligence || {};
    return (
      <div>
        {dg.framing && (
          <div style={{ ...card({ borderColor: "var(--warn)", borderLeftWidth: 3, background: "var(--bg-2)", padding: "12px 16px" }), display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: "var(--s-5)" }}>
            <window.Pill tone="warn">{dg.framing.tag}</window.Pill>
            <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.5, flex: 1, minWidth: 260 }}>{dg.framing.text}</span>
          </div>
        )}
        <window.SectionHead sub={dg.verifyNote || "material claims cross-checked against their single source"}>Verification</window.SectionHead>
        {dg.verifyMix && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(" + dg.verifyMix.length + ", 1fr)", gap: 1, background: "var(--rule)", border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden", marginBottom: 14 }}>
            {dg.verifyMix.map(([cls, n, note]) => (
              <div key={cls} style={{ background: "var(--bg)", padding: "12px 14px" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                  <Badge cls={cls} /><span style={{ fontFamily: "var(--ui-display)", fontWeight: 700, fontSize: "18px", color: "var(--ink)" }}>{n}</span>
                </div>
                <div style={{ fontSize: "10px", color: "var(--ink-4)", marginTop: 5, lineHeight: 1.45 }}>{note}</div>
              </div>
            ))}
          </div>
        )}
        {dg.verification && dg.verification.length > 0 && (
          <Grid cols="minmax(190px,0.9fr) 1.4fr 110px" headers={["Material claim", "How the platform checked it", "Class"]} mb={14}>
            {dg.verification.map((v, i) => (
              <React.Fragment key={i}>
                <div style={cell("var(--ink)", { fontWeight: 500, fontSize: "var(--fs-sm)" })}>{v.claim}</div>
                <div style={cell("var(--ink-3)")}>{v.finding}</div>
                <div style={{ background: "var(--bg)", padding: "9px 12px" }}><Badge cls={v.cls} /></div>
              </React.Fragment>
            ))}
          </Grid>
        )}
        <window.SectionHead sub="where two sources disagree — severity and the resolution path">Contradictions</window.SectionHead>
        <Grid cols="52px 1fr 1fr 1.1fr 64px 1fr" headers={["ID", "Source A", "Source B", "Conflict", "Sev", "Resolution"]} mb={18}>
          {(dg.contradictions || []).map((x) => (
            <React.Fragment key={x.id}>
              <div style={cell("var(--ink-4)", { fontFamily: "var(--mono)", fontSize: "9px" })}>{x.id}</div>
              <div style={cell()}>{x.a}</div>
              <div style={cell()}>{x.b}</div>
              <div style={cell("var(--ink)", { fontWeight: 500 })}>{x.conflict}</div>
              <div style={{ background: "var(--bg)", padding: "9px 12px" }}><window.Pill tone={sevTone(x.sev)}>{x.sev}</window.Pill></div>
              <div style={cell("var(--ink-3)")}>{x.fix}</div>
            </React.Fragment>
          ))}
        </Grid>

        <window.SectionHead sub="what must be evidenced — every gap names the document that closes it, and by when">Open Evidence Gaps</window.SectionHead>
        <Grid cols="56px 1.1fr 60px 1.4fr 1.4fr 1fr" headers={["ID", "Gap", "Sev", "Where it stands today", "What closes it", "Due"]} mb={0}>
          {(dg.gaps || []).map((g) => (
            <React.Fragment key={g.id}>
              <div style={cell("var(--ink-4)", { fontFamily: "var(--mono)", fontSize: "9px" })}>{g.id}</div>
              <div style={cell("var(--ink)", { fontWeight: 500, fontSize: "var(--fs-sm)" })}>{g.gap}</div>
              <div style={{ background: "var(--bg)", padding: "9px 12px" }}><window.Pill tone={sevTone(g.sev)}>{g.sev}</window.Pill></div>
              <div style={cell("var(--ink-3)")}>{g.today}</div>
              <div style={cell()}>{g.closes}</div>
              <div style={cell("var(--ink-3)", { fontFamily: "var(--mono)", fontSize: "9px" })}>{g.due}</div>
            </React.Fragment>
          ))}
        </Grid>
      </div>
    );
  }

  // ── UNIVERSAL · 06 — Readiness (G6) ────────────────────────────────
  function ReadinessSection({ D }) {
    const rd = D.readiness || {};
    return (
      <div>
        <window.SectionHead sub="go / no-go gates — recompute as evidence lands">Readiness</window.SectionHead>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
          {(rd.paths || []).map((p) => {
            const done = p.items.filter((i) => i.ok).length;
            return (
              <div key={p.path} style={{ border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden", background: "var(--bg)" }}>
                <div style={{ background: "var(--bg-dark)", color: "#fff", padding: "11px 15px", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)" }}>{p.path}</span>
                  <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: "10px", color: "var(--accent-hi)" }}>{done}/{p.items.length} gates</span>
                    <window.Pill tone={p.ok ? "ok" : "warn"}>{p.verdict}</window.Pill>
                  </span>
                </div>
                <div style={{ padding: "10px 15px" }}>
                  <div style={{ display: "flex", gap: 3, marginBottom: 10 }}>
                    {p.items.map((it, i) => (<div key={i} title={it.what} style={{ flex: 1, height: 6, borderRadius: 3, background: it.ok ? "var(--ok)" : "var(--bg-3)" }}></div>))}
                  </div>
                  {p.items.map((it, i) => (
                    <div key={i} style={{ display: "grid", gridTemplateColumns: "16px 1fr auto", gap: 8, alignItems: "baseline", borderTop: i ? "1px solid var(--rule-soft)" : "none", padding: "6px 0" }}>
                      <span style={{ color: it.ok ? "var(--ok)" : "var(--ink-5)", fontSize: "11px" }}>{it.ok ? "●" : "○"}</span>
                      <span style={{ fontSize: "var(--fs-xs)", color: it.ok ? "var(--ink-2)" : "var(--ink)", fontWeight: it.ok ? 400 : 500 }}>{it.what}</span>
                      <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", color: "var(--ink-4)", whiteSpace: "nowrap" }}>{it.note}</span>
                    </div>
                  ))}
                  {p.note && <p style={{ margin: "8px 0 0", fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.5 }}>{p.note}</p>}
                </div>
              </div>
            );
          })}
        </div>

        {(D.diligence || {}).filings && (D.diligence || {}).filings.length > 0 && (
          <div>
            <window.SectionHead sub="what must be filed, in dependency order — the regulatory gate sequence to launch (generic to any exempt offering)">Filing Pipeline</window.SectionHead>
            <Grid cols="210px 84px 1fr" headers={["Filing", "Status", "Detail"]} mb={0}>
              {(D.diligence || {}).filings.map((f, i) => (
                <React.Fragment key={i}>
                  <div style={cell("var(--ink)", { fontWeight: 500, fontSize: "var(--fs-sm)" })}>{f.name}</div>
                  <div style={{ background: "var(--bg)", padding: "9px 12px" }}><window.Pill tone={f.statusTone || "neutral"}>{f.statusLabel || f.status}</window.Pill></div>
                  <div style={cell("var(--ink-3)")}>{f.detail}</div>
                </React.Fragment>
              ))}
            </Grid>
          </div>
        )}

        <window.SectionHead sub="ranked · every action gated on the evidence above">Recommended Actions</window.SectionHead>
        <Grid cols="36px 1.1fr 1.5fr 64px" headers={["#", "Recommended action", "Rationale (evidence)", "Priority"]} mb={0}>
          {(rd.actions || []).map((a) => {
            const [n, action, rationale, pri] = Array.isArray(a) ? a : [a.n, a.action, a.rationale, a.pri];
            return (
              <React.Fragment key={n}>
                <div style={cell("var(--ink-4)", { fontFamily: "var(--mono)", fontWeight: 600 })}>{n}</div>
                <div style={cell("var(--ink)", { fontWeight: 500, fontSize: "var(--fs-sm)" })}>{action}</div>
                <div style={cell("var(--ink-3)")}>{rationale}</div>
                <div style={{ background: "var(--bg)", padding: "9px 12px" }}><window.Pill tone={PRI_TONE[pri] || "neutral"}>{pri}</window.Pill></div>
              </React.Fragment>
            );
          })}
        </Grid>
      </div>
    );
  }

  // ── UNIVERSAL · 07 — Sources (G7) ──────────────────────────────────
  function SourcesSection({ D, go, standalone }) {
    const sr = D.sources || {};
    if (sr.render) return sr.render(go, standalone);
    const reg = sr.registry || [];
    const relTone = (n) => (n >= 80 ? "var(--ok)" : n >= 55 ? "var(--warn)" : "var(--err)");
    return (
      <div>
        <window.SectionHead sub="every fact cites one source — with a reliability score, version and a page/section citation locator; the sourced facts themselves live in the Knowledge Base">Citation Registry</window.SectionHead>
        {sr.note && <p style={{ margin: "0 0 14px", fontSize: "var(--fs-sm)", color: "var(--ink-3)", lineHeight: 1.6, maxWidth: "94ch" }}>{sr.note}</p>}
        {reg.length > 0 ? (
          <Grid cols="74px 64px 1.6fr 92px 1.05fr 104px 44px" headers={["ID", "Type", "Source", "Reliability", "Citation", "Ingested", "Facts"]} mb={0}>
            {reg.map((r) => (
              <React.Fragment key={r.id}>
                <div style={cell("var(--accent-lo)", { fontFamily: "var(--mono)", fontSize: "10px", fontWeight: 600 })}>{r.id}</div>
                <div style={{ background: "var(--bg)", padding: "9px 12px" }}><window.Pill tone={r.kind === "doc" ? "info" : "neutral"}>{r.kind}</window.Pill></div>
                <div style={{ background: "var(--bg)", padding: "9px 12px" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 7, flexWrap: "wrap" }}>
                    <span style={{ fontSize: "var(--fs-sm)", fontWeight: 500, color: "var(--ink)", lineHeight: 1.4 }}>{r.name}</span>
                    {isNew(r) && <NewPill />}
                  </div>
                  {(r.author || r.dept || r.version || r.related) && <div style={{ fontFamily: "var(--mono)", fontSize: "8px", color: "var(--ink-4)", marginTop: 2, lineHeight: 1.45 }}>{[r.author, r.dept, r.version && ("v" + r.version)].filter(Boolean).join(" · ")}{r.related ? " · ↳ " + r.related : ""}</div>}
                </div>
                <div style={{ background: "var(--bg)", padding: "9px 12px" }}>
                  {r.rel != null ? (
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 3 }}>
                        <span style={{ fontFamily: "var(--mono)", fontSize: "7.5px", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--ink-4)" }}>{r.tier || ""}</span>
                        <span style={{ fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 700, color: relTone(r.rel) }}>{r.rel}</span>
                      </div>
                      <span style={{ display: "block", height: 4, background: "var(--bg-3)", borderRadius: 2, overflow: "hidden" }}><span style={{ display: "block", width: r.rel + "%", height: "100%", background: relTone(r.rel), borderRadius: 2 }}></span></span>
                    </div>
                  ) : <span style={{ fontFamily: "var(--mono)", fontSize: "9px", color: "var(--ink-4)" }}>—</span>}
                </div>
                <div style={cell("var(--ink-4)", { fontFamily: "var(--mono)", fontSize: "8.5px", wordBreak: "break-word" })}>
                  {r.loc && <span style={{ display: "block", color: "var(--ink-2)" }}>{r.loc}</span>}
                  {r.url ? <a href={r.url} target="_blank" rel="noopener noreferrer" style={{ color: "var(--accent-lo)", textDecoration: "none" }}>{r.origin || r.url} ↗</a> : <span>{r.origin}</span>}
                </div>
                <div style={cell("var(--ink-3)", { fontFamily: "var(--mono)", fontSize: "8.5px" })}>
                  {r.uploaded && <span style={{ display: "block" }} title="uploaded to the data room"><span style={{ color: "var(--ink-4)" }}>↑ </span>{r.uploaded}</span>}
                  {r.parsed && <span style={{ display: "block", color: "var(--ink-2)" }} title={r.kind === "web" ? "retrieved & searched" : "parsed & extracted"}><span style={{ color: "var(--ink-4)" }}>{r.kind === "web" ? "⧉ " : "▤ "}</span>{r.parsed}</span>}
                  {!r.uploaded && !r.parsed && <span style={{ color: "var(--ink-4)" }}>—</span>}
                </div>
                <div style={cell("var(--ink-2)", { fontFamily: "var(--mono)", fontSize: "10px", fontWeight: 600, textAlign: "center" })}>{r.facts != null ? r.facts : "—"}</div>
              </React.Fragment>
            ))}
          </Grid>
        ) : (
          <div style={card({ background: "var(--bg-2)" })}><p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink-2)", lineHeight: 1.6 }}>{sr.note}</p></div>
        )}
        {reg.some((r) => r.author || r.dept || r.version) && (
          <p style={{ margin: "10px 0 0", fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.04em", color: "var(--ink-4)", lineHeight: 1.6 }}>
            Document metadata — author · department · version lineage · related documents (↳) — is carried per source; reliability is the source-reliability tier assigned at parse. Ingested shows ↑ upload / ▤ parse for documents and ⧉ retrieval for web sources.
          </p>
        )}
        <p style={{ margin: "var(--s-4) 0 0", fontFamily: "var(--mono)", fontSize: "9px", letterSpacing: "0.06em", color: "var(--ink-4)", lineHeight: 1.7 }}>
          Classifications: V verified · P self-reported · A assumption · H hypothesis · Q questionable · U unknown.
        </p>
      </div>
    );
  }

  // ── UNIVERSAL · 09 — Structural Relations (G9), from the Knowledge Graph ──
  function StructureSection({ D, go, standalone }) {
    const gi = D.graphInsights;
    const REL_TONE = { "at-risk": "err", flow: "accent", firm: "ok", open: "warn" };
    const REL_COLOR = { "at-risk": "var(--err)", flow: "var(--accent)", firm: "var(--ok)", open: "var(--warn)" };
    if (!gi) {
      return (
        <div>
          <window.SectionHead sub="insights read off the typed entity graph — the relationships the deal hangs on">Structural Relations</window.SectionHead>
          <div style={card({ background: "var(--bg-2)" })}><p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink-3)" }}>No structural read yet — the relationship map appears once the deal graph is built.</p></div>
        </div>
      );
    }
    return (
      <div>
        <window.SectionHead sub="the load-bearing edges the deal hangs on and the chains that carry control & value — flagged at-risk, value-flow or firm">Load-bearing &amp; At-risk Relationships</window.SectionHead>
        {gi.note && <p style={{ margin: "0 0 14px", fontSize: "var(--fs-sm)", color: "var(--ink-2)", lineHeight: 1.6 }}>{gi.note}</p>}
        <div style={{ ...card(), marginBottom: 14 }}>
          {(gi.relations || []).map((r, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 16px", gap: 10, alignItems: "start", borderTop: i ? "1px solid var(--rule-soft)" : "none", padding: "8px 0" }}>
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap", marginBottom: 3 }}>
                  <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{r.from}</span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: "9px", color: REL_COLOR[r.status] || "var(--ink-4)" }}>{r.rel}</span>
                  <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{r.to}</span>
                  <window.Pill tone={REL_TONE[r.status] || "neutral"}>{r.status}</window.Pill>
                </div>
                {r.note && <p style={{ margin: 0, fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.5 }}>{r.note}</p>}
              </div>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: REL_COLOR[r.status] || "var(--ink-4)", marginTop: 4 }}></span>
            </div>
          ))}

          {gi.chains && gi.chains.length > 0 && (
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--rule)" }}>
              {mono("dependency chains — how control & value flow", { display: "block", marginBottom: 8, color: "var(--ink-4)" })}
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {gi.chains.map((c, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "minmax(78px, auto) 1fr", gap: 12, alignItems: "baseline", borderLeft: "3px solid " + (REL_COLOR[c.status] || "var(--ink-4)"), paddingLeft: 10 }}>
                    {mono(c.label, { color: REL_COLOR[c.status] || "var(--ink-4)", whiteSpace: "nowrap" })}
                    <div style={{ lineHeight: 1.5 }}>
                      <span style={{ fontFamily: "var(--mono)", fontSize: "10.5px", fontWeight: 600, color: "var(--ink)" }}>{c.path}</span>
                      {c.note && <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)" }}> — {c.note}</span>}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {gi.insight && (
          <div style={{ ...card({ borderColor: "var(--accent-bd)", borderLeftWidth: 3, background: "var(--accent-bg)" }), marginBottom: 14 }}>
            {mono("structural insight", { display: "block", marginBottom: 6, color: "var(--accent-lo)" })}
            <p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink)", lineHeight: 1.6, fontWeight: 500 }}>{gi.insight}</p>
          </div>
        )}

        {!standalone && go && (
          <button onClick={() => go("graph")} style={{ marginTop: 4, border: "none", background: "transparent", color: "var(--ink-4)", cursor: "pointer", fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.06em", textTransform: "uppercase", padding: 0 }}>full graph ↗</button>
        )}
      </div>
    );
  }

  // ── class-specific fallback — schema skeleton when a class supplies no body
  function LensTemplate({ classId, slot }) {
    const SCHEMA = window.REPORT_SCHEMA;
    const groups = (SCHEMA && SCHEMA.groupsForClass) ? SCHEMA.groupsForClass(classId) : [];
    const gid = { subject: "G2", instrument: "G3", underwriting: "G4" }[slot];
    const g = groups.find((x) => x.id === gid);
    if (!g) return null;
    return (
      <div>
        <window.SectionHead sub="the sub-sections and findings for this section — each fact sourced from the Knowledge Base">{g.label}</window.SectionHead>
        {g.subs.map((sub) => (
          <div key={sub.id} style={{ ...card(), marginBottom: 12 }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 8 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 600, color: "var(--ink-4)" }}>{sub.id}</span>
              <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{sub.label}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {sub.cards.map(([type, def, step], i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "92px 1fr 88px", gap: 10, alignItems: "baseline", borderTop: i ? "1px solid var(--rule-soft)" : "none", padding: "6px 0" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--accent-lo)" }}>{type}</span>
                  <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.5 }}>{def}</span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: "8px", color: "var(--ink-4)", textAlign: "right" }}>{step}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ── the shell ──────────────────────────────────────────────────────
  function IntelligenceReport({ proj, tenant, go, standalone, part: partProp, setPart: setPartProp }) {
    const [partLocal, setPartLocal] = useState("brief");
    const part = partProp != null ? partProp : partLocal;
    const setPart = setPartProp || setPartLocal;
    const D = (window.INTEL_REPORTS && window.INTEL_REPORTS[proj.id]) || null;
    const classId = D ? D.classId : (window.AssetClass ? window.AssetClass.of(proj) : "equity");
    const SCHEMA = window.REPORT_SCHEMA;
    const groups = (SCHEMA && SCHEMA.groupsForClass) ? SCHEMA.groupsForClass(classId) : [];
    // four delivered parts (schema-driven) over the canonical slots
    const PARTS = (SCHEMA && (SCHEMA.REPORTS || SCHEMA.PARTS)) || FALLBACK_PARTS;
    const slotGroup = {}; SLOTS.forEach((slot, i) => { slotGroup[slot] = groups[i]; });
    const renderSlot = (slot) => {
      if (slot === "thesis") return <ThesisSection D={D} />;
      if (slot === "diligence") return <DiligenceSection D={D} />;
      if (slot === "readiness") return <ReadinessSection D={D} />;
      if (slot === "opportunities") return <OpportunitySection D={D} />;
      if (slot === "sources") return <SourcesSection D={D} go={go} standalone={standalone} />;
      if (slot === "structure") return <StructureSection D={D} go={go} standalone={standalone} />;
      const fn = D && D.classSections && D.classSections[slot];
      return fn ? fn() : <LensTemplate classId={classId} slot={slot} />;
    };

    if (!D) {
      return (
        <div>
          <window.PageHead eyebrow={tenant.name + " · " + proj.name} title="Intelligence Report"></window.PageHead>
          <div style={card({ background: "var(--bg-2)" })}>
            <p style={{ margin: 0, fontSize: "var(--fs-sm)", color: "var(--ink-2)" }}>No report payload registered for this project yet — run the workflow to compose it.</p>
          </div>
        </div>
      );
    }

    const activePart = PARTS.find((p) => p.id === part) || PARTS[0];
    const body = (
      <div>
        {part === "brief" && <DigestStrip D={D} />}
        {activePart.slots.map((slot, i) => (
          <div key={slot} style={{ marginTop: i ? "var(--s-6)" : 0 }}>{renderSlot(slot)}</div>
        ))}
      </div>
    );

    const ph = D.pageHead || {};
    const partIdx = PARTS.findIndex((p) => p.id === activePart.id);
    return (
      <div>
        <window.PageHead eyebrow={ph.eyebrow || (tenant.name + " · " + proj.name)} title={ph.title || "Intelligence Report"} sub={ph.sub} right={ph.right}></window.PageHead>

        {/* active part header — the part nav lives in the Workspace sidebar */}
        <div style={{ display: "flex", alignItems: "baseline", gap: 11, flexWrap: "wrap", margin: "0 0 var(--s-5)", paddingBottom: 11, borderBottom: "1px solid var(--rule-hard)" }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: "10px", fontWeight: 700, color: "var(--accent-lo)" }}>{String(partIdx + 1).padStart(2, "0")}</span>
          <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-md)", color: "var(--ink)" }}>{activePart.name}</span>
          {activePart.cadence && <window.Pill tone="accent">{activePart.cadence}</window.Pill>}
          <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)", lineHeight: 1.45 }}>{activePart.sub}</span>
          {activePart.classSpecific && <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-4)" }}><span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }}></span>class-specific</span>}
        </div>

        {body}

        <p style={{ margin: "var(--s-6) 0 0", fontFamily: "var(--mono)", fontSize: "9px", letterSpacing: "0.06em", color: "var(--ink-4)", lineHeight: 1.7 }}>
          {D.footer || "Generated from the project Knowledge Base. Classifications: V verified · P self-reported · A assumption · H hypothesis · Q questionable · U unknown."}
        </p>
      </div>
    );
  }

  // shared helpers other report-data modules reuse for their class sections
  window.IntelReportKit = { mono, card, Grid, cell, sevTone, SEV_COLOR, PRI_TONE, mkBadge };
  window.IntelligenceReport = IntelligenceReport;
})();
