// CFOCommentaryPanel — window.CFOCommentaryPanel
// ─────────────────────────────────────────────────────────────────────────────
// Expert-CFO AI commentary card for analysis pages that don't already carry
// commentary (the Transaction Advisory pages). It calls cfo-synthesis through the
// shared window.PerduraSynthesis client (surface_type="page_commentary") and
// renders the returned `prioritized` items as severity-tagged findings plus the
// `summary` as the CFO read-out.
//
// IMPORTANT: this ADAPTS the existing { summary, prioritized } response contract —
// it does NOT require any change to the shared synthesis response shape, which
// also feeds Board Reports, CFO Briefings, and the Exceptions inbox. Each finding
// traces to a real synthesized signal; nothing is fabricated. Silent-fails and
// hides when there is nothing material to say. Marked `no-print` so it never
// bleeds into a printed CIM / deal proposal / board PDF.
// ─────────────────────────────────────────────────────────────────────────────
(function () {
  const { useState, useEffect } = React;
  const SEV_DOT = { high: "#ef5350", medium: "#f5b301", low: "#00b894", info: "#8899aa" };
  const SEV_ICON = { high: "🔴", medium: "🟡", low: "🟢", info: "🟢" };

  function CFOCommentaryPanel(props) {
    const companyId = props.companyId || props.scopedCompanyId || props.tenantId || null;
    const pageType = props.pageType || null;
    // Period is only used to key the cache; the synthesis client resolves the
    // actual window server-side from the tenant's data.
    const period =
      props.period ||
      (props.globalPeriod && (props.globalPeriod.key || props.globalPeriod.id)) ||
      (props.periodStart && props.periodEnd ? props.periodStart + ":" + props.periodEnd : "current");

    const [phase, setPhase] = useState("loading"); // loading | done | hidden
    const [findings, setFindings] = useState([]);
    const [summary, setSummary] = useState("");
    const [meta, setMeta] = useState({});
    const [expanded, setExpanded] = useState(true);

    const cacheKey = "perdura_cmt_" + companyId + "_" + pageType + "_" + period;

    function apply(res) {
      const items = Array.isArray(res.prioritized) ? res.prioritized : [];
      const sum = res && typeof res.summary === "string" ? res.summary.trim() : "";
      const mapped = items
        .map((it) => ({
          severity: String(it.severity || "info").toLowerCase(),
          headline: it.headline || "",
          detail: it.supporting_detail || it.diagnosed_driver || it.recommended_action || "",
        }))
        .filter((f) => f.headline);
      if (!mapped.length && !sum) { setPhase("hidden"); return; }
      setFindings(mapped);
      setSummary(sum);
      setMeta({ model: res.model, signal_count: res.signal_count });
      setPhase("done");
    }

    function load(force) {
      if (!companyId || !pageType || !window.PerduraSynthesis) { setPhase("hidden"); return; }
      if (!force) {
        try {
          const cached = localStorage.getItem(cacheKey);
          if (cached) { apply(JSON.parse(cached)); return; }
        } catch (_e) { /* ignore malformed cache */ }
      }
      setPhase("loading");
      window.PerduraSynthesis.fetch(companyId, "page_commentary", { page_type: pageType })
        .then((res) => {
          if (!res || res.error) { setPhase("hidden"); return; }
          try { localStorage.setItem(cacheKey, JSON.stringify(res)); } catch (_e) { /* private mode */ }
          apply(res);
        })
        .catch(() => setPhase("hidden"));
    }

    function regenerate(e) {
      if (e) e.stopPropagation();
      try { localStorage.removeItem(cacheKey); } catch (_e) { /* ignore */ }
      load(true);
    }

    useEffect(() => { load(false); /* eslint-disable-next-line */ }, [companyId, pageType, period]);

    if (phase === "hidden") return null;

    return (
      <div className="no-print" style={{
        background: "linear-gradient(135deg,#0d2040 0%,#1a3a5c 100%)",
        borderRadius: 12, padding: "20px 24px", marginTop: 24,
        border: "1px solid rgba(0,184,148,0.3)",
      }}>
        <div
          onClick={() => setExpanded((v) => !v)}
          style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: expanded ? 16 : 0, cursor: "pointer" }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ background: "#00b894", borderRadius: 6, padding: "3px 8px", fontSize: 10, fontWeight: 700, color: "white", textTransform: "uppercase", letterSpacing: 1 }}>🤖 CFO AI</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: "white" }}>Expert Analysis</div>
          </div>
          <div style={{ color: "#00b894", fontSize: 16 }}>{expanded ? "▲" : "▼"}</div>
        </div>

        {expanded && (
          <div>
            {phase === "loading" ? (
              <div style={{ color: "#8899aa", fontSize: 13, fontStyle: "italic" }}>⏳ Analysing your data…</div>
            ) : (
              <div>
                {findings.map((f, i) => (
                  <div key={i} style={{ display: "flex", gap: 12, marginBottom: 12, alignItems: "flex-start" }}>
                    <span style={{ fontSize: 15, flexShrink: 0 }}>{SEV_ICON[f.severity] || SEV_ICON.info}</span>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "white", marginBottom: 2 }}>{f.headline}</div>
                      {f.detail && <div style={{ fontSize: 12, color: "#8899aa", lineHeight: 1.5 }}>{f.detail}</div>}
                    </div>
                  </div>
                ))}

                {summary && (
                  <div style={{ background: "rgba(0,184,148,0.1)", borderRadius: 8, padding: "12px 16px", marginTop: findings.length ? 12 : 0, borderLeft: "3px solid #00b894" }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: "#00b894", marginBottom: 4, textTransform: "uppercase", letterSpacing: 0.5 }}>CFO Read-out</div>
                    <div style={{ fontSize: 12.5, color: "#c8d6e8", lineHeight: 1.55 }}>{summary}</div>
                  </div>
                )}

                <div style={{ fontSize: 10, color: "#6475a0", marginTop: 12, borderTop: "1px solid rgba(255,255,255,0.08)", paddingTop: 8, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
                  <span>Generated from your live signals{meta.signal_count != null ? ` · ${meta.signal_count} signal(s)` : ""} · Not financial advice</span>
                  <span style={{ color: "#00b894", cursor: "pointer", flexShrink: 0 }} onClick={regenerate}>↻ Regenerate</span>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  }

  window.CFOCommentaryPanel = CFOCommentaryPanel;
})();
