// PageCommentary — Stage 5.A. A subtle footer panel that renders a short,
// CFO-grade narrative for an analytical page (Income Statement, Balance Sheet,
// Cash Flow Statement, Reconciliation).
//
// Calls cfo-synthesis with surface_type="page_commentary" + page_type, and shows
// the returned `summary` paragraph under a "CFO Commentary" heading. It is
// strictly NON-BLOCKING: while fetching it shows a small skeleton; if synthesis
// is unavailable, errors, or returns nothing, the panel hides quietly and the
// page works exactly as before. Every figure in the paragraph traces to a real
// signal — the synthesis layer is guardrailed against fabrication.
//
// Props: { tenantId, pageType, periodStart, periodEnd }
//   pageType ∈ income_statement | balance_sheet | cash_flow | reconciliation
//   periodStart/periodEnd are advisory (re-fetch when the period changes); the
//   evaluator anchors on the tenant's own data window server-side.

(function () {
  const R = window.React;
  if (!R) return;
  const { useState, useEffect } = R;

  function PageCommentary(props) {
    const tenantId = props.tenantId;
    const pageType = props.pageType;
    const [phase, setPhase] = useState("loading"); // loading | done | hidden
    const [text, setText] = useState("");
    const [meta, setMeta] = useState({});

    useEffect(() => {
      let alive = true;
      if (!tenantId || !pageType || !window.PerduraSynthesis) { setPhase("hidden"); return; }
      setPhase("loading");
      window.PerduraSynthesis.fetch(tenantId, "page_commentary", { page_type: pageType })
        .then((res) => {
          if (!alive) return;
          const summary = res && typeof res.summary === "string" ? res.summary.trim() : "";
          // Hide quietly on error or when there's nothing material to say.
          if (!res || res.error || !summary) { setPhase("hidden"); return; }
          setText(summary);
          setMeta({ model: res.model, signal_count: res.signal_count, retried: res.retried });
          setPhase("done");
        })
        .catch(() => { if (alive) setPhase("hidden"); });
      return () => { alive = false; };
      // Re-fetch when tenant, page, or the resolved period changes.
    }, [tenantId, pageType, props.periodStart, props.periodEnd]);

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

    return (
      <div className="pc-page-commentary" style={{
        marginTop: 24, padding: "16px 18px", borderRadius: 12,
        background: "var(--surface-2, #f6f8fb)", border: "1px solid var(--border, #e3e8ef)",
      }}>
        <div style={{
          fontSize: 11, fontWeight: 800, textTransform: "uppercase", letterSpacing: 0.5,
          color: "var(--text-3)", marginBottom: 8, display: "flex", alignItems: "center", gap: 8,
        }}>
          <span>CFO Commentary</span>
        </div>
        {phase === "loading" ? (
          <div aria-hidden="true">
            {[92, 100, 78].map((w, i) => (
              <div key={i} style={{
                height: 11, width: w + "%", borderRadius: 5, marginBottom: 8,
                background: "linear-gradient(90deg, var(--border,#e3e8ef) 25%, var(--surface,#fff) 50%, var(--border,#e3e8ef) 75%)",
              }} />
            ))}
          </div>
        ) : (
          <>
            <p style={{ fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.6, margin: 0 }}>{text}</p>
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 8 }}>
              Generated from your live signals{meta.signal_count != null ? ` · ${meta.signal_count} signal(s)` : ""}{meta.model ? ` · ${meta.model}` : ""}.
            </div>
          </>
        )}
      </div>
    );
  }

  window.PageCommentary = PageCommentary;
})();
