// IntelligencePage (Business Intelligence hub) — window.IntelligencePage
// The CFO cockpit: one place that tells the owner everything about the business.
// Six tabs — Overview · Performance · Run Rate · Margins · Outliers · Benchmarks.
// Every figure derives from the live `data` prop (GL txns + plHistory + bs + cash
// + aging). No fabrication: when a number can't be derived we say so. AI panels
// call the cfo-synthesis edge function via window.PerduraSynthesis and cache the
// result per company + period in localStorage. Built on window.PerduraPageKit.

(function () {
  const h = React.createElement;
  const { useState, useEffect } = React;

  // ── Industry benchmark reference (percentiles) ────────────────────────────
  const BENCHMARKS = {
    healthcare_services: {
      label: "Healthcare Services",
      gross_margin:  { p25: 0.35, p50: 0.45, p75: 0.58 },
      ebitda_margin: { p25: 0.08, p50: 0.15, p75: 0.22 },
      dso:           { p25: 25,   p50: 35,   p75: 50 },
      opex_pct:      { p25: 0.28, p50: 0.35, p75: 0.44 },
    },
    saas: {
      label: "SaaS / Software",
      gross_margin:  { p25: 0.65, p50: 0.75, p75: 0.85 },
      ebitda_margin: { p25: 0.05, p50: 0.15, p75: 0.28 },
      dso:           { p25: 20,   p50: 30,   p75: 45 },
      opex_pct:      { p25: 0.45, p50: 0.55, p75: 0.70 },
    },
    professional_services: {
      label: "Professional Services",
      gross_margin:  { p25: 0.28, p50: 0.38, p75: 0.50 },
      ebitda_margin: { p25: 0.06, p50: 0.12, p75: 0.20 },
      dso:           { p25: 30,   p50: 42,   p75: 60 },
      opex_pct:      { p25: 0.30, p50: 0.40, p75: 0.52 },
    },
    distribution: {
      label: "Distribution / Wholesale",
      gross_margin:  { p25: 0.18, p50: 0.25, p75: 0.35 },
      ebitda_margin: { p25: 0.03, p50: 0.07, p75: 0.12 },
      dso:           { p25: 28,   p50: 38,   p75: 52 },
      opex_pct:      { p25: 0.14, p50: 0.20, p75: 0.28 },
    },
    retail: {
      label: "Retail",
      gross_margin:  { p25: 0.25, p50: 0.38, p75: 0.52 },
      ebitda_margin: { p25: 0.04, p50: 0.09, p75: 0.15 },
      dso:           { p25: 5,    p50: 12,   p75: 25 },
      opex_pct:      { p25: 0.22, p50: 0.30, p75: 0.42 },
    },
  };
  // Map a company's industry/business-type text to the closest benchmark set.
  function pickBenchmark(profile) {
    const s = String((profile && (profile.industry || profile.business_type)) || "").toLowerCase();
    if (/health|medical|clinic|dental|care|hospital/.test(s)) return "healthcare_services";
    if (/saas|software|tech|app|platform|subscription/.test(s)) return "saas";
    if (/retail|store|shop|ecommerce|commerce|consumer/.test(s)) return "retail";
    if (/distribut|wholesale|logistics|supply|manufact/.test(s)) return "distribution";
    return "professional_services";
  }

  // ── AI commentary panel (cfo-synthesis + localStorage cache) ──────────────
  // Uses the whitelisted "page_commentary" surface with a per-tab page_type. Shows
  // an immediate local fallback, then upgrades with the AI response when it lands.
  function AICommentary(props) {
    const { tenantId, pageType, periodKey, fallback, nonce } = props;
    const [open, setOpen] = useState(true);
    const [state, setState] = useState({ status: "idle", summary: null, items: [] });
    const cacheKey = "perdura.intel.ai." + (tenantId || "none") + "." + pageType + "." + periodKey;

    useEffect(() => {
      let alive = true;
      // Serve cache unless the user forced a refresh via nonce.
      if (!nonce) {
        try {
          const raw = localStorage.getItem(cacheKey);
          if (raw) {
            const c = JSON.parse(raw);
            if (c && c.summary) { setState({ status: "done", summary: c.summary, items: c.items || [] }); return () => { alive = false; }; }
          }
        } catch (e) { /* ignore */ }
      }
      if (!tenantId || !window.PerduraSynthesis || !window.PerduraSynthesis.fetch) {
        setState({ status: "unavailable", summary: null, items: [] });
        return () => { alive = false; };
      }
      setState((s) => ({ status: "loading", summary: s.summary, items: s.items }));
      window.PerduraSynthesis.fetch(tenantId, "page_commentary", { page_type: pageType }).then((resp) => {
        if (!alive) return;
        if (!resp || resp.error) { setState({ status: "unavailable", summary: null, items: [] }); return; }
        const summary = resp.summary || null;
        const items = Array.isArray(resp.prioritized) ? resp.prioritized : [];
        setState({ status: "done", summary, items });
        try { localStorage.setItem(cacheKey, JSON.stringify({ ts: Date.now(), summary, items })); } catch (e) { /* ignore */ }
      }).catch(() => { if (alive) setState({ status: "unavailable", summary: null, items: [] }); });
      return () => { alive = false; };
    }, [tenantId, pageType, periodKey, nonce]);

    const body = state.summary
      || (state.items && state.items.length ? state.items.slice(0, 3).map((it) => it.headline).filter(Boolean).join(" ") : null)
      || fallback
      || "Connect and sync your accounting data to unlock AI-generated CFO analysis for this view.";

    return h("div", { style: { background: "linear-gradient(135deg, rgba(13,32,64,.04) 0%, rgba(28,78,216,.04) 100%)", border: "1px solid rgba(13,32,64,.12)", borderLeft: "4px solid #009fa0", borderRadius: 10, padding: "16px 20px", marginTop: 24 } },
      h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", cursor: "pointer" }, onClick: () => setOpen(!open) },
        h("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
          h("span", { style: { fontSize: 11, fontWeight: 800, color: "#009fa0", letterSpacing: ".08em", textTransform: "uppercase" } }, "🤖 CFO Analysis"),
          state.status === "loading" ? h("span", { style: { fontSize: 10, color: "#6475a0" } }, "· thinking…") : null),
        h("span", { style: { fontSize: 12, color: "#6475a0" } }, open ? "collapse ▲" : "expand ▼")),
      open ? h("div", { style: { marginTop: 10 } },
        h("div", { style: { fontSize: 13, color: "#1a2540", lineHeight: 1.6 } }, body),
        h("div", { style: { fontSize: 10.5, color: "#94a3b8", marginTop: 8 } }, "Generated from your real financial data · Not financial advice")) : null);
  }

  // ── helpers ───────────────────────────────────────────────────────────────
  const sum = (arr) => (arr || []).reduce((a, b) => a + (Number(b) || 0), 0);
  const sliceLast = (arr, n) => (arr || []).slice(Math.max(0, (arr || []).length - n));
  const deltaPct = (cur, prior) => (prior && Number.isFinite(prior) && prior !== 0) ? (cur - prior) / Math.abs(prior) * 100 : null;
  const dir = (v, goodUp) => v == null ? "flat" : (goodUp ? (v >= 0 ? "up" : "dn") : (v <= 0 ? "up" : "dn"));

  // Monthly totals per account (by account_name) over the trailing window — the
  // series the z-score outlier detector runs on.
  function monthlyByAccount(txns, monthKeys) {
    const idxOf = {}; monthKeys.forEach((k, i) => { idxOf[k] = i; });
    const acc = {};
    for (const t of (txns || [])) {
      const name = t.account_name || t.canonical_category || "Unclassified";
      const d = t.posted_date ? new Date(t.posted_date) : null;
      if (!d || isNaN(d)) continue;
      const key = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0");
      if (!(key in idxOf)) continue;
      const row = acc[name] || (acc[name] = { name, category: t.canonical_category || null, values: Array(monthKeys.length).fill(0) });
      row.values[idxOf[key]] += Math.abs(Number(t.amount) || 0);
    }
    return Object.values(acc);
  }

  function detectOutliers(accounts) {
    const out = [];
    accounts.forEach((account) => {
      const values = account.values;
      if (!values || values.length < 4) return;
      const hist = values.slice(0, values.length - 1);
      const latest = values[values.length - 1];
      const mean = hist.reduce((a, b) => a + b, 0) / hist.length;
      if (mean <= 0 && latest <= 0) return;
      const variance = hist.map((v) => Math.pow(v - mean, 2)).reduce((a, b) => a + b, 0) / hist.length;
      const stdDev = Math.sqrt(variance);
      const zScore = stdDev > 0 ? (latest - mean) / stdDev : 0;
      if (Math.abs(zScore) > 1.5 && Math.abs(latest - mean) > 500) {
        out.push({
          account: account.name, category: account.category, latest, mean, zScore,
          direction: latest > mean ? "spike" : "drop",
          severity: Math.abs(zScore) > 2.5 ? "high" : Math.abs(zScore) > 2 ? "medium" : "low",
          multiple: mean > 0 ? latest / mean : null,
        });
      }
    });
    return out.sort((a, b) => Math.abs(b.zScore) - Math.abs(a.zScore));
  }

  // Consecutive-direction trend anomalies from a monthly account series.
  function trendAnomalies(accounts) {
    const res = [];
    accounts.forEach((a) => {
      const v = sliceLast(a.values, 6).filter((x) => x != null);
      if (v.length < 4) return;
      let up = 0, down = 0;
      for (let i = v.length - 1; i > 0; i--) {
        if (v[i] > v[i - 1] * 1.01) { if (down) break; up++; } else if (v[i] < v[i - 1] * 0.99) { if (up) break; down++; } else break;
      }
      const first = v[v.length - 1 - Math.max(up, down)], last = v[v.length - 1];
      const cum = first ? (last - first) / Math.abs(first) * 100 : 0;
      if (up >= 3) res.push({ account: a.name, dir: "up", months: up, cum });
      else if (down >= 2) res.push({ account: a.name, dir: "down", months: down, cum });
    });
    return res.sort((a, b) => Math.abs(b.cum) - Math.abs(a.cum)).slice(0, 6);
  }

  function TabBar({ tab, setTab, tabs }) {
    return h("div", { style: { display: "flex", gap: 4, borderBottom: "1px solid rgba(13,32,64,.1)", marginBottom: 18, overflowX: "auto" } },
      tabs.map(([k, label]) => h("button", {
        key: k, onClick: () => setTab(k),
        style: {
          background: "transparent", border: "none", borderBottom: "2px solid " + (tab === k ? "#1C4ED8" : "transparent"),
          padding: "10px 16px", fontSize: 13, fontWeight: tab === k ? 700 : 500, cursor: "pointer",
          color: tab === k ? "#0d2040" : "#6475a0", whiteSpace: "nowrap", fontFamily: "Inter, system-ui",
        },
      }, label)));
  }

  function Page(props) {
    const K = window.PerduraPageKit;
    if (!K) return h("div", { className: "pc-page" }, "Loading…");
    const { data, companyProfile, scopedCompanyId, setPage } = props;
    const M = (v) => K.moneyStr(v, { compact: true });
    const nav = (p) => (setPage ? setPage(p) : (window.__perduraSetPage && window.__perduraSetPage(p)));
    const drill = (acct) => window.openAccountDetail && window.openAccountDetail(acct);

    // Hooks first — always, before any early return.
    const [tab, setTab] = useState("overview");
    const [aiNonce, setAiNonce] = useState(0);
    const ps = K.usePeriodState("intelligence", "ltm");
    const tenantId = scopedCompanyId || (companyProfile && companyProfile.id) || null;

    const plH = (data && (data.plHistory || data.pl)) || null;
    const txns = (data && data.txns) || [];
    const hasData = !!(data && plH && Array.isArray(plH.revenue) && plH.revenue.length);

    // ── Empty state ─────────────────────────────────────────────────────────
    if (!hasData) {
      return h(K.Shell, { hero: { eyebrow: "BUSINESS INTELLIGENCE", title: "Business Intelligence", subtitle: "Your CFO cockpit — one place for everything about the business" } },
        h(K.Card, { title: "Connect your accounting data to unlock Intelligence" },
          h("div", { style: { padding: 8, fontSize: 13.5, color: "#4a5680", lineHeight: 1.6 } },
            "The Intelligence hub reads directly from your general ledger. Connect QuickBooks, Xero, Wave, or upload a workbook in ",
            h("a", { onClick: () => nav("settings_config"), style: { color: "#1C4ED8", cursor: "pointer", fontWeight: 600 } }, "Settings → Data Sources"),
            " and Intelligence will light up with your real performance, run rate, margins, outliers, and benchmarks.")));
    }

    // ── Derived metrics ───────────────────────────────────────────────────────
    const revArr = (plH.revenue || []).map(Number);
    const cogsArr = (plH.cogs || []).map(Number);
    const opexArr = (plH.opex || []).map(Number);
    const gpArr = (plH.gp && plH.gp.length ? plH.gp : revArr.map((r, i) => r - (cogsArr[i] || 0))).map(Number);
    const ebitdaArr = (plH.ebitda || gpArr.map((g, i) => g - (opexArr[i] || 0))).map(Number);
    const labels = plH.labels || [];
    const years = plH.years || [];
    const N = revArr.length;

    // month keys (YYYY-MM) aligned to the plHistory arrays, for the outlier engine.
    const MON3 = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
    const monthKeys = labels.map((lb, i) => {
      const m = MON3.indexOf(String(lb || "").slice(0, 3).toLowerCase());
      const y = years[i];
      return (y && m >= 0) ? (y + "-" + String(m + 1).padStart(2, "0")) : ("idx-" + i);
    });

    // LTM (last 12) vs prior-year (prior 12).
    const T = K.ttm(plH) || { cur: { revenue: sum(revArr), cogs: sum(cogsArr), opex: sum(opexArr), gp: sum(gpArr), ebitda: sum(ebitdaArr) }, prior: null, hasPrior: false, N };
    const ltm = T.cur, py = T.prior;
    const revLtm = ltm.revenue, cogsLtm = ltm.cogs, gpLtm = ltm.gp, opexLtm = ltm.opex, ebitdaLtm = ltm.ebitda;
    const niLtm = (data && Number.isFinite(data.net_income_ltm)) ? data.net_income_ltm : (gpLtm - opexLtm);
    const gmPct = revLtm ? gpLtm / revLtm * 100 : null;
    const ebitdaPct = revLtm ? ebitdaLtm / revLtm * 100 : null;
    const opexPct = revLtm ? opexLtm / revLtm * 100 : null;

    const bs = data && data.bs;
    const cash = data && data.cash;
    const aging = data && data.aging;
    const cashOnHand = bs ? bs.cash : (cash ? cash.endCash : null);
    const arBal = bs ? bs.accounts_receivable : (aging && aging.ar ? aging.ar.outstanding : null);
    const dso = (arBal != null && revLtm) ? Math.round(arBal / (revLtm / 365)) : null;

    // Prior-year comparatives for the KPI deltas.
    const revPY = py ? py.revenue : null;
    const gmPctPY = (py && py.revenue) ? py.gp / py.revenue * 100 : null;
    const ebitdaPY = py ? py.ebitda : null;
    const opexPctPY = (py && py.revenue) ? py.opex / py.revenue * 100 : null;

    // period selector → windowed figures (drives Performance / Margins / Outliers).
    const anchor = K.anchorFromPlH(plH);
    const range = K.resolvePeriod(ps.mode, anchor, ps.custom);
    const cmpRange = K.comparePeriod(range, ps.cmp);
    const span = K.plIdxRange(plH, range);
    const cspan = cmpRange ? K.plIdxRange(plH, cmpRange) : null;
    const periodKey = ps.mode + (ps.cmp || "");

    const win = (arr, sp) => K.sumIdx(arr, sp);
    const pRev = win(revArr, span), pCogs = win(cogsArr, span), pOpex = win(opexArr, span);
    const pGp = win(gpArr, span), pEbitda = win(ebitdaArr, span);
    const pNi = pEbitda; // net income proxy for the window (no window-level D&A split)

    const generateReport = () => { setAiNonce((n) => n + 1); };

    // ── Tab: Overview ─────────────────────────────────────────────────────────
    function renderOverview() {
      const m12 = sliceLast(labels, 12);
      const rev12 = sliceLast(revArr, 12);
      const priorYr12 = N >= 24 ? revArr.slice(N - 24, N - 12) : null;

      const kpis = [
        { label: "Revenue (LTM)", value: M(revLtm), valueColor: "navy", page: "revenue_intelligence",
          d: deltaPct(revLtm, revPY), goodUp: true, note: "vs PY" },
        { label: "Gross Margin", value: gmPct == null ? "—" : gmPct.toFixed(1) + "%", valueColor: "green", page: "margin",
          d: (gmPct != null && gmPctPY != null) ? gmPct - gmPctPY : null, isBps: true, goodUp: true, note: "vs PY" },
        { label: "EBITDA", value: M(ebitdaLtm), valueColor: "gold", page: "income_statement",
          d: deltaPct(ebitdaLtm, ebitdaPY), goodUp: true, note: "vs PY" },
        { label: "Cash on Hand", value: cashOnHand == null ? "—" : M(cashOnHand), valueColor: "teal", page: "cash",
          d: null, note: cash && cash.runwayDays ? Math.round(cash.runwayDays / 30) + " mo runway" : "balance sheet" },
        { label: "AR Days (DSO)", value: dso == null ? "—" : dso + " days", valueColor: "blue", page: "arap",
          d: null, note: arBal != null ? M(arBal) + " outstanding" : "needs AR data" },
        { label: "Expense Ratio", value: opexPct == null ? "—" : opexPct.toFixed(1) + "%", valueColor: "amber", page: "opex_intelligence",
          d: (opexPct != null && opexPctPY != null) ? opexPct - opexPctPY : null, isBps: true, goodUp: false, note: "opex ÷ revenue" },
      ];

      const insights = buildInsights();

      const aiFallback = "Revenue is " + M(revLtm) + " over the last twelve months"
        + (revPY != null ? " (" + (revLtm >= revPY ? "up " : "down ") + Math.abs(deltaPct(revLtm, revPY) || 0).toFixed(0) + "% vs prior year)" : "")
        + " at a " + (gmPct == null ? "—" : gmPct.toFixed(1) + "%") + " gross margin and " + (ebitdaPct == null ? "—" : ebitdaPct.toFixed(1) + "%") + " EBITDA margin."
        + (cash && cash.runwayDays ? " Cash covers roughly " + Math.round(cash.runwayDays / 30) + " months at the current burn." : "");

      return [
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_overview", periodKey: "ltm", nonce: aiNonce, fallback: aiFallback }),
        h("div", { key: "kpis", className: "pa-kpi-strip pa-kpi-strip-3", style: { marginTop: 18 } },
          kpis.map((k, i) => {
            const deltaStr = k.d == null ? null : (k.isBps ? (Math.abs(k.d) * 100).toFixed(0) + " bps" : Math.abs(k.d).toFixed(0) + "%");
            return h(K.Kpi, { key: i, animDelay: i * 0.04, label: k.label, value: k.value, valueColor: k.valueColor,
              delta: deltaStr, deltaDir: k.d == null ? "flat" : dir(k.d, k.goodUp), sub: k.note,
              onClick: () => nav(k.page) });
          })),
        h("div", { key: "trend", className: "pa-grid-2", style: { marginTop: 4 } },
          h(K.Card, { title: "REVENUE TREND", sub: "12 months · prior-year overlay (dashed)" },
            h(K.Bars, { values: rev12, prior: priorYr12, labels: m12, height: 200 }),
            h(K.KeyTakeaway, { text: "Trailing-12-month revenue is <b>" + M(revLtm) + "</b>"
              + (revPY != null ? ", " + (revLtm >= revPY ? "up" : "down") + " <b>" + Math.abs(deltaPct(revLtm, revPY) || 0).toFixed(0) + "%</b> versus the prior year." : ".") })),
          h(K.Card, { title: "TOP INSIGHTS", sub: "Signals detected from your ledger" },
            h("div", { style: { padding: "4px 0" } },
              insights.length ? insights.map((it, i) => h("div", { key: i, onClick: it.page ? () => nav(it.page) : undefined,
                style: { display: "flex", gap: 10, alignItems: "flex-start", padding: "9px 14px", borderBottom: "1px solid rgba(13,32,64,.05)", cursor: it.page ? "pointer" : "default" } },
                h("span", { style: { fontSize: 13, flexShrink: 0 } }, it.sev === "high" ? "🔴" : it.sev === "medium" ? "🟡" : "🟢"),
                h("div", null,
                  h("span", { style: { fontSize: 8.5, fontWeight: 800, letterSpacing: ".08em", color: it.sev === "high" ? "#d94f47" : it.sev === "medium" ? "#d97706" : "#18a867", textTransform: "uppercase" } }, it.sev),
                  h("div", { style: { fontSize: 12.5, color: "#1a2540", fontWeight: 500, lineHeight: 1.45, marginTop: 1 } }, it.text))))
                : h("div", { style: { padding: 14, fontSize: 12.5, color: "#6475a0" } }, "No material signals this period — the business looks steady.")))),
      ];
    }

    // Deterministic insight signals from real data (AR aging, margin, vendor
    // spikes, runway, growth). Severity-ranked.
    function buildInsights() {
      const out = [];
      // AR aging concentration
      if (aging && aging.ar && aging.ar.topOverdue && aging.ar.topOverdue.length) {
        const over = aging.ar.topOverdue;
        const tied = sum(over.map((o) => o.amount));
        const oldest = Math.max.apply(null, over.map((o) => o.days || 0));
        if (tied > 0) out.push({ sev: oldest > 60 ? "high" : "medium", page: "arap",
          text: "AR aging: <b>" + M(tied) + "</b> tied up in " + over.length + " customer" + (over.length > 1 ? "s" : "") + " (oldest " + oldest + " days past due)." });
      }
      // Vendor spend spike (from outliers)
      const outliers = detectOutliers(monthlyByAccount(txns, monthKeys));
      if (outliers.length && outliers[0].direction === "spike" && outliers[0].multiple) {
        const o = outliers[0];
        out.push({ sev: o.severity, page: "opex_intelligence",
          text: "Spend spike: <b>" + o.account + "</b> at " + M(o.latest) + " — " + o.multiple.toFixed(1) + "× its " + M(o.mean) + " baseline (z=" + o.zScore.toFixed(1) + ")." });
      }
      // Margin compression
      if (gmPct != null && gmPctPY != null) {
        const bps = (gmPct - gmPctPY) * 100;
        if (bps < -80) out.push({ sev: bps < -180 ? "high" : "medium", page: "margin",
          text: "Gross margin compressed <b>" + Math.abs(bps).toFixed(0) + " bps</b> vs prior year (" + gmPct.toFixed(1) + "% now)." });
        else if (bps > 80) out.push({ sev: "low", page: "margin",
          text: "Gross margin expanded <b>" + bps.toFixed(0) + " bps</b> vs prior year to " + gmPct.toFixed(1) + "%." });
      }
      // Cash runway
      if (cash && cash.runwayDays != null) {
        const mo = cash.runwayDays / 30;
        if (mo < 6 && cash.burnPerDay > 0) out.push({ sev: mo < 3 ? "high" : "medium", page: "cash",
          text: "Cash runway is <b>" + mo.toFixed(1) + " months</b> at the current burn — plan financing before it tightens." });
        else out.push({ sev: "low", page: "cash", text: "Cash position healthy — <b>" + (mo > 24 ? "24+" : mo.toFixed(1)) + " months</b> of runway at current burn." });
      }
      // Revenue growth
      if (revPY != null) {
        const g = deltaPct(revLtm, revPY);
        if (g != null && g > 5) out.push({ sev: "low", page: "revenue_intelligence", text: "Revenue growth tracking <b>+" + g.toFixed(0) + "%</b> year-over-year." });
        else if (g != null && g < -5) out.push({ sev: "medium", page: "revenue_intelligence", text: "Revenue is <b>" + g.toFixed(0) + "%</b> year-over-year — investigate the decline." });
      }
      const rank = { high: 0, medium: 1, low: 2 };
      return out.sort((a, b) => rank[a.sev] - rank[b.sev]).slice(0, 5);
    }

    // ── Tab: Performance ──────────────────────────────────────────────────────
    function renderPerformance() {
      // current window vs prior period vs prior year
      const pyRange = K.comparePeriod(range, "prior_year");
      const pyspan = pyRange ? K.plIdxRange(plH, pyRange) : null;
      const ppRange = K.comparePeriod(range, "prior_period");
      const ppspan = ppRange ? K.plIdxRange(plH, ppRange) : null;
      const col = (arr, sp) => sp ? K.sumIdx(arr, sp) : null;
      const rows = [
        { label: "Revenue", cur: pRev, pp: col(revArr, ppspan), py: col(revArr, pyspan), page: "revenue_intelligence", fmt: M },
        { label: "Gross Profit", cur: pGp, pp: col(gpArr, ppspan), py: col(gpArr, pyspan), page: "margin", fmt: M },
        { label: "Gross Margin %", cur: pRev ? pGp / pRev * 100 : null, pp: (col(revArr, ppspan)) ? col(gpArr, ppspan) / col(revArr, ppspan) * 100 : null, py: (col(revArr, pyspan)) ? col(gpArr, pyspan) / col(revArr, pyspan) * 100 : null, page: "margin", pct: true },
        { label: "EBITDA", cur: pEbitda, pp: col(ebitdaArr, ppspan), py: col(ebitdaArr, pyspan), page: "income_statement", fmt: M },
        { label: "EBITDA Margin %", cur: pRev ? pEbitda / pRev * 100 : null, pp: (col(revArr, ppspan)) ? col(ebitdaArr, ppspan) / col(revArr, ppspan) * 100 : null, py: (col(revArr, pyspan)) ? col(ebitdaArr, pyspan) / col(revArr, pyspan) * 100 : null, page: "income_statement", pct: true },
        { label: "Operating Expenses", cur: pOpex, pp: col(opexArr, ppspan), py: col(opexArr, pyspan), page: "opex_intelligence", fmt: M },
        { label: "Net Income", cur: pNi, pp: col(ebitdaArr, ppspan), py: col(ebitdaArr, pyspan), page: "income_statement", fmt: M },
      ];
      const chg = (cur, base, pct) => {
        if (cur == null || base == null) return "—";
        if (pct) return (cur - base >= 0 ? "+" : "") + (cur - base).toFixed(1) + " pts";
        const d = deltaPct(cur, base);
        return d == null ? "—" : (d >= 0 ? "+" : "") + d.toFixed(0) + "%";
      };
      const chgColor = (cur, base, goodUp) => { if (cur == null || base == null) return "#6475a0"; const up = cur >= base; return (up === (goodUp !== false)) ? "#18a867" : "#d94f47"; };

      const table = h(K.Card, { title: "PERIOD COMPARISON", sub: range.label + " · current vs prior period vs prior year · click a row to drill", padding: 0 },
        h("div", { style: { overflowX: "auto" } },
          h("table", { className: "pa-table" },
            h("thead", null, h("tr", null,
              h("th", null, "Metric"), h("th", { className: "num" }, "Current"), h("th", { className: "num" }, "Prior Period"),
              h("th", { className: "num" }, "Chg"), h("th", { className: "num" }, "Prior Year"), h("th", { className: "num" }, "YoY"))),
            h("tbody", null, rows.map((r, i) => {
              const fmt = r.pct ? ((v) => v == null ? "—" : v.toFixed(1) + "%") : (r.fmt || M);
              const goodUp = r.label !== "Operating Expenses";
              return h("tr", { key: i, onClick: () => nav(r.page), title: "Drill into " + r.label, style: { cursor: "pointer" } },
                h("td", { style: { fontWeight: 600 } }, r.label),
                h("td", { className: "num", style: { fontWeight: 700 } }, fmt(r.cur)),
                h("td", { className: "num" }, fmt(r.pp)),
                h("td", { className: "num", style: { color: chgColor(r.cur, r.pp, goodUp), fontWeight: 700 } }, chg(r.cur, r.pp, r.pct)),
                h("td", { className: "num" }, fmt(r.py)),
                h("td", { className: "num", style: { color: chgColor(r.cur, r.py, goodUp), fontWeight: 700 } }, chg(r.cur, r.py, r.pct)));
            })))));

      // waterfall bridge Revenue → GP → EBITDA → Net Income
      const bridge = [
        { label: "Revenue", value: pRev, type: "start" },
        { label: "− COGS", value: -pCogs, type: "negative" },
        { label: "Gross Profit", value: pGp, type: "end" },
        { label: "− OpEx", value: -pOpex, type: "negative" },
        { label: "EBITDA", value: pEbitda, type: "end" },
        { label: "Net Income", value: pNi, type: "end" },
      ];

      // monthly heatmap — revenue vs prior month
      const heat = sliceLast(labels, 12).map((lb, i, arr) => {
        const idx = N - arr.length + i;
        const cur = revArr[idx], prev = revArr[idx - 1];
        const g = (prev && prev !== 0) ? (cur - prev) / Math.abs(prev) : 0;
        return { label: lb, color: g > 0.02 ? "#18a867" : g < -0.02 ? "#d94f47" : "#d97706", g };
      });

      return [
        table,
        h("div", { key: "b", className: "pa-grid-2", style: { marginTop: 18 } },
          h(K.Card, { title: "REVENUE → NET INCOME BRIDGE", sub: range.label }, h(K.BridgeChart, { items: bridge })),
          h(K.Card, { title: "MONTHLY REVENUE HEATMAP", sub: "vs prior month · trailing 12" },
            h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, padding: "10px 4px" } },
              heat.map((c, i) => h("div", { key: i, title: c.label + ": " + (c.g >= 0 ? "+" : "") + (c.g * 100).toFixed(1) + "% MoM",
                style: { flex: "1 0 60px", minWidth: 54, textAlign: "center" } },
                h("div", { style: { height: 30, borderRadius: 6, background: c.color, opacity: 0.85 } }),
                h("div", { style: { fontSize: 9.5, color: "#6475a0", marginTop: 3 } }, c.label)))))),
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_performance", periodKey, nonce: aiNonce,
          fallback: "For " + range.label.toLowerCase() + ", revenue is " + M(pRev) + " at a " + (pRev ? (pGp / pRev * 100).toFixed(1) : "—") + "% gross margin and " + M(pEbitda) + " EBITDA." }),
      ];
    }

    // ── Tab: Run Rate ─────────────────────────────────────────────────────────
    function renderRunRate() {
      const last3 = { rev: sum(sliceLast(revArr, 3)), gp: sum(sliceLast(gpArr, 3)), ebitda: sum(sliceLast(ebitdaArr, 3)) };
      const runRate = { rev: last3.rev / 3 * 12, gp: last3.gp / 3 * 12, ebitda: last3.ebitda / 3 * 12 };
      const monthsLeft = 12 - ((anchor.getMonth() + 1)); // months remaining in calendar year after anchor month
      const ytdMonths = anchor.getMonth() + 1;
      const ytd = { rev: sum(revArr.slice(N - ytdMonths)), gp: sum(gpArr.slice(N - ytdMonths)), ebitda: sum(ebitdaArr.slice(N - ytdMonths)) };
      const monthlyRR = { rev: last3.rev / 3, gp: last3.gp / 3, ebitda: last3.ebitda / 3 };
      const yeProj = { rev: ytd.rev + monthlyRR.rev * monthsLeft, gp: ytd.gp + monthlyRR.gp * monthsLeft, ebitda: ytd.ebitda + monthlyRR.ebitda * monthsLeft };

      const rrRows = [
        { label: "Revenue", ltm: revLtm, rr: runRate.rev, ye: yeProj.rev },
        { label: "Gross Profit", ltm: gpLtm, rr: runRate.gp, ye: yeProj.gp },
        { label: "EBITDA", ltm: ebitdaLtm, rr: runRate.ebitda, ye: yeProj.ebitda },
      ];
      const burnMo = cash && cash.burnPerDay != null ? cash.burnPerDay * 30 : (monthlyRR.ebitda < 0 ? -monthlyRR.ebitda : 0);
      const runwayMo = cash && cash.runwayDays != null ? cash.runwayDays / 30 : (burnMo > 0 && cashOnHand ? cashOnHand / burnMo : null);

      const avg3 = sum(sliceLast(revArr, 3)) / 3;
      const avg6 = sum(sliceLast(revArr, 6)) / Math.min(6, N);
      const avg12 = revLtm / 12;
      const momentum = avg3 > avg6 * 1.02 ? "Accelerating" : avg3 < avg6 * 0.98 ? "Decelerating" : "Stable";

      const runwayPct = runwayMo == null ? 0 : Math.max(0, Math.min(1, runwayMo / 18));

      return [
        h(K.Card, { key: "rr", title: "RUN-RATE PROJECTIONS", sub: "Annualized from trailing 3 months · YE projection = YTD + run-rate × months remaining", padding: 0 },
          h("div", { style: { overflowX: "auto" } },
            h("table", { className: "pa-table" },
              h("thead", null, h("tr", null, h("th", null, "Metric"), h("th", { className: "num" }, "LTM"), h("th", { className: "num" }, "Run Rate (annualized)"), h("th", { className: "num" }, "YE Projection"))),
              h("tbody", null, rrRows.map((r, i) => h("tr", { key: i },
                h("td", { style: { fontWeight: 600 } }, r.label),
                h("td", { className: "num" }, M(r.ltm)),
                h("td", { className: "num", style: { fontWeight: 700 } }, M(r.rr)),
                h("td", { className: "num" }, M(r.ye)))),
                h("tr", null, h("td", { style: { fontWeight: 600 } }, "Cash Burn / Month"),
                  h("td", { className: "num" }, burnMo > 0 ? M(-burnMo) : "—"),
                  h("td", { className: "num" }, monthlyRR.ebitda < 0 ? M(monthlyRR.ebitda) : "cash generative"),
                  h("td", { className: "num" }, "—")))))),
        h("div", { key: "grid", className: "pa-grid-2", style: { marginTop: 18 } },
          h(K.Card, { title: "RUNWAY CALCULATOR", sub: "At current burn" },
            h("div", { style: { padding: "6px 4px", display: "flex", flexDirection: "column", gap: 10 } },
              rrKV("Current cash", cashOnHand == null ? "—" : M(cashOnHand)),
              rrKV("Monthly burn rate", burnMo > 0 ? M(burnMo) : "Cash generative"),
              rrKV("Runway", runwayMo == null ? "—" : (runwayMo > 24 ? "24+ months" : runwayMo.toFixed(1) + " months")),
              h("div", { style: { height: 12, borderRadius: 6, background: "rgba(13,32,64,.08)", overflow: "hidden", marginTop: 4 } },
                h("div", { style: { height: "100%", width: (runwayPct * 100).toFixed(0) + "%", background: runwayMo != null && runwayMo < 6 ? "#d94f47" : runwayMo != null && runwayMo < 12 ? "#d97706" : "#18a867", borderRadius: 6 } })))),
          h(K.Card, { title: "REVENUE MOMENTUM", sub: "Average monthly revenue" },
            h("div", { style: { padding: "6px 4px", display: "flex", flexDirection: "column", gap: 10 } },
              rrKV("3-month avg", M(avg3) + " /mo"),
              rrKV("6-month avg", M(avg6) + " /mo"),
              rrKV("12-month avg", M(avg12) + " /mo"),
              h("div", { style: { marginTop: 4, fontSize: 13, fontWeight: 700, color: momentum === "Accelerating" ? "#18a867" : momentum === "Decelerating" ? "#d94f47" : "#d97706" } },
                (momentum === "Accelerating" ? "▲ " : momentum === "Decelerating" ? "▼ " : "→ ") + momentum)))),
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_runrate", periodKey: "ltm", nonce: aiNonce,
          fallback: "Trailing-3-month run rate annualizes to " + M(runRate.rev) + " revenue and " + M(runRate.ebitda) + " EBITDA. Revenue momentum is " + momentum.toLowerCase() + "." + (runwayMo != null ? " Runway is about " + (runwayMo > 24 ? "24+" : runwayMo.toFixed(1)) + " months." : "") }),
      ];
    }
    function rrKV(k, v) {
      return h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "baseline", borderBottom: "1px solid rgba(13,32,64,.06)", paddingBottom: 6 } },
        h("span", { style: { fontSize: 12.5, color: "#4a5680" } }, k),
        h("span", { style: { fontSize: 15, fontWeight: 800, color: "#0d2040", fontFamily: K.MONO } }, v));
    }

    // ── Tab: Margins ──────────────────────────────────────────────────────────
    function renderMargins() {
      const m12 = sliceLast(labels, 12);
      const gm12 = sliceLast(revArr, 12).map((r, i) => { const idx = N - 12 + i; return revArr[idx] ? gpArr[idx] / revArr[idx] * 100 : null; });
      const em12 = sliceLast(revArr, 12).map((r, i) => { const idx = N - 12 + i; return revArr[idx] ? ebitdaArr[idx] / revArr[idx] * 100 : null; });
      const nm12 = em12; // net margin proxy (no monthly D&A split)
      const marginSeries = [
        { type: "line", color: "#059669", data: gm12 },
        { type: "line", color: "#1C4ED8", data: em12 },
        { type: "dashed-line", color: "#94a3b8", data: nm12 },
      ];

      // revenue by category (real) + cost structure donut (COGS + opex)
      const revCats = K.catBreakdownWindow(txns, companyProfile, ["revenue"], range, cmpRange);
      const revTotalCat = revCats.reduce((s, r) => s + r.cur, 0) || pRev;
      const costCats = K.catBreakdownWindow(txns, companyProfile, ["cogs", "opex"], range, cmpRange);

      // margin compression alerts (period vs comparison)
      const alerts = [];
      const curGm = pRev ? pGp / pRev * 100 : null;
      const cmpGm = cspan && K.sumIdx(revArr, cspan) ? K.sumIdx(gpArr, cspan) / K.sumIdx(revArr, cspan) * 100 : null;
      if (curGm != null && cmpGm != null && (curGm - cmpGm) * 100 < -100) alerts.push({ label: "Gross margin", bps: (curGm - cmpGm) * 100 });
      const curEm = pRev ? pEbitda / pRev * 100 : null;
      const cmpEm = cspan && K.sumIdx(revArr, cspan) ? K.sumIdx(ebitdaArr, cspan) / K.sumIdx(revArr, cspan) * 100 : null;
      if (curEm != null && cmpEm != null && (curEm - cmpEm) * 100 < -100) alerts.push({ label: "EBITDA margin", bps: (curEm - cmpEm) * 100 });

      const swatch = (color, label, dashed) => h("span", { style: { display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10, color: "#475569", fontWeight: 600 } },
        h("span", { style: { width: 14, height: dashed ? 0 : 8, borderRadius: 2, background: dashed ? "transparent" : color, borderTop: dashed ? "2px dashed " + color : "none", display: "inline-block" } }), label);

      return [
        h("div", { key: "row1", className: "pa-grid-2" },
          h(K.Card, { title: "MARGIN TREND", sub: "12 months · gross / EBITDA / net (dashed)", right: h("div", { style: { display: "flex", gap: 10 } }, swatch("#059669", "Gross"), swatch("#1C4ED8", "EBITDA"), swatch("#94a3b8", "Net", true)) },
            h(K.MultiSeriesBarChart, { months: m12, series: marginSeries, height: 190 }),
            h(K.KeyTakeaway, { text: "Gross margin is <b>" + (gmPct == null ? "—" : gmPct.toFixed(1) + "%") + "</b> and EBITDA margin <b>" + (ebitdaPct == null ? "—" : ebitdaPct.toFixed(1) + "%") + "</b> over the last twelve months." })),
          h(K.Card, { title: "COST STRUCTURE", sub: "COGS + OpEx by category · " + range.label },
            costCats.length ? h(K.Donut, { items: costCats.slice(0, 6).map((r, i) => ({ label: r.name, value: r.cur, color: K.RANK_COLORS[i % K.RANK_COLORS.length] })) })
              : h("div", { style: { color: K.MUTE, fontSize: 12, padding: 12 } }, "No classified cost accounts in this period."))),
        h(K.Card, { key: "cat", title: "REVENUE BY CATEGORY", sub: "Share of revenue · " + range.label + " · click to drill", padding: 0 },
          revCats.length ? h("div", { style: { overflowX: "auto" } }, h("table", { className: "pa-table" },
            h("thead", null, h("tr", null, h("th", null, "Category"), h("th", { className: "num" }, "Revenue"), h("th", { className: "num" }, "% of Revenue"))),
            h("tbody", null, revCats.slice(0, 10).map((r, i) => h("tr", { key: i, onClick: () => drill({ name: r.name, category: "revenue", page: "margin" }), title: "View account detail", style: { cursor: "pointer" } },
              h("td", { style: { fontWeight: 600 } }, r.name),
              h("td", { className: "num", style: { fontWeight: 700 } }, M(r.cur)),
              h("td", { className: "num" }, revTotalCat ? (r.cur / revTotalCat * 100).toFixed(1) + "%" : "—"))),
              h(K.MarginRow, { label: "Total revenue", value: M(revTotalCat), kind: "gross", span: 2 }))))
            : h("div", { className: "pa-card-body", style: { color: "#6475a0", fontSize: 12.5 } }, "No classified revenue categories in this period.")),
        alerts.length ? h(K.Card, { key: "alerts", title: "MARGIN COMPRESSION ALERTS", sub: "Drops greater than 100 bps vs " + (cmpRange ? cmpRange.label.toLowerCase() : "comparison") },
          alerts.map((a, i) => h("div", { key: i, style: { display: "flex", gap: 10, alignItems: "flex-start", padding: "8px 4px" } },
            h("span", { style: { fontSize: 14 } }, "⚠️"),
            h("div", null,
              h("div", { style: { fontSize: 12.5, fontWeight: 700, color: "#d94f47" } }, a.label + " compressed " + Math.abs(a.bps).toFixed(0) + " bps this period"),
              h("div", { style: { fontSize: 11, color: "#6475a0", marginTop: 2 } }, "Review pricing and the largest cost categories — cost increases may not be passed through to pricing."))))) : null,
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_margins", periodKey, nonce: aiNonce,
          fallback: "Gross margin is " + (gmPct == null ? "—" : gmPct.toFixed(1) + "%") + " and EBITDA margin " + (ebitdaPct == null ? "—" : ebitdaPct.toFixed(1) + "%") + (costCats.length ? ". Largest cost line: " + costCats[0].name + " at " + M(costCats[0].cur) + "." : ".") }),
      ];
    }

    // ── Tab: Outliers ─────────────────────────────────────────────────────────
    function renderOutliers() {
      const accounts = monthlyByAccount(txns, monthKeys);
      const outliers = detectOutliers(accounts).slice(0, 12);
      const anomalies = trendAnomalies(accounts);

      const cards = outliers.length ? outliers.map((o, i) => h("div", { key: i,
        onClick: () => drill({ name: o.account, category: o.category || null, page: "opex_intelligence" }), title: "View transactions",
        style: { background: "white", borderRadius: 10, border: "1px solid rgba(13,32,64,.09)", borderLeft: "4px solid " + (o.severity === "high" ? "#d94f47" : o.severity === "medium" ? "#d97706" : "#1C4ED8"), padding: "12px 14px", marginBottom: 10, cursor: "pointer" } },
        h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start" } },
          h("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
            h("span", { style: { fontSize: 13 } }, o.severity === "high" ? "🔴" : o.severity === "medium" ? "🟡" : "🟢"),
            h("span", { style: { fontSize: 12.5, fontWeight: 700, color: "#0d2040" } }, o.account)),
          h("span", { style: { fontSize: 8.5, fontWeight: 800, padding: "2px 7px", borderRadius: 4, textTransform: "uppercase", letterSpacing: ".05em", fontFamily: K.MONO,
            color: o.severity === "high" ? "#d94f47" : o.severity === "medium" ? "#d97706" : "#1C4ED8", background: o.severity === "high" ? "rgba(217,79,71,.1)" : o.severity === "medium" ? "rgba(217,119,6,.1)" : "rgba(28,78,216,.1)" } }, o.severity)),
        h("div", { style: { fontSize: 11.5, color: "#4a5680", marginTop: 5, lineHeight: 1.5 } },
          M(o.latest) + " this month vs " + M(o.mean) + " avg" + (o.multiple ? " (" + o.multiple.toFixed(1) + "× baseline)" : "") + " · " + (o.direction === "spike" ? "spike" : "drop")),
        h("div", { style: { fontSize: 10.5, color: "#6475a0", marginTop: 3, fontFamily: K.MONO } }, "Z-score: " + o.zScore.toFixed(1) + " standard deviations " + (o.zScore >= 0 ? "above" : "below") + " normal · click to view transactions →")))
        : h("div", { style: { padding: 16, fontSize: 12.5, color: "#6475a0" } }, "No statistical outliers detected — account activity is within normal ranges (needs ≥4 months of history per account).");

      return [
        h(K.Card, { key: "o", title: "AUTOMATED OUTLIER DETECTION", sub: "Accounts more than 1.5σ from their trailing average · ranked by z-score" },
          h("div", { style: { padding: "4px 0" } }, cards)),
        anomalies.length ? h(K.Card, { key: "t", title: "TREND ANOMALIES", sub: "Accounts moving consistently in one direction" },
          anomalies.map((a, i) => h("div", { key: i, style: { display: "flex", gap: 10, alignItems: "center", padding: "8px 4px", borderBottom: "1px solid rgba(13,32,64,.05)" } },
            h("span", { style: { fontSize: 13 } }, a.dir === "up" ? "📈" : "📉"),
            h("div", { style: { fontSize: 12.5, color: "#1a2540" } },
              h("b", null, a.account), " " + (a.dir === "up" ? "up" : "down") + " " + a.months + " consecutive months (" + (a.cum >= 0 ? "+" : "") + a.cum.toFixed(0) + "% cumulative)")))) : null,
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_outliers", periodKey: "ltm", nonce: aiNonce,
          fallback: outliers.length ? ("Largest outlier: " + outliers[0].account + " at " + M(outliers[0].latest) + ", " + (outliers[0].multiple ? outliers[0].multiple.toFixed(1) + "× its baseline" : "z=" + outliers[0].zScore.toFixed(1)) + ". Review before it distorts the period.") : "No statistical outliers this period — spending is within normal ranges." }),
      ];
    }

    // ── Tab: Benchmarks ───────────────────────────────────────────────────────
    function renderBenchmarks() {
      const key = pickBenchmark(companyProfile);
      const B = BENCHMARKS[key];
      const metrics = [
        { label: "Gross Margin", you: gmPct == null ? null : gmPct / 100, b: B.gross_margin, higherBetter: true, fmt: (v) => (v * 100).toFixed(1) + "%" },
        { label: "EBITDA Margin", you: ebitdaPct == null ? null : ebitdaPct / 100, b: B.ebitda_margin, higherBetter: true, fmt: (v) => (v * 100).toFixed(1) + "%" },
        { label: "DSO", you: dso == null ? null : dso, b: B.dso, higherBetter: false, fmt: (v) => Math.round(v) + " days" },
        { label: "OpEx Ratio", you: opexPct == null ? null : opexPct / 100, b: B.opex_pct, higherBetter: false, fmt: (v) => (v * 100).toFixed(1) + "%" },
      ];

      const bar = (m) => {
        if (m.you == null) return h("div", { style: { fontSize: 11.5, color: "#6475a0" } }, "Needs more data");
        const lo = m.b.p25, hi = m.b.p75, span = (hi - lo) || 1;
        const posPct = Math.max(0, Math.min(1, (m.you - lo) / span)) * 100;
        // position of median tick
        const medPct = Math.max(0, Math.min(1, (m.b.p50 - lo) / span)) * 100;
        return h("div", null,
          h("div", { style: { position: "relative", height: 12, borderRadius: 6, background: "linear-gradient(90deg, rgba(28,78,216,.12), rgba(28,78,216,.28))", margin: "16px 0 6px" } },
            h("div", { style: { position: "absolute", left: medPct + "%", top: -4, width: 2, height: 20, background: "#0d2040", opacity: 0.5 } }),
            h("div", { style: { position: "absolute", left: "calc(" + posPct + "% - 6px)", top: -3, width: 12, height: 18, borderRadius: 3, background: "#009fa0", border: "2px solid white", boxShadow: "0 1px 3px rgba(0,0,0,.2)" } })),
          h("div", { style: { display: "flex", justifyContent: "space-between", fontSize: 9.5, color: "#94a3b8", fontFamily: K.MONO } },
            h("span", null, "P25 " + m.fmt(m.b.p25)), h("span", null, "P50 " + m.fmt(m.b.p50)), h("span", null, "P75 " + m.fmt(m.b.p75))));
      };
      const verdict = (m) => {
        if (m.you == null) return { icon: "—", text: "insufficient data", color: "#6475a0" };
        const aboveMed = m.higherBetter ? m.you >= m.b.p50 : m.you <= m.b.p50;
        return aboveMed
          ? { icon: "✅", text: "You: " + m.fmt(m.you) + " — " + (m.higherBetter ? "at/above median" : "at/below median (good)"), color: "#18a867" }
          : { icon: "⚠️", text: "You: " + m.fmt(m.you) + " — " + (m.higherBetter ? "below median" : "above median") + ", room to improve", color: "#d97706" };
      };

      const summaryItems = metrics.map((m) => { const v = verdict(m); return { icon: v.icon, text: "<b>" + m.label + "</b> — " + v.text.replace(/^You: /, ""), color: v.color }; });

      return [
        h("div", { key: "hd", style: { fontSize: 11.5, color: "#6475a0", marginBottom: 12 } },
          "Compared against ", h("b", null, B.label), " industry percentiles. ",
          h("span", { style: { color: "#94a3b8" } }, "Benchmarks are indicative reference ranges, not a guarantee of performance.")),
        h("div", { key: "m", className: "pa-grid-2" }, metrics.map((m, i) => h(K.Card, { key: i, title: m.label.toUpperCase(), sub: "Industry range · your position marked in teal" },
          bar(m),
          h("div", { style: { marginTop: 10, fontSize: 12, fontWeight: 600, color: verdict(m).color } }, verdict(m).icon + " " + verdict(m).text)))),
        h(K.Card, { key: "sum", title: "BENCHMARK SUMMARY", sub: B.label },
          h("div", { style: { padding: "4px 0" } }, summaryItems.map((it, i) => h("div", { key: i, style: { display: "flex", gap: 10, alignItems: "flex-start", padding: "7px 4px", borderBottom: "1px solid rgba(13,32,64,.05)" } },
            h("span", { style: { fontSize: 13 } }, it.icon),
            h("span", { style: { fontSize: 12.5, color: "#1a2540", lineHeight: 1.5 }, dangerouslySetInnerHTML: { __html: it.text } }))))),
        h(AICommentary, { key: "ai", tenantId, pageType: "intelligence_benchmarks", periodKey: "ltm", nonce: aiNonce,
          fallback: "Against " + B.label + " benchmarks, your gross margin is " + (gmPct == null ? "—" : gmPct.toFixed(1) + "%") + " (median " + (B.gross_margin.p50 * 100).toFixed(0) + "%) and EBITDA margin " + (ebitdaPct == null ? "—" : ebitdaPct.toFixed(1) + "%") + " (median " + (B.ebitda_margin.p50 * 100).toFixed(0) + "%)." }),
      ];
    }

    const TABS = [["overview", "Overview"], ["performance", "Performance"], ["runrate", "Run Rate"], ["margins", "Margins"], ["outliers", "Outliers"], ["benchmarks", "Benchmarks"]];
    const content = tab === "overview" ? renderOverview()
      : tab === "performance" ? renderPerformance()
      : tab === "runrate" ? renderRunRate()
      : tab === "margins" ? renderMargins()
      : tab === "outliers" ? renderOutliers()
      : renderBenchmarks();

    const controls = h("div", { style: { display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" } },
      h(K.PeriodControls, ps),
      h("button", { onClick: generateReport, style: { background: "rgba(255,255,255,.14)", border: "1px solid rgba(255,255,255,.24)", borderRadius: 7, padding: "6px 12px", color: "#eef2ff", fontSize: 11.5, fontWeight: 700, cursor: "pointer", fontFamily: "Inter, system-ui" } }, "✨ Generate AI Report"),
      h("button", { onClick: () => window.print(), style: { background: "rgba(255,255,255,.14)", border: "1px solid rgba(255,255,255,.24)", borderRadius: 7, padding: "6px 12px", color: "#eef2ff", fontSize: 11.5, fontWeight: 700, cursor: "pointer", fontFamily: "Inter, system-ui" } }, "⭳ Export"));

    return h(K.Shell, { hero: { eyebrow: "BUSINESS INTELLIGENCE", title: "Business Intelligence",
      subtitle: "Your CFO cockpit · " + range.label + " · everything about the business in one place", controls } },
      h(TabBar, { tab, setTab, tabs: TABS }),
      content);
  }

  window.IntelligencePage = Page;
})();
