// Dev-only synthesis surface — /dev/synthesis?tenant=<id>&surface=<type> or
// /{company-slug}/dev-synthesis?surface=<type>. Calls the cfo-synthesis edge
// function with debug:true and renders the synthesized items side-by-side with
// the EXACT source SignalSet the function fed the model — so every claim in the
// synthesis can be traced to a real signal. Internal verification tool, not
// customer-facing.
//
// Exposes window.__perduraSynthesis for the e2e harness.

(function () {
  const R = window.React;
  if (!R) return;

  const SURFACES = (window.PerduraSynthesis && window.PerduraSynthesis.SURFACES) ||
    ["what_matters_now", "opportunities", "exceptions_inbox", "page_commentary"];

  function DevSynthesisPage(props) {
    const scopedId = props.scopedCompanyId || (props.companyProfile && props.companyProfile.id) || null;
    const initialSurface = (props.surface && SURFACES.indexOf(props.surface) >= 0) ? props.surface : "what_matters_now";
    const [surface, setSurface] = R.useState(initialSurface);
    const [state, setState] = R.useState({ status: "idle", resp: null, error: null });

    R.useEffect(() => {
      let cancelled = false;
      async function run() {
        if (!scopedId) { setState({ status: "no-tenant", resp: null, error: null }); return; }
        if (!window.PerduraSynthesis) { setState({ status: "loading-client", resp: null, error: null }); return; }
        setState({ status: "running", resp: null, error: null });
        const resp = await window.PerduraSynthesis.fetch(scopedId, surface, { debug: true });
        if (cancelled) return;
        window.__perduraSynthesis = resp;
        if (resp.error) setState({ status: "error", resp, error: resp.error });
        else setState({ status: "done", resp, error: null });
      }
      run();
      return () => { cancelled = true; };
    }, [scopedId, surface]);

    const mono = { fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 };
    const wrap = { padding: 20, color: "var(--text-1, #111)" };
    const pre = { ...mono, whiteSpace: "pre-wrap", background: "var(--surface-2,#f6f7f9)", padding: 12, borderRadius: 6, overflow: "auto" };

    // Build the id → signal lookup so we can show, per synthesized item, the
    // exact signals it cites (the verification the harness asserts on).
    const resp = state.resp || {};
    const ss = resp.signal_set || null;
    const byId = {};
    if (ss && ss.signals) ss.signals.forEach((s) => { byId[s.id] = s; });

    const surfaceButtons = R.createElement("div", { style: { marginBottom: 12 } },
      SURFACES.map((s) => R.createElement("button", {
        key: s,
        onClick: () => setSurface(s),
        style: {
          marginRight: 8, padding: "4px 10px", fontSize: 12, borderRadius: 6,
          border: "1px solid var(--border,#d0d5dd)", cursor: "pointer",
          background: s === surface ? "var(--brand,#2563eb)" : "var(--surface-1,#fff)",
          color: s === surface ? "#fff" : "var(--text-1,#111)",
        },
      }, s))
    );

    if (state.status !== "done") {
      return R.createElement("div", { style: wrap, "data-dev-synthesis": state.status },
        R.createElement("h2", null, "Synthesis — debug surface (dev)"),
        surfaceButtons,
        R.createElement("p", { style: mono }, "status: " + state.status),
        state.error ? R.createElement("pre", { style: { ...pre, color: "#b91c1c" } }, state.error) : null
      );
    }

    const items = resp.prioritized || [];
    const header = R.createElement("div", { style: { ...mono, marginBottom: 8 } },
      `${ss ? ss.archetype : "?"} · surface=${surface} · ${items.length} item(s) · ${resp.signal_count} signals` +
      (resp.retried ? " · RETRIED" : ""));

    const itemBlocks = items.length
      ? items.map((it, i) => {
        const cited = (it.source_signal_ids || []).map((id) => ({ id, sig: byId[id] }));
        const allReal = cited.every((c) => !!c.sig);
        return R.createElement("div", {
          key: i,
          style: { border: "1px solid var(--border,#d0d5dd)", borderRadius: 8, padding: 12, marginBottom: 12 },
        },
          R.createElement("div", { style: { fontWeight: 700, marginBottom: 4 } }, it.headline),
          R.createElement("div", { style: { ...mono, color: "#047857", marginBottom: 4 } },
            it.estimated_dollar_impact != null ? "$" + Math.round(Math.abs(it.estimated_dollar_impact)).toLocaleString() : "(no $ impact)"),
          R.createElement("div", { style: { marginBottom: 4 } }, it.supporting_detail),
          R.createElement("div", { style: { ...mono, color: "#6b7280", marginBottom: 4 } }, "driver: " + it.diagnosed_driver),
          R.createElement("div", { style: { ...mono, color: "#6b7280", marginBottom: 4 } }, "action: " + it.recommended_action),
          R.createElement("div", { style: { ...mono, marginBottom: 4 } }, "drill_into: " + it.drill_into),
          R.createElement("div", { style: { ...mono, color: allReal ? "#047857" : "#b91c1c" } },
            (allReal ? "✓ " : "✗ ") + "source_signal_ids: " + JSON.stringify(it.source_signal_ids)),
          cited.map((c, j) => R.createElement("pre", { key: j, style: { ...pre, marginTop: 6 } },
            c.sig ? JSON.stringify({ id: c.sig.id, name: c.sig.name, kind: c.sig.kind, value: c.sig.value, impact: c.sig.estimated_dollar_impact, severity: c.sig.severity, evidence: c.sig.supporting_evidence && c.sig.supporting_evidence.values }, null, 2)
              : `UNKNOWN SIGNAL ID: ${c.id} (not in SignalSet)`))
        );
      })
      : [R.createElement("p", { key: "empty", style: mono }, "summary: " + resp.summary)];

    return R.createElement("div", { style: wrap, "data-dev-synthesis": "done" },
      R.createElement("h2", null, "Synthesis — debug surface (dev)"),
      surfaceButtons,
      header,
      R.createElement("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 } },
        R.createElement("div", null,
          R.createElement("h3", null, "Synthesized items (claims ↔ cited signals)"),
          R.createElement("div", { style: { ...mono, marginBottom: 8 } }, "summary: " + resp.summary),
          itemBlocks,
          resp.guardrail_notes && resp.guardrail_notes.length
            ? R.createElement("div", null, R.createElement("h4", null, "Guardrail notes"),
                R.createElement("pre", { style: { ...pre, color: "#b45309" } }, JSON.stringify(resp.guardrail_notes, null, 2)))
            : null
        ),
        R.createElement("div", null,
          R.createElement("h3", null, "Source SignalSet (the only facts the AI saw)"),
          R.createElement("pre", { id: "dev-synth-signalset", style: pre }, JSON.stringify(ss, null, 2))
        )
      )
    );
  }

  window.DevSynthesisPage = DevSynthesisPage;
})();
