// SynthesizedSurface — shared orchestration for any synthesis-backed UI surface.
// Owns the fetch lifecycle (loading → done/empty/error) and the footer, and
// renders the prioritized items as cards. Both the Opportunities page and the
// What-Matters-Now panel use this so their loading/empty/footer behavior is
// identical and neither duplicates fetch/parse logic.
//
//   <window.SynthesizedSurface
//      tenantId={scopedCompanyId}
//      surfaceType="opportunities"
//      max={6}                       // optional cap on rendered items
//      loadingLabel="…"
//      emptyTitle="…" emptyDetail="…"
//      setPage={setPage} setDrillKey={setDrillKey} />
//
// Reads ONLY the synthesis service output (window.PerduraSynthesis.fetch).

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

  function Footer({ resp }) {
    if (!resp) return null;
    // Generated-at: the client renders "now" when the response lands — the
    // service is stateless, so this is the moment the user is looking at.
    let ts = "";
    try { ts = new Date().toLocaleString(); } catch (_e) { ts = ""; }
    const n = typeof resp.signal_count === "number" ? resp.signal_count : 0;
    return R.createElement("div", {
      style: { fontSize: 11.5, color: "var(--text-3,#98a2b3)", marginTop: 12 },
    }, `Generated ${ts} · Based on ${n} underlying signal${n === 1 ? "" : "s"}.` + (resp.retried ? " · re-validated" : ""));
  }

  function SynthesizedSurface(props) {
    const { tenantId, surfaceType, max, loadingLabel, emptyTitle, emptyDetail, setPage, setDrillKey, severityBorder } = props;
    const [state, setState] = R.useState({ status: "idle", resp: null });

    R.useEffect(() => {
      let cancelled = false;
      if (!tenantId) { setState({ status: "idle", resp: null }); return; }
      if (!window.PerduraSynthesis) { setState({ status: "loading", resp: null }); }
      else setState({ status: "loading", resp: null });
      (async () => {
        if (!window.PerduraSynthesis) return;
        const resp = await window.PerduraSynthesis.fetch(tenantId, surfaceType, {});
        if (cancelled) return;
        if (resp && resp.error) setState({ status: "error", resp });
        else setState({ status: "done", resp: resp || { prioritized: [], summary: "", signal_count: 0 } });
      })();
      return () => { cancelled = true; };
    }, [tenantId, surfaceType]);

    if (state.status === "idle") return null;
    if (state.status === "loading") {
      return R.createElement(window.SignalLoader || "div", { label: loadingLabel, lines: 3 });
    }
    if (state.status === "error") {
      return R.createElement(window.IntelEmptyState || "div", {
        tone: "error",
        title: "Couldn't generate insights right now",
        detail: (state.resp && state.resp.error) ? String(state.resp.error) : undefined,
      });
    }

    const resp = state.resp || {};
    let items = resp.prioritized || [];
    if (max && items.length > max) items = items.slice(0, max);

    if (!items.length) {
      return R.createElement("div", null,
        R.createElement(window.IntelEmptyState || "div", {
          title: emptyTitle,
          detail: emptyDetail || resp.summary,
        }),
        R.createElement(Footer, { resp })
      );
    }

    return R.createElement("div", { "data-intel-state": "done", "data-intel-count": items.length },
      resp.summary
        ? R.createElement("div", {
          style: { fontSize: 14, color: "var(--text-2,#475467)", marginBottom: 14, lineHeight: 1.5 },
        }, resp.summary)
        : null,
      items.map((it, i) => R.createElement(window.SynthesizedItemCard || "div", {
        key: i, item: it, setPage, setDrillKey, severityBorder,
      })),
      R.createElement(Footer, { resp })
    );
  }

  window.SynthesizedSurface = SynthesizedSurface;
})();
