// Perdura — CFO Briefings (Stage 5.B). Operator-rhythm weekly/monthly digests:
// list + history, a Generate flow (cfo-briefing-synthesis, claude-opus-4-7), and
// a scannable single-briefing view (2–3 minute read) with editable narratives so
// the operator can add a personal note before sharing.
//
// Generic + config-driven: renders whatever sections the composer produced and
// whatever narrative the AI returned. NO industry-conditional or customer-
// conditional logic. Drill-downs reuse the dr= mechanism (window.__perduraDrillDataRoom
// / PerduraSynthesis.navigateDrill).

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

  const fmtUSD = (n, o) => (window.fmtUSD ? window.fmtUSD(n, o || { compact: true }) : (n == null ? "—" : String(n)));
  const db = () => window.supabaseClient;

  const STATUS_STYLE = {
    draft: { background: "var(--bg-elev-2)", color: "var(--text-3)" },
    generated: { background: "rgba(16,185,129,0.12)", color: "#10b981" },
    generated_partial: { background: "rgba(217,119,6,0.12)", color: "var(--warning)" },
    archived: { background: "var(--bg-elev-2)", color: "var(--text-4)" },
  };
  const TYPE_STYLE = {
    weekly: { background: "rgba(37,99,235,0.12)", color: "#2563eb" },
    monthly: { background: "rgba(124,58,237,0.12)", color: "#7c3aed" },
  };
  const Badge = ({ style, label }) => R.createElement("span", { className: "pc-adm-badge", style }, label);

  async function callBriefingSynthesis(body) {
    const d = db();
    let token = window.SUPABASE_ANON_KEY;
    try { const { data } = await d.auth.getSession(); if (data?.session?.access_token) token = data.session.access_token; } catch (_e) { /* anon */ }
    const res = await fetch(`${window.SUPABASE_URL}/functions/v1/cfo-briefing-synthesis`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, "Apikey": window.SUPABASE_ANON_KEY },
      body: JSON.stringify(body),
    });
    const out = await res.json();
    if (!res.ok) throw new Error(out && out.error ? out.error : `HTTP ${res.status}`);
    return out;
  }

  // ── Period selector (reuses the engine period model, like Board Reports) ─────
  function PeriodPicker({ profile, onChange }) {
    const P = window.PerduraPeriod;
    const fy = (profile && profile.fiscal_year_start_month) || 1;
    const [preset, setPreset] = useState("last_month");
    useEffect(() => {
      if (!P) return;
      const state = { period: { kind: "preset", preset }, compare: { kind: "prior_period" } };
      const resolved = P.resolve(state, { fiscalYearStartMonth: fy });
      onChange({
        period_start: resolved.startDate, period_end: resolved.endDate, period_label: resolved.label,
        prior_period_start: resolved.compare ? resolved.compare.startDate : null,
        prior_period_end: resolved.compare ? resolved.compare.endDate : null,
        prior_period_label: resolved.compare ? resolved.compare.label : null,
      });
    }, [preset]);
    const sel = { padding: "7px 10px", borderRadius: 8, border: "1px solid var(--border)", background: "var(--bg-card)", color: "var(--text-1)", fontSize: 13 };
    return R.createElement("select", { style: sel, value: preset, onChange: (e) => setPreset(e.target.value) },
      (P ? P.PRESETS : []).map((p) => R.createElement("option", { key: p.key, value: p.key }, p.label)));
  }

  // ── List + history + generate ────────────────────────────────────────────────
  function BriefingsList({ companyId, profile, setBriefing }) {
    const [rows, setRows] = useState(null);
    const [pp, setPp] = useState(null);
    const [btype, setBtype] = useState("weekly");
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState("");

    const load = useCallback(async () => {
      if (!companyId) return;
      const { data } = await db().from("cfo_briefings")
        .select("id,briefing_type,period_label,period_start,period_end,status,model_used,generated_at,updated_at,sections")
        .eq("company_id", companyId)
        .order("period_end", { ascending: false, nullsFirst: false }).order("updated_at", { ascending: false });
      setRows(data || []);
    }, [companyId]);
    useEffect(() => { load(); }, [load]);

    async function generate() {
      if (!pp) { setErr("Pick a period first."); return; }
      setBusy(true); setErr("");
      try {
        const out = await callBriefingSynthesis({
          company_id: companyId, briefing_type: btype,
          period_start: pp.period_start, period_end: pp.period_end, period_label: pp.period_label,
          prior_period_start: pp.prior_period_start, prior_period_end: pp.prior_period_end, prior_period_label: pp.prior_period_label,
        });
        if (out && out.briefing && out.briefing.id) { await load(); setBriefing({ id: out.briefing.id }); }
        else setErr(out && out.error ? out.error : "Generation returned no briefing.");
      } catch (e) { setErr(String(e.message || e)); }
      finally { setBusy(false); }
    }

    const typeBtn = (val, label) => R.createElement("button", {
      onClick: () => setBtype(val),
      style: {
        padding: "6px 14px", borderRadius: 999, fontSize: 12.5, fontWeight: 600, cursor: "pointer", marginRight: 8,
        border: btype === val ? "1px solid var(--accent, #2f6fed)" : "1px solid var(--border)",
        background: btype === val ? "var(--accent-soft, #eef6ff)" : "var(--bg-card)",
        color: btype === val ? "var(--accent, #2f6fed)" : "var(--text-2)",
      },
    }, label);

    return R.createElement("div", { className: "pc-page" },
      R.createElement("div", { style: { marginBottom: 18 } },
        R.createElement("h1", { style: { fontSize: 22, fontWeight: 800, margin: 0 } }, "CFO Briefings"),
        R.createElement("div", { style: { fontSize: 13, color: "var(--text-3)", marginTop: 4 } },
          "Your Monday-morning digest — what changed, what's resolved, what's new, and what to watch. A 2–3 minute read, narrated by a master FP&A specialist.")),

      R.createElement("div", { className: "pc-card", style: { padding: 16, marginBottom: 18 } },
        R.createElement("div", { style: { fontSize: 12, fontWeight: 700, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 10 } }, "Generate a briefing"),
        R.createElement("div", { style: { display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" } },
          typeBtn("weekly", "Weekly"), typeBtn("monthly", "Monthly"),
          R.createElement("span", { style: { color: "var(--text-3)", fontSize: 12, margin: "0 4px" } }, "period"),
          R.createElement(PeriodPicker, { profile, onChange: setPp })),
        R.createElement("div", { style: { marginTop: 14, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" } },
          R.createElement("button", { className: "pc-btn-primary", disabled: busy || !pp, onClick: generate, style: { fontSize: 13.5, padding: "10px 18px" } },
            busy ? "Generating with claude-opus-4-7…" : "Generate Briefing Now"),
          pp ? R.createElement("span", { style: { fontSize: 12, color: "var(--text-3)" } }, `${pp.period_label}${pp.prior_period_label ? " vs " + pp.prior_period_label : ""}`) : null),
        err ? R.createElement("div", { style: { color: "#ef4444", fontSize: 12.5, marginTop: 10 } }, err) : null,
        busy ? R.createElement("div", { style: { fontSize: 12, color: "var(--text-3)", marginTop: 8 } }, "Composing the digest, then drafting the briefing — ~15-30s.") : null),

      rows == null
        ? R.createElement("div", { style: { padding: 40, textAlign: "center", color: "var(--text-3)" } }, "Loading…")
        : (rows.length === 0
          ? R.createElement("div", { className: "pc-card", style: { padding: 40, textAlign: "center" } },
            R.createElement("div", { style: { fontSize: 15, fontWeight: 600, marginBottom: 6 } }, "No briefings yet"),
            R.createElement("div", { style: { fontSize: 13, color: "var(--text-3)", marginBottom: 14 } }, "Generate your first briefing — pick a cadence and period above."),
          )
          : R.createElement("div", { className: "pc-card", style: { padding: 0 } },
            R.createElement("div", { className: "pc-card-hd" }, R.createElement("div", { className: "pc-card-title" }, "History")),
            R.createElement("div", { className: "pc-adm-table-wrap" },
              R.createElement("table", { className: "pc-adm-table" },
                R.createElement("thead", null, R.createElement("tr", null,
                  ["Cadence", "Period", "Status", "Model", "Generated", ""].map((h, i) => R.createElement("th", { key: i, style: i === 5 ? { textAlign: "right" } : null }, h)))),
                R.createElement("tbody", null,
                  rows.map((r) => R.createElement("tr", { key: r.id, style: { cursor: "pointer" }, onClick: () => setBriefing({ id: r.id }) },
                    R.createElement("td", null, R.createElement(Badge, { style: TYPE_STYLE[r.briefing_type] || TYPE_STYLE.weekly, label: r.briefing_type || "weekly" })),
                    R.createElement("td", { style: { fontWeight: 600, color: "var(--text-1)" } }, r.period_label || "—"),
                    R.createElement("td", null, R.createElement(Badge, { style: STATUS_STYLE[r.status] || STATUS_STYLE.draft, label: (r.status || "draft").replace(/_/g, " ") })),
                    R.createElement("td", { style: { color: "var(--text-3)", fontSize: 12, fontFamily: "monospace" } }, r.model_used || "—"),
                    R.createElement("td", { style: { color: "var(--text-3)", fontSize: 12 } }, r.generated_at ? String(r.generated_at).slice(0, 10) : "—"),
                    R.createElement("td", { style: { textAlign: "right" } }, R.createElement("button", { className: "pc-btn-mini ghost", onClick: (e) => { e.stopPropagation(); setBriefing({ id: r.id }); } }, "Open →"))))))))
      )
    );
  }

  // ── Section renderers (scannable) ──────────────────────────────────────────
  const SECTION_TITLES = {
    what_changed_materially: "What changed materially",
    resolved_this_period: "Resolved this period",
    new_active_items: "New & active",
    forward_look: "Forward look",
  };
  const sevColor = (s) => (s === "high" ? "#c0392b" : s === "medium" ? "#b7791f" : s === "low" ? "#2f6fed" : "#6b7785");

  function MoverRow({ m }) {
    const up = (m.delta || 0) >= 0;
    return R.createElement("div", { style: { display: "flex", justifyContent: "space-between", gap: 12, padding: "6px 0", borderTop: "1px solid var(--border)" } },
      R.createElement("div", { style: { fontSize: 13, color: "var(--text-1)" } }, m.label,
        m.severity ? R.createElement("span", { style: { marginLeft: 8, fontSize: 10, fontWeight: 700, textTransform: "uppercase", color: sevColor(m.severity) } }, m.severity) : null),
      R.createElement("div", { style: { fontSize: 13, fontWeight: 700, fontFamily: "ui-monospace,monospace", color: up ? "#10b981" : "#ef4444" } }, m.magnitude_label || (m.current_value != null ? fmtUSD(m.current_value) : "—")));
  }
  function ItemRow({ it }) {
    return R.createElement("div", { style: { display: "flex", justifyContent: "space-between", gap: 12, padding: "6px 0", borderTop: "1px solid var(--border)" } },
      R.createElement("div", { style: { fontSize: 13, color: "var(--text-1)" } },
        it.is_new ? R.createElement("span", { style: { fontSize: 9.5, fontWeight: 800, color: "#2563eb", background: "rgba(37,99,235,0.12)", padding: "1px 6px", borderRadius: 999, marginRight: 8, textTransform: "uppercase" } }, "new") : null,
        it.label,
        it.severity ? R.createElement("span", { style: { marginLeft: 8, fontSize: 10, fontWeight: 700, textTransform: "uppercase", color: sevColor(it.severity) } }, it.severity) : null),
      it.dollar_impact != null ? R.createElement("div", { style: { fontSize: 13, fontWeight: 700, fontFamily: "ui-monospace,monospace", color: "var(--text-1)" } }, fmtUSD(it.dollar_impact)) : null);
  }

  function SectionData({ skey, sec }) {
    if (!sec) return null;
    if (skey === "what_changed_materially") {
      return R.createElement("div", null, sec.map((m, i) => R.createElement(MoverRow, { key: i, m })));
    }
    if (skey === "resolved_this_period") {
      return R.createElement("div", null, sec.map((r, i) => R.createElement("div", { key: i, style: { padding: "6px 0", borderTop: "1px solid var(--border)", fontSize: 13 } },
        R.createElement("span", { style: { color: "var(--text-1)" } }, "✓ " + r.label),
        r.resolved_at ? R.createElement("span", { style: { color: "var(--text-3)", fontSize: 11.5, marginLeft: 8 } }, String(r.resolved_at).slice(0, 10)) : null,
        r.resolution_notes ? R.createElement("div", { style: { color: "var(--text-3)", fontSize: 12, fontStyle: "italic", marginTop: 2 } }, r.resolution_notes) : null)));
    }
    if (skey === "new_active_items") {
      return R.createElement("div", null,
        (sec.exceptions || []).length ? R.createElement("div", { style: { marginBottom: 8 } },
          R.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.3 } }, "Exceptions"),
          sec.exceptions.map((it, i) => R.createElement(ItemRow, { key: i, it }))) : null,
        (sec.opportunities || []).length ? R.createElement("div", null,
          R.createElement("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.3 } }, "Opportunities"),
          sec.opportunities.map((it, i) => R.createElement(ItemRow, { key: i, it }))) : null);
    }
    if (skey === "forward_look") {
      return R.createElement("div", { style: { fontSize: 12.5, color: "var(--text-2)" } },
        (sec.emerging_risks || []).length ? R.createElement("div", null, "Watch: " + sec.emerging_risks.map((r) => r.label).join(" · ")) : null,
        (sec.focus_areas || []).length ? R.createElement("div", { style: { marginTop: 4 } }, "Focus: " + sec.focus_areas.join(", ")) : null);
    }
    return null;
  }

  // ── Single briefing view (scannable, editable narratives) ──────────────────
  function BriefingView({ companyId, briefingId, setBriefing }) {
    const [briefing, setB] = useState(null);
    const [err, setErr] = useState("");
    const [saveState, setSaveState] = useState("");
    const saveTimer = useRef(null);

    useEffect(() => {
      let cancelled = false;
      (async () => {
        const { data, error } = await db().from("cfo_briefings").select("*").eq("id", briefingId).maybeSingle();
        if (cancelled) return;
        if (error) setErr(error.message); else setB(data);
      })();
      return () => { cancelled = true; };
    }, [briefingId]);

    const sections = briefing && briefing.sections ? briefing.sections : null;
    const keys = sections && sections.section_keys ? sections.section_keys : (sections && sections.sections ? Object.keys(sections.sections) : []);
    const narr = (sections && sections.narratives) || {};

    function editNarrative(key, text) {
      setB((b) => {
        const next = { ...b, sections: { ...b.sections, narratives: { ...(b.sections.narratives || {}), [key]: text } } };
        setSaveState("saving");
        if (saveTimer.current) clearTimeout(saveTimer.current);
        saveTimer.current = setTimeout(async () => {
          const { error } = await db().from("cfo_briefings").update({ sections: next.sections, updated_at: new Date().toISOString() }).eq("id", briefingId);
          setSaveState(error ? "error" : "saved");
          if (!error) setTimeout(() => setSaveState(""), 1500);
        }, 800);
        return next;
      });
    }

    if (err) return R.createElement("div", { className: "pc-page" }, R.createElement("div", { style: { color: "#ef4444" } }, err));
    if (!briefing) return R.createElement("div", { className: "pc-page" }, R.createElement("div", { style: { padding: 40, color: "var(--text-3)" } }, "Loading briefing…"));

    return R.createElement("div", { className: "pc-page" },
      R.createElement("div", { style: { marginBottom: 16 } },
        R.createElement("button", { className: "pc-btn-mini ghost", onClick: () => setBriefing({ id: null }), style: { marginBottom: 8 } }, "← All briefings"),
        R.createElement("h1", { style: { fontSize: 22, fontWeight: 800, margin: 0 } },
          (briefing.briefing_type === "monthly" ? "Monthly" : "Weekly") + " Briefing"),
        R.createElement("div", { style: { fontSize: 13, color: "var(--text-3)", marginTop: 4, display: "flex", gap: 10, alignItems: "center" } },
          briefing.period_label || "—",
          R.createElement(Badge, { style: STATUS_STYLE[briefing.status] || STATUS_STYLE.draft, label: (briefing.status || "draft").replace(/_/g, " ") }),
          saveState === "saving" ? R.createElement("span", { style: { fontSize: 11, color: "var(--text-3)" } }, "saving…") : null,
          saveState === "saved" ? R.createElement("span", { style: { fontSize: 11, color: "#10b981" } }, "saved") : null)),

      briefing.status === "generated_partial" ? R.createElement("div", { style: { padding: "10px 14px", borderRadius: 8, background: "rgba(217,119,6,0.08)", border: "1px solid rgba(217,119,6,0.25)", fontSize: 12.5, color: "var(--text-2)", marginBottom: 16 } }, "The narrative could not be fully generated this run — the deterministic numbers below are complete; you can re-generate or write the narrative yourself.") : null,

      sections && sections.executive_overview ? R.createElement("div", { style: { fontSize: 14.5, lineHeight: 1.6, color: "var(--text-1)", marginBottom: 20, padding: "14px 16px", background: "var(--bg-elev-1)", borderRadius: 10, border: "1px solid var(--border)" } }, sections.executive_overview) : null,

      keys.length === 0 ? R.createElement("div", { className: "pc-card", style: { padding: 24, color: "var(--text-3)" } }, "Nothing material to flag this period.") : null,

      keys.map((k) => R.createElement("div", { key: k, className: "pc-card", style: { padding: 18, marginBottom: 14 } },
        R.createElement("div", { style: { fontSize: 15, fontWeight: 700, marginBottom: 10 } }, SECTION_TITLES[k] || k),
        R.createElement(SectionData, { skey: k, sec: sections.sections && sections.sections[k] }),
        narr[k] ? R.createElement("p", { style: { fontSize: 13.5, lineHeight: 1.6, color: "var(--text-2)", margin: "10px 0 0" } }, narr[k]) : null,
        R.createElement("details", { style: { marginTop: 8 } },
          R.createElement("summary", { style: { fontSize: 11.5, color: "var(--text-3)", cursor: "pointer" } }, "Edit / add a note"),
          R.createElement("textarea", {
            className: "pc-adm-input", rows: 3, style: { width: "100%", fontSize: 13, lineHeight: 1.6, fontFamily: "inherit", marginTop: 6 },
            value: narr[k] || "", placeholder: "Add your own note before sharing…",
            onChange: (e) => editNarrative(k, e.target.value),
          })))),
    );
  }

  function CfoBriefingsPage(props) {
    const companyId = props.scopedCompanyId || (props.companyProfile && props.companyProfile.id);
    const profile = props.companyProfile;
    const b = props.briefing || { id: null };
    if (!companyId) return R.createElement("div", { className: "pc-page" }, R.createElement("div", { style: { padding: 40, color: "var(--text-3)" } }, "Select a company to view briefings."));
    if (b.id) return R.createElement(BriefingView, { companyId, briefingId: b.id, setBriefing: props.setBriefing });
    return R.createElement(BriefingsList, { companyId, profile, setBriefing: props.setBriefing });
  }

  window.CfoBriefingsPage = CfoBriefingsPage;
})();
