// insights-panel.jsx
// ─────────────────────────────────────────────────────────────────────────────
// CFO INTELLIGENCE ENGINE
// Plain-English insights for a non-financial entrepreneur, on EVERY page.
// Answers three questions every time:
//   1. What happened this period (specific numbers)
//   2. Why it matters (plain English, no jargon)
//   3. What to do about it (specific actions with estimated impact)
//
// DETERMINISTIC: every insight traces to a real computed figure. Nothing is
// fabricated. Built from the ACTUAL app data shape:
//   data.plHistory = { revenue[], cogs[], opex[], gp[], ebitda[] }
//     (there is no net_income series — EBITDA is the bottom line, NI ≡ EBITDA)
//   data.bs        = { cash, accounts_receivable, accounts_payable, inventory, ... }
//   data.txns      = [{ account_name, canonical_category, posted_date, amount }]
//
// Registers window.InsightsPanel and window.buildInsights.
// ─────────────────────────────────────────────────────────────────────────────
(function () {
  const h = React.createElement;
  const { useState, useMemo } = React;

  // Map the app's real page keys onto the engine's internal page archetypes.
  const PAGE_ALIAS = {
    overview: "dashboard", dashboard: "dashboard", health: "dashboard",
    income_statement: "income-statement", "income-statement": "income-statement", financials: "income-statement",
    expenses: "expenses", opex_intelligence: "expenses", opex: "expenses",
    revenue_intelligence: "revenue", revenue: "revenue", sales: "revenue",
    working_capital: "working-capital", "working-capital": "working-capital",
    arap: "ar-ap", arap_analytics: "ar-ap", "ar-ap": "ar-ap",
    kpi_scorecard: "kpi-scorecard", "kpi-scorecard": "kpi-scorecard", ratios: "kpi-scorecard",
    cash: "cash-flow-runway", cash_forecast: "cash-flow-runway", "cash-flow-runway": "cash-flow-runway",
    cash_flow_statement: "cash-flow-statement", "cash-flow-statement": "cash-flow-statement",
    margin: "margin",
    balance_sheet: "balance-sheet", "balance-sheet": "balance-sheet",
  };

  // ─── INTELLIGENCE ENGINE ─────────────────────────────────────────────────
  function buildInsights(page, data, profile) {
    const plH  = (data && (data.plHistory || data.pl)) || {};
    const txns = (data && data.txns) || [];
    const bs   = (data && data.bs) || {};
    const prof = profile || (data && data.companyProfile) || {};
    const name = prof.name || prof.company_name || "Your business";
    const curr = prof.currency || "$";

    const fmt = (v) => {
      if (v === null || v === undefined || Number.isNaN(v)) return "—";
      const abs = Math.abs(v);
      const sign = v < 0 ? "-" : "";
      if (abs >= 1000000) return sign + curr + (abs / 1000000).toFixed(1) + "M";
      if (abs >= 1000)    return sign + curr + Math.round(abs / 1000) + "K";
      return sign + curr + Math.round(abs);
    };
    const pct = (a, b) => (b > 0 ? (((a - b) / b) * 100).toFixed(1) : null);
    const avg = (arr) => (arr.length ? arr.reduce((s, v) => s + (v || 0), 0) / arr.length : 0);
    const last = (arr, n = 1) => (Array.isArray(arr) ? arr : []).slice(-n);
    const lastVal = (arr) => last(arr, 1)[0] || 0;
    const prevVal = (arr) => last(arr, 2)[0] || 0;

    const rev     = lastVal(plH.revenue);
    const prevRev = prevVal(plH.revenue);
    const revChg  = pct(rev, prevRev);

    const gp       = lastVal(plH.gp);
    const gpMargin = rev > 0 ? (gp / rev) * 100 : 0;

    const opex      = lastVal(plH.opex);
    const prevOpex  = prevVal(plH.opex);
    const opexChg   = pct(opex, prevOpex);
    const opexRatio = rev > 0 ? (opex / rev) * 100 : 0;

    // NI ≡ EBITDA in this rollup (no separate net_income series exists).
    const ni       = lastVal(plH.ebitda);
    const prevNi   = prevVal(plH.ebitda);
    const niChg    = pct(ni, prevNi);
    const niMargin = rev > 0 ? (ni / rev) * 100 : 0;

    const avgRev  = avg(last(plH.revenue, 6));
    const avgOpex = avg(last(plH.opex, 6));

    // Top expense account (operating-cost categories only).
    const expenseAccounts = {};
    txns.filter((t) => {
      const cat = (t.canonical_category || "").toLowerCase();
      return ["opex", "expenses", "operating", "salary", "rent", "utilities"].some((k) => cat.includes(k));
    }).forEach((t) => {
      const acct = t.account_name || "Other";
      expenseAccounts[acct] = (expenseAccounts[acct] || 0) + Math.abs(parseFloat(t.amount || 0));
    });
    const topExpense = Object.entries(expenseAccounts).sort((a, b) => b[1] - a[1])[0];

    // Spike detection: account >20% above its prior-month average (and >$500).
    const acctMonthly = {};
    txns.forEach((t) => {
      const acct = t.account_name || "Other";
      const mon = (t.posted_date || t.date || "").slice(0, 7);
      if (!mon) return;
      if (!acctMonthly[acct]) acctMonthly[acct] = {};
      acctMonthly[acct][mon] = (acctMonthly[acct][mon] || 0) + Math.abs(parseFloat(t.amount || 0));
    });
    const spikes = [];
    Object.entries(acctMonthly).forEach(([acct, byMonth]) => {
      const months = Object.keys(byMonth).sort();
      if (months.length < 4) return;
      const recent = byMonth[months[months.length - 1]] || 0;
      const histAvg = avg(months.slice(0, -1).map((m) => byMonth[m] || 0));
      if (histAvg > 0 && recent > histAvg * 1.2 && recent - histAvg > 500) {
        spikes.push({ acct, recent, histAvg, delta: recent - histAvg, pct: (((recent - histAvg) / histAvg) * 100).toFixed(0) });
      }
    });
    spikes.sort((a, b) => b.delta - a.delta);

    const key = PAGE_ALIAS[(page || "").toLowerCase()] || (page || "").toLowerCase();

    switch (key) {
      case "dashboard": {
        const headline = rev > 0
          ? `${name} generated ${fmt(rev)} in revenue this period${revChg ? `, ${parseFloat(revChg) > 0 ? "▲ up" : "▼ down"} ${Math.abs(revChg)}% vs last month` : ""}.`
          : "Connect your accounting data to see personalised insights.";
        const items = [];

        if (gpMargin > 0) items.push({
          type: gpMargin > 40 ? "positive" : gpMargin > 20 ? "warning" : "critical",
          icon: gpMargin > 40 ? "✓" : "⚠",
          title: `Gross margin: ${gpMargin.toFixed(1)}%`,
          body: gpMargin > 40
            ? `For every dollar you earn, you keep about ${Math.round(gpMargin)}c after direct costs. This is healthy.`
            : `Your gross margin is tight — only ${gpMargin.toFixed(1)}% of revenue remains after direct costs. Review pricing and supplier costs.`,
          action: gpMargin < 30 ? `Increasing prices by 5% would add roughly ${fmt(rev * 0.05)} to gross profit.` : null,
        });

        if (opexRatio > 0) items.push({
          type: opexRatio < 50 ? "positive" : opexRatio < 70 ? "warning" : "critical",
          icon: opexRatio < 50 ? "✓" : "⚠",
          title: `Operating costs: ${opexRatio.toFixed(1)}% of revenue`,
          body: opexRatio < 50
            ? `Operating costs are well-controlled at ${fmt(opex)} — ${opexRatio.toFixed(1)}% of revenue.`
            : `Operating costs consumed ${opexRatio.toFixed(1)}% of revenue (${fmt(opex)}). ${opexRatio > 70 ? "This is high and needs attention." : "Monitor closely."}`,
          action: topExpense ? `Your largest expense is ${topExpense[0]} at ${fmt(topExpense[1])}. Start your review there.` : null,
        });

        if (spikes.length > 0) items.push({
          type: "warning",
          icon: "📈",
          title: `Unusual spend detected: ${spikes[0].acct}`,
          body: `${spikes[0].acct} is ${spikes[0].pct}% above its normal level this month — ${fmt(spikes[0].recent)} vs typical ${fmt(spikes[0].histAvg)}. Worth investigating.`,
          action: `Reviewing this one item could recover up to ${fmt(spikes[0].delta)} this period.`,
        });

        if (ni !== 0) items.push({
          type: ni > 0 ? "positive" : "critical",
          icon: ni > 0 ? "✓" : "🚨",
          title: `Bottom line: ${fmt(ni)} ${ni > 0 ? "profit" : "loss"}`,
          body: ni > 0
            ? `After operating costs, the business kept ${fmt(ni)} (${niMargin.toFixed(1)}% margin). ${niMargin > 15 ? "Excellent." : niMargin > 5 ? "Solid, with room to improve." : "Margins are thin — focus on cost reduction."}`
            : `The business ran a ${fmt(Math.abs(ni))} loss this period. Action is needed to cut costs or grow revenue.`,
          action: ni < 0 ? `Break-even needs either ${fmt(Math.abs(ni))} more revenue or the same reduction in costs.` : null,
        });

        return { headline, items, page: key };
      }

      case "income-statement": {
        const headline = `Your Income Statement shows how much ${name} earned and spent${rev > 0 ? `, resulting in a ${fmt(ni)} ${ni >= 0 ? "profit" : "loss"}` : ""}.`;
        const items = [];

        items.push({
          type: "info", icon: "📖",
          title: "How to read this statement",
          body: "Revenue minus Cost of Goods Sold = Gross Profit. Gross Profit minus Operating Expenses = EBITDA (the bottom line in this view). Each section is expandable.",
          action: "Click any account name to see its monthly trend and drill into individual transactions.",
        });

        if (revChg !== null) items.push({
          type: parseFloat(revChg) > 0 ? "positive" : "warning",
          icon: parseFloat(revChg) > 0 ? "▲" : "▼",
          title: `Revenue ${parseFloat(revChg) > 0 ? "grew" : "declined"} ${Math.abs(revChg)}% vs last month`,
          body: `Revenue moved from ${fmt(prevRev)} to ${fmt(rev)}. ${parseFloat(revChg) > 10 ? "Strong growth — understand what drove it so you can repeat it." : parseFloat(revChg) < -10 ? "Significant decline — investigate the cause." : "Movement is within a normal range."}`,
          action: null,
        });

        if (opexChg !== null && Math.abs(parseFloat(opexChg)) > 5) items.push({
          type: parseFloat(opexChg) > 10 ? "warning" : "neutral",
          icon: "💡",
          title: `Operating expenses ${parseFloat(opexChg) > 0 ? "increased" : "decreased"} ${Math.abs(opexChg)}% vs last month`,
          body: `Expenses moved from ${fmt(prevOpex)} to ${fmt(opex)}. ${spikes.length > 0 ? `The main driver appears to be ${spikes[0].acct}.` : "Review the expense breakdown below for drivers."}`,
          action: spikes.length > 0 ? `Investigate ${spikes[0].acct} — ${fmt(spikes[0].delta)} above normal.` : null,
        });

        return { headline, items, page: key };
      }

      case "expenses": {
        const headline = `Operating expenses totalled ${fmt(opex)} this period — ${opexRatio.toFixed(1)}% of revenue.`;
        const items = [];

        items.push({
          type: "info", icon: "💡",
          title: "What to look for",
          body: "Your top 3 expense categories usually make up 70-80% of total costs. Focus there first. Click any row to see its monthly trend.",
          action: topExpense ? `Your largest expense is ${topExpense[0]} at ${fmt(topExpense[1])} — start here.` : null,
        });

        spikes.slice(0, 2).forEach((spike) => {
          items.push({
            type: "warning", icon: "⚠",
            title: `${spike.acct} is ${spike.pct}% above normal`,
            body: `This month: ${fmt(spike.recent)} vs typical ${fmt(spike.histAvg)}. The ${fmt(spike.delta)} increase is worth checking before it becomes a pattern.`,
            action: `Click ${spike.acct} below to see the monthly breakdown and understand what changed.`,
          });
        });

        if (opexRatio > 60) items.push({
          type: "warning", icon: "⚠",
          title: `Cost ratio is high at ${opexRatio.toFixed(1)}%`,
          body: `Well-run businesses typically run a 40-55% opex ratio. You are about ${(opexRatio - 50).toFixed(1)} points above the midpoint.`,
          action: `Reducing opex by 10% would add roughly ${fmt(opex * 0.1)} to your bottom line.`,
        });

        return { headline, items, page: key };
      }

      case "revenue": {
        const headline = `Revenue was ${fmt(rev)} this period${revChg ? `, ${parseFloat(revChg) > 0 ? "up" : "down"} ${Math.abs(revChg)}% vs last month` : ""}.`;
        const items = [];

        items.push({
          type: parseFloat(revChg || 0) >= 0 ? "positive" : "warning",
          icon: parseFloat(revChg || 0) >= 0 ? "▲" : "▼",
          title: `Revenue trend: ${parseFloat(revChg || 0) >= 0 ? "Growing" : "Declining"}`,
          body: `${fmt(rev)} this period vs ${fmt(avgRev)} 6-month average. ${parseFloat(revChg || 0) > 0 ? "Momentum is positive — find your top growth drivers and double down." : "Revenue is below your recent average — check which income streams slowed."}`,
          action: "Click any revenue line below to see its monthly trend and concentration risk.",
        });

        const revByAcct = {};
        txns.filter((t) => {
          const cat = (t.canonical_category || "").toLowerCase();
          return cat.includes("revenue") || cat.includes("income") || cat.includes("sales");
        }).forEach((t) => {
          const acct = t.account_name || "Other";
          revByAcct[acct] = (revByAcct[acct] || 0) + Math.abs(parseFloat(t.amount || 0));
        });
        const totalRev = Object.values(revByAcct).reduce((s, v) => s + v, 0);
        const topRevAcct = Object.entries(revByAcct).sort((a, b) => b[1] - a[1])[0];
        if (topRevAcct && totalRev > 0) {
          const concentration = (topRevAcct[1] / totalRev) * 100;
          if (concentration > 50) items.push({
            type: "warning", icon: "⚠",
            title: `Revenue concentration risk: ${concentration.toFixed(0)}% from one source`,
            body: `${topRevAcct[0]} accounts for ${concentration.toFixed(0)}% of revenue. If this stream slows, it hits the whole business hard.`,
            action: "Diversify revenue streams to reduce dependency on any single source.",
          });
        }

        return { headline, items, page: key };
      }

      case "working-capital": {
        const cash = bs.cash || 0;
        const ar = bs.accounts_receivable || 0;
        const ap = bs.accounts_payable || 0;
        const inv = bs.inventory || 0;
        const wc = (cash + ar + inv) - ap;
        const monthlyBurn = avgOpex || 0;
        const runway = monthlyBurn > 0 ? Math.round(cash / monthlyBurn) : null;

        const headline = wc >= 0
          ? `Working capital is positive at ${fmt(wc)} — the business can cover its short-term obligations.`
          : `Working capital is negative at ${fmt(wc)} — the business may struggle to meet short-term obligations.`;
        const items = [];

        if (runway !== null) items.push({
          type: runway > 6 ? "positive" : runway > 3 ? "warning" : "critical",
          icon: runway > 6 ? "✓" : "⚠",
          title: `Cash runway: ${runway} months`,
          body: `At current spending (${fmt(monthlyBurn)}/month) and ${fmt(cash)} cash, you have ${runway} months. ${runway < 3 ? "Critically low — act now." : runway < 6 ? "Below comfortable levels — plan ahead." : "Healthy — maintain this buffer."}`,
          action: runway < 6 && ar > 0 ? `Accelerating collection of your ${fmt(ar)} in receivables could extend runway meaningfully.` : null,
        });

        if (ar > 0) {
          const annRev = last(plH.revenue, 12).reduce((s, v) => s + (v || 0), 0);
          const dso = annRev > 0 ? Math.round(ar / (annRev / 365)) : null;
          if (dso) items.push({
            type: dso < 30 ? "positive" : dso < 60 ? "warning" : "critical",
            icon: dso < 30 ? "✓" : "⚠",
            title: `Customers owe you ${fmt(ar)} — collecting in ~${dso} days`,
            body: `Days Sales Outstanding (DSO) of ${dso} days means it takes ${dso} days on average to get paid after a sale. ${dso > 45 ? "That's slow — faster collection frees up cash." : "That's reasonable."}`,
            action: dso > 45 ? `Cutting DSO by 10 days would release roughly ${fmt((annRev / 365) * 10)} in cash.` : null,
          });
        }

        return { headline, items, page: key };
      }

      case "ar-ap": {
        const ar = bs.accounts_receivable || 0;
        const ap = bs.accounts_payable || 0;
        const headline = `You are owed ${fmt(ar)} by customers and owe ${fmt(ap)} to suppliers. Net position: ${fmt(ar - ap)}.`;
        const items = [];

        items.push({
          type: "info", icon: "💡",
          title: "What this means for your cash",
          body: `Receivables (${fmt(ar)}) is cash you've earned but not yet collected — collect faster and more lands in your bank. Payables (${fmt(ap)}) is what you owe suppliers — paying later (within terms) preserves cash.`,
          action: ar > 0 ? "Collect your oldest invoices first — aged receivables are most at risk of becoming bad debt." : null,
        });

        if (ap > 0 && ar > ap * 2) items.push({
          type: "warning", icon: "⚠",
          title: "Customers owe you far more than you owe suppliers",
          body: `Your receivables (${fmt(ar)}) are ${(ar / Math.max(ap, 1)).toFixed(1)}x your payables (${fmt(ap)}). That sounds good, but it means a lot of cash is tied up waiting to be collected.`,
          action: "Review payment terms and chase overdue invoices weekly.",
        });

        return { headline, items, page: key };
      }

      case "kpi-scorecard": {
        const headline = `Your KPI Scorecard shows how ${name} performs across its key financial metrics.`;
        const items = [];

        items.push({
          type: "info", icon: "📊",
          title: "How to use this scorecard",
          body: "Green = at or above benchmark. Amber = watch closely. Red = needs attention. The benchmark bands show where similar businesses typically land.",
          action: "Start with any red KPI — those are your highest-impact improvement opportunities.",
        });

        if (gpMargin > 0 && gpMargin < 30) items.push({
          type: "warning", icon: "⚠",
          title: `Gross margin (${gpMargin.toFixed(1)}%) is below benchmark`,
          body: "Most businesses target a 35-60% gross margin. A low one means direct costs are eating too much of your revenue.",
          action: "Review pricing and supplier costs. A 5% price increase usually beats cost-cutting for impact.",
        });

        return { headline, items, page: key };
      }

      case "cash-flow-runway":
      case "cash-flow-statement": {
        const cash = bs.cash || 0;
        const monthlyBurn = avgOpex || 0;
        const runway = monthlyBurn > 0 ? Math.round(cash / monthlyBurn) : null;
        const headline = `Cash flow shows the actual movement of money in and out of ${name}.`;
        const items = [];

        items.push({
          type: "info", icon: "💡",
          title: "Profit is not the same as cash",
          body: "A business can be profitable and still run out of cash. Cash flow tracks money actually received and paid — not when it's earned or invoiced. That's why managing it matters.",
          action: "Collect receivables faster and time large payments deliberately.",
        });

        if (runway !== null) items.push({
          type: runway > 6 ? "positive" : runway > 3 ? "warning" : "critical",
          icon: runway > 6 ? "✓" : "🚨",
          title: `${runway} months of cash runway remaining`,
          body: `With ${fmt(cash)} cash and ~${fmt(monthlyBurn)}/month spend, you have ${runway} months before running out. ${runway < 3 ? "This needs immediate attention." : runway < 6 ? "Plan ahead — line up a credit facility as a buffer." : "Healthy position."}`,
          action: runway < 6 ? "Talk to your bank about a revolving credit facility before you need it." : null,
        });

        return { headline, items, page: key };
      }

      case "margin": {
        const headline = `Gross margin is ${gpMargin.toFixed(1)}% — you keep about ${Math.round(gpMargin)}c of every revenue dollar after direct costs.`;
        const items = [];
        items.push({
          type: "info", icon: "💡",
          title: "What margin tells you",
          body: `Gross profit was ${fmt(gp)} on ${fmt(rev)} of revenue. Margin is the single fastest lever on profitability — small pricing and cost changes compound here.`,
          action: gpMargin < 40 ? `A 5% price increase would add roughly ${fmt(rev * 0.05)} straight to gross profit.` : null,
        });
        if (gpMargin > 0) items.push({
          type: gpMargin > 40 ? "positive" : gpMargin > 20 ? "warning" : "critical",
          icon: gpMargin > 40 ? "✓" : "⚠",
          title: `Margin health: ${gpMargin > 40 ? "Healthy" : gpMargin > 20 ? "Watch" : "Under pressure"}`,
          body: gpMargin > 40 ? "You have comfortable room to absorb cost increases and invest in growth." : "Direct costs are taking a large share of revenue — review supplier pricing and your own price points.",
          action: null,
        });
        return { headline, items, page: key };
      }

      case "balance-sheet": {
        const cash = bs.cash || 0;
        const ar = bs.accounts_receivable || 0;
        const ap = bs.accounts_payable || 0;
        const headline = `Your balance sheet snapshot: ${fmt(cash)} cash, ${fmt(ar)} owed to you, ${fmt(ap)} you owe.`;
        const items = [];
        items.push({
          type: "info", icon: "📖",
          title: "How to read this",
          body: "Assets are what the business owns (cash, receivables, inventory). Liabilities are what it owes (payables, loans). The gap between them is your equity — the net worth of the business.",
          action: "Click any line to drill into the accounts that make it up.",
        });
        if (cash > 0 && ap > cash) items.push({
          type: "warning", icon: "⚠",
          title: "You owe suppliers more than you hold in cash",
          body: `Payables (${fmt(ap)}) exceed your cash (${fmt(cash)}). That's manageable if receivables are coming in soon, but watch the timing closely.`,
          action: "Match the timing of your collections against upcoming supplier payments.",
        });
        return { headline, items, page: key };
      }

      default: {
        return {
          headline: `${name} — financial intelligence powered by your real accounting data.`,
          items: [{
            type: "info", icon: "💡",
            title: "Click any number to drill down",
            body: "Every number on this page is clickable. Click an account or metric to see its monthly trend, what drives it, and specific recommendations.",
            action: null,
          }],
          page: key,
        };
      }
    }
  }

  // ─── INSIGHTS PANEL COMPONENT ───────────────────────────────────────────
  function InsightsPanel({ data, companyProfile, page, context }) {
    const [expanded, setExpanded] = useState(true);
    const [activeItem, setActiveItem] = useState(null);

    const insights = useMemo(
      () => buildInsights(page, data, companyProfile),
      [page, data, companyProfile]
    );

    if (!insights) return null;

    const typeStyle = (type) => ({
      positive: { bg: "rgba(0,184,148,.06)",   border: "rgba(0,184,148,.2)",   dot: "#00b894", text: "#065f46" },
      warning:  { bg: "rgba(245,158,11,.06)",  border: "rgba(245,158,11,.2)",  dot: "#f59e0b", text: "#92400e" },
      critical: { bg: "rgba(231,76,60,.06)",   border: "rgba(231,76,60,.2)",   dot: "#e74c3c", text: "#991b1b" },
      info:     { bg: "rgba(28,78,216,.06)",   border: "rgba(28,78,216,.2)",   dot: "#1C4ED8", text: "#1e3a8a" },
      neutral:  { bg: "rgba(100,117,160,.06)", border: "rgba(100,117,160,.2)", dot: "#6475a0", text: "#374151" },
    }[type] || { bg: "rgba(28,78,216,.06)", border: "rgba(28,78,216,.2)", dot: "#1C4ED8", text: "#1e3a8a" });

    const statusPriority = { critical: 0, warning: 1, positive: 2, info: 3, neutral: 4 };
    const overallStatus = insights.items && insights.items.length
      ? insights.items.reduce((worst, item) =>
          (statusPriority[item.type] || 4) < (statusPriority[worst.type] || 4) ? item : worst
        ).type
      : "info";
    const overall = typeStyle(overallStatus);

    return h("div", { style: { background: overall.bg, border: `1px solid ${overall.border}`, borderRadius: "12px", marginBottom: "20px", overflow: "hidden" } },

      h("div", {
        onClick: () => setExpanded((e) => !e),
        style: { padding: "14px 18px", display: "flex", justifyContent: "space-between", alignItems: "center", cursor: "pointer", gap: "12px" },
      },
        h("div", { style: { display: "flex", gap: "10px", alignItems: "center" } },
          h("div", { style: { background: overall.dot, borderRadius: "6px", padding: "3px 8px", fontSize: "9px", fontWeight: "800", color: "white", letterSpacing: ".08em", flexShrink: 0 } }, "CFO AI"),
          h("div", { style: { fontSize: "13px", fontWeight: "600", color: "#0d2040", lineHeight: "1.4" } }, insights.headline)
        ),
        h("div", { style: { display: "flex", alignItems: "center", gap: "8px", flexShrink: 0 } },
          insights.items && insights.items.length > 0 && h("div", { style: { background: overall.dot, color: "white", borderRadius: "12px", padding: "2px 8px", fontSize: "10px", fontWeight: "700" } }, insights.items.length + " insights"),
          h("div", { style: { color: "#6475a0", fontSize: "12px" } }, expanded ? "▲" : "▼")
        )
      ),

      expanded && insights.items && insights.items.length > 0 && h("div", { style: { borderTop: `1px solid ${overall.border}` } },
        insights.items.map((item, i) => {
          const s = typeStyle(item.type);
          const isActive = activeItem === i;
          return h("div", {
            key: i,
            onClick: () => setActiveItem(isActive ? null : i),
            style: { padding: "12px 18px", borderBottom: i < insights.items.length - 1 ? `1px solid ${overall.border}` : "none", cursor: "pointer", background: isActive ? s.bg : "transparent", transition: "background .15s" },
          },
            h("div", { style: { display: "flex", gap: "10px", alignItems: "flex-start" } },
              h("div", { style: { width: "20px", height: "20px", borderRadius: "50%", background: s.dot, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, fontSize: "10px" } }, item.icon),
              h("div", { style: { flex: 1 } },
                h("div", { style: { fontSize: "12px", fontWeight: "700", color: "#0d2040", marginBottom: isActive ? "6px" : "0" } }, item.title),
                isActive && h("div", { style: { fontSize: "11.5px", color: "#4a5680", lineHeight: "1.6", marginBottom: item.action ? "8px" : "0" } }, item.body),
                isActive && item.action && h("div", { style: { fontSize: "11px", color: s.text, fontWeight: "600", background: s.bg, border: `1px solid ${s.border}`, borderRadius: "6px", padding: "6px 10px", display: "flex", alignItems: "center", gap: "6px" } },
                  h("span", null, "→"),
                  item.action
                )
              ),
              !isActive && h("div", { style: { color: "#6475a0", fontSize: "10px", flexShrink: 0 } }, "›")
            )
          );
        })
      )
    );
  }

  window.InsightsPanel = InsightsPanel;
  window.buildInsights = buildInsights;
})();
