// Strategic intelligence pages: Weekly Review, Risk Dashboard, Expense Intelligence, Sales Concentration

const { useState: useStateIns, useMemo: useMemoIns, useEffect: useEffectIns } = React;

// ────────────────────────────────────────────────────────────────────────
// WEEKLY BUSINESS REVIEW — the Monday-morning one-pager
// ────────────────────────────────────────────────────────────────────────
function WeeklyReviewPage({ data, bizType, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { pl, exceptions } = data;
  const { curIdx, cmpIdx, sumAt, period, cmpLbl, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);
  const periodLabel = (window.PERIOD_OPTIONS || []).find(o => o.v === period)?.l || "This month";

  const rev      = sumAt(pl.revenue, curIdx);
  const gp       = sumAt(pl.gp, curIdx);
  const ebitda   = sumAt(pl.ebitda, curIdx);
  const revPrior = sumAt(pl.revenue, cmpIdx);
  const revDelta = revPrior > 0 ? ((rev - revPrior) / revPrior) * 100 : 0;

  // What changed / what to fix / what to celebrate
  const changed = [
    { headline: "Revenue is on a 3-month uptrend",         detail: "+6.4% this week, +18% YTD. Polaris Beacon (+24%) and Aurelius Pro Kit drove most of the lift.", sentiment: "positive" },
    { headline: "Gross margin compressed 1.8 pp",          detail: "V-201 input cost increase hasn't been passed to wholesale. Costing $52K/month until addressed.", sentiment: "negative" },
    { headline: "AR aging > 60d up 34% vs trailing average", detail: "$62.4K concentrated in 3 customers. Cascade Foods (92 days) is a 2-sigma anomaly.", sentiment: "negative" },
    { headline: "Cash position improved 2.4%",             detail: "$1.82M on hand. Atlas Logistics ($48K) collection would extend runway by 26 days.", sentiment: "positive" },
    { headline: "South region pipeline at 0.9x quota",      detail: "Other regions average 2.4x. Coverage needs reallocating this week — affects Q3 revenue.", sentiment: "negative" },
  ];
  const toFix = [
    { headline: "Pass 4% of V-201 cost increase to wholesale",  impact: 312000, why: "Recovers $312K annualized; still 14% below DTC pricing. Volume risk is minimal per historical elasticity.", confidence: 86 },
    { headline: "Cancel 4 underused software subscriptions",   impact: 48000,  why: "All under 30% usage. No business impact. Free annualized margin.", confidence: 94 },
    { headline: "Place rush PO + air freight for Polaris Beacon", impact: 28000, why: "Stockout in 11 days; current air freight upgrade saves 12 days for +$2.4K landed.", confidence: 91 },
  ];
  const celebrate = [
    { headline: "Polaris Beacon line is your fastest-growing product",       detail: "+24% MoM, 62% margin. Worth a marketing pulse this quarter." },
  ];

  return (
    <div className="pc-page">
      <Card padding={32} style={{ background: "linear-gradient(135deg, rgba(110,231,183,0.04), rgba(99,102,241,0.04))", borderColor: "rgba(110,231,183,0.18)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24, flexWrap: "wrap", gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>Monday, May 14, 2026 · Week 20</div>
            <h1 style={{ fontSize: 34, fontFamily: "'Instrument Serif', serif", fontWeight: 400, margin: 0, lineHeight: 1.1 }}>Your week in one read.</h1>
            <div style={{ fontSize: 14, color: "var(--text-2)", marginTop: 8, maxWidth: 720, lineHeight: 1.5 }}>
              Designed to take 90 seconds. Skim what changed, decide what to fix, share what worked.
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="pc-btn-mini ghost"><Icon d={icons.download} size={12} /> Email to team</button>
            <button className="pc-btn-mini ghost"><Icon d={icons.download} size={12} /> Export PDF</button>
          </div>
        </div>

        <div className="pc-wbr-headlines">
          <div className="pc-wbr-headline">
            <div className="pc-wbr-headline-l">Revenue · {periodLabel}</div>
            <div className="pc-wbr-headline-v">{fmtUSD(rev, { compact: true })}</div>
            <div className="pc-wbr-headline-d" style={{ color: revDelta >= 0 ? "var(--positive)" : "var(--danger)" }}>{revDelta >= 0 ? "▲" : "▼"} {Math.abs(revDelta).toFixed(1)}% vs prior period</div>
          </div>
          <div className="pc-wbr-headline">
            <div className="pc-wbr-headline-l">Gross margin</div>
            <div className="pc-wbr-headline-v">{(gp/rev*100).toFixed(1)}%</div>
            <div className="pc-wbr-headline-d" style={{ color: "var(--danger)" }}>▼ 1.8 pp vs trailing 6-month</div>
          </div>
          <div className="pc-wbr-headline">
            <div className="pc-wbr-headline-l">EBITDA</div>
            <div className="pc-wbr-headline-v">{fmtUSD(ebitda, { compact: true })}</div>
            <div className="pc-wbr-headline-d" style={{ color: "var(--danger)" }}>▼ 3.2 pp margin compression</div>
          </div>
          <div className="pc-wbr-headline">
            <div className="pc-wbr-headline-l">Cash</div>
            <div className="pc-wbr-headline-v">{fmtUSD(data.cash.startCash, { compact: true })}</div>
            <div className="pc-wbr-headline-d" style={{ color: "var(--positive)" }}>▲ Runway 12+ months</div>
          </div>
        </div>
      </Card>

      <div className="pc-wbr-section">
        <div className="pc-wbr-section-hd">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div className="pc-wbr-section-num">1</div>
            <div>
              <h2 className="pc-wbr-section-title">5 things that changed</h2>
              <div className="pc-wbr-section-sub">Read in 30 seconds. Skip if nothing surprises you.</div>
            </div>
          </div>
        </div>
        <div className="pc-wbr-items">
          {changed.map((c, idx) => (
            <div key={idx} className={"pc-wbr-item pc-wbr-" + c.sentiment}>
              <div className="pc-wbr-item-num">{idx + 1}</div>
              <div style={{ flex: 1 }}>
                <div className="pc-wbr-item-title">{c.headline}</div>
                <div className="pc-wbr-item-body">{c.detail}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="pc-wbr-section">
        <div className="pc-wbr-section-hd">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div className="pc-wbr-section-num" style={{ background: "var(--warning)", color: "var(--bg-base)" }}>2</div>
            <div>
              <h2 className="pc-wbr-section-title">3 things to fix this week</h2>
              <div className="pc-wbr-section-sub">Estimated combined upside: <b style={{ color: "var(--positive)" }}>{fmtUSD(toFix.reduce((s,x) => s + x.impact, 0), { compact: true })}</b> annualized</div>
            </div>
          </div>
        </div>
        <div className="pc-wbr-fix-list">
          {toFix.map((f, idx) => (
            <div key={idx} className="pc-wbr-fix">
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="pc-wbr-fix-title">{f.headline}</div>
                <div className="pc-wbr-fix-why">{f.why}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8 }}>
                  <ConfBar v={f.confidence} />
                  <span style={{ fontSize: 11, color: "var(--text-3)" }}>AI confidence</span>
                </div>
              </div>
              <div className="pc-wbr-fix-impact">
                <div className="pc-wbr-fix-impact-v">{fmtUSD(f.impact, { compact: true })}</div>
                <div className="pc-wbr-fix-impact-l">annualized</div>
                <button className="pc-btn-mini" style={{ marginTop: 10 }}>Act on this</button>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="pc-wbr-section">
        <div className="pc-wbr-section-hd">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div className="pc-wbr-section-num" style={{ background: "var(--positive)", color: "var(--bg-base)" }}>3</div>
            <div>
              <h2 className="pc-wbr-section-title">1 thing worth celebrating</h2>
              <div className="pc-wbr-section-sub">Forward this to your team.</div>
            </div>
          </div>
        </div>
        <div className="pc-wbr-celebrate">
          {celebrate.map((c, idx) => (
            <div key={idx}>
              <div className="pc-wbr-celebrate-title">{c.headline}</div>
              <div className="pc-wbr-celebrate-body">{c.detail}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// RISK DASHBOARD — concentration + dependency risks
// ────────────────────────────────────────────────────────────────────────
function RiskPage({ data, bizType }) {
  const { profit, vendors, products } = data;
  // Customer concentration
  const sortedCust = [...profit].sort((a, b) => b.revenue - a.revenue);
  const totalRev = sortedCust.reduce((s, c) => s + c.revenue, 0);
  const top1Pct = (sortedCust[0]?.revenue || 0) / totalRev * 100;
  const top3Pct = sortedCust.slice(0, 3).reduce((s, c) => s + c.revenue, 0) / totalRev * 100;
  const top10Pct = sortedCust.slice(0, 10).reduce((s, c) => s + c.revenue, 0) / totalRev * 100;

  return (
    <div className="pc-page">
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Customer concentration" value={top3Pct.toFixed(0) + "%"} hint="Top 3 customers" accent={top3Pct > 40 ? "var(--danger)" : top3Pct > 25 ? "var(--warning)" : "var(--positive)"} />
        <KPICard label="Largest customer" value={top1Pct.toFixed(0) + "%"} hint={sortedCust[0]?.name || ""} accent={top1Pct > 20 ? "var(--danger)" : "var(--warning)"} />
        <KPICard label="Vendor dependency" value="42%" hint="Top vendor share of COGS" accent="var(--warning)" />
        <KPICard label="Aggregate risk score" value="6.8/10" hint="Medium risk · monitored" accent="var(--warning)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Risk diagnosis</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              Your <b>biggest exposure is customer concentration</b> — losing {sortedCust[0]?.name} alone removes {top1Pct.toFixed(0)}% of revenue. Diversification target: drop top-1 share below 15%. <b>V-205 is your only source of POL-550</b>, which is a critical SKU with no dual source — single-point-of-failure that doesn't show in financials until it breaks.
            </div>
          </div>
        </div>
      </div>

      <div className="pc-grid-2">
        <Card title="Customer concentration (Pareto)" subtitle="Top 10 customers cumulative share of revenue">
          <table className="pc-table compact">
            <thead><tr><th>#</th><th>Customer</th><th style={{textAlign:"right"}}>Revenue</th><th style={{textAlign:"right"}}>% of total</th><th>Cumulative</th></tr></thead>
            <tbody>
              {(() => {
                let cum = 0;
                return sortedCust.slice(0, 10).map((c, idx) => {
                  const pct = c.revenue / totalRev * 100;
                  cum += pct;
                  return (
                    <tr key={c.id} className={idx === 0 && pct > 20 ? "pc-row-danger" : ""}>
                      <td style={{paddingLeft: 14, fontFamily: "ui-monospace, monospace", fontSize: 11, color: "var(--text-3)"}}>{idx + 1}</td>
                      <td style={{fontWeight: 500}}>{c.name}</td>
                      <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(c.revenue, {compact: true})}</td>
                      <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: pct > 15 ? "var(--danger)" : pct > 8 ? "var(--warning)" : "var(--text-2)"}}>{pct.toFixed(1)}%</td>
                      <td><Bullet value={cum} target={50} max={100} accent={cum > 80 ? "var(--danger)" : "var(--accent-2)"} /></td>
                    </tr>
                  );
                });
              })()}
            </tbody>
          </table>
        </Card>

        <Card title="Vendor & supply risk" subtitle="Single-source SKUs and high-share vendors">
          <table className="pc-table compact">
            <thead><tr><th>Risk</th><th>Detail</th><th style={{textAlign:"right"}}>Exposure</th><th>Severity</th></tr></thead>
            <tbody>
              {[
                { r: "Single-source SKU", d: "POL-550 → V-205 only", e: 168200, s: "critical" },
                { r: "Vendor share", d: "V-201 = 42% of COGS", e: 384000, s: "high" },
                { r: "Geographic", d: "South region = 1 region · 1 person", e: 102000, s: "medium" },
                { r: "Key person", d: "Iris Calloway = 18% of billable hrs", e: 184000, s: "medium" },
                { r: "Credit exposure", d: "$48K AR > 60d to single customer", e: 48200, s: "medium" },
                { r: "Lease concentration", d: "3 of 9 stores expire same year", e: 248000, s: "low" },
              ].map((r, idx) => (
                <tr key={idx} className={r.s === "critical" ? "pc-row-danger" : ""}>
                  <td style={{paddingLeft: 14, fontWeight: 500}}>{r.r}</td>
                  <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{r.d}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.e, {compact: true})}</td>
                  <td><SevPill sev={r.s} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      <Card title="Customer-loss scenario" subtitle="Cascade impact if your largest customer leaves"
            action={<ExportButton rows={sortedCust.slice(0, 3).map((c, idx) => ({ Rank: idx + 1, Customer: c.name, Revenue: c.revenue, RevSharePct: ((c.revenue/totalRev)*100).toFixed(1), GPLost: c.gp, NetProfitLost: c.netProfit }))} filename="Concentration_risk" />} padding={0}>
        <table className="pc-table">
          <thead><tr><th>If you lose…</th><th style={{textAlign:"right"}}>Revenue lost</th><th style={{textAlign:"right"}}>GP lost</th><th style={{textAlign:"right"}}>Net profit lost</th><th>Mitigation</th></tr></thead>
          <tbody>
            {sortedCust.slice(0, 3).map((c, idx) => (
              <tr key={c.id}>
                <td style={{paddingLeft: 14, fontWeight: 500}}>{c.name} <span style={{ color: "var(--text-3)", fontSize: 11 }}>({c.segment})</span></td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--danger)"}}>−{fmtUSD(c.revenue)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--danger)"}}>−{fmtUSD(c.gp)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--danger)", fontWeight: 500}}>−{fmtUSD(c.netProfit)}</td>
                <td style={{fontSize: 11.5, color: "var(--text-2)"}}>
                  {idx === 0 ? "Replacement would require " + Math.ceil(c.revenue / 18000) + " new mid-market wins" :
                   idx === 1 ? "Pipeline coverage in segment must increase to 3x" :
                   "Replacement plan: pipeline coverage adequate"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// EXPENSE INTELLIGENCE — spend analytics, fixed vs variable, savings ops
// ────────────────────────────────────────────────────────────────────────
function ExpensesPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { pl } = data;
  const { curIdx, cmpIdx, sumAt, cmpMult, compareDeltaSub, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);
  const opex = sumAt(pl.opex, curIdx);
  const opexPrev = sumAt(pl.opex, cmpIdx) * cmpMult;
  const periodMonths = curIdx.length;

  const categories = [
    { name: "Personnel — Salaries & Benefits", amt: Math.round(opex * 0.51), fixed: true,  delta: 2.1, vs: "headcount growth" },
    { name: "Sales & Marketing",               amt: Math.round(opex * 0.18), fixed: false, delta: 8.4, vs: "revenue" },
    { name: "Software & Subscriptions",         amt: Math.round(opex * 0.09), fixed: true,  delta: 22.4, vs: "seat count" },
    { name: "Facilities & Rent",                amt: Math.round(opex * 0.08), fixed: true,  delta: 0,    vs: "no change" },
    { name: "Professional Services",            amt: Math.round(opex * 0.07), fixed: false, delta: 4.2,  vs: "project intensity" },
    { name: "Travel & Entertainment",           amt: Math.round(opex * 0.04), fixed: false, delta: 14.8, vs: "seasonality" },
    { name: "G&A — Other",                     amt: Math.round(opex * 0.03), fixed: true,  delta: -1.2, vs: "trimmed Q1" },
  ];
  const totalFixed = categories.filter(c => c.fixed).reduce((s,c) => s + c.amt, 0);
  const totalVariable = opex - totalFixed;

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Total opex" value={fmtUSD(opex, { compact: true })} delta={opexPrev > 0 ? deltaPct(opex, opexPrev) : null} sub={compareDeltaSub || "vs. last period"} accent="var(--warning)" spark={pl.opex} />
        <KPICard label="Fixed costs"        value={fmtUSD(totalFixed, { compact: true })} hint={`${(totalFixed/opex*100).toFixed(0)}% of opex`} accent="var(--accent-2)" />
        <KPICard label="Variable costs"     value={fmtUSD(totalVariable, { compact: true })} hint={`${(totalVariable/opex*100).toFixed(0)}% of opex`} accent="var(--accent)" />
        <KPICard label="Savings identified" value={fmtUSD(58400)} hint="AI-detected · annualized" accent="var(--positive)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Spend diagnosis</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              <b>Software & Subscriptions grew 22.4% YoY</b> with no seat-count change — pure stair-step from auto-renewals. <b>Travel +14.8%</b> includes 2 hotel charges miscoded as Air. <b>$58K of annualized savings</b> are addressable in the next 30 days with no operational impact.
            </div>
          </div>
        </div>
        <button className="pc-btn-mini">Build savings plan</button>
      </div>

      <Card title="Expense by category" subtitle="Fixed vs variable · with vs-driver flag"
            action={<ExportButton rows={categories} filename="Expense_categories" />} padding={0}>
        <table className="pc-table">
          <thead><tr><th>Category</th><th>Type</th><th style={{textAlign:"right"}}>Amount</th><th style={{textAlign:"right"}}>% of opex</th><th style={{textAlign:"right"}}>Δ vs avg</th><th>Driver</th><th>Trend</th></tr></thead>
          <tbody>
            {categories.map((c, idx) => (
              <tr key={idx} className={c.delta > 15 ? "pc-row-danger" : ""}>
                <td style={{paddingLeft: 14, fontWeight: 500}}>{c.name}</td>
                <td><span className="pc-chip">{c.fixed ? "Fixed" : "Variable"}</span></td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(c.amt)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--text-2)"}}>{(c.amt/opex*100).toFixed(1)}%</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: c.delta > 10 ? "var(--danger)" : c.delta > 0 ? "var(--warning)" : "var(--positive)"}}>{c.delta > 0 ? "+" : ""}{c.delta.toFixed(1)}%</td>
                <td style={{fontSize: 11.5, color: "var(--text-3)"}}>{c.vs}</td>
                <td><Sparkline values={Array.from({length: 12}, () => c.amt * (0.9 + Math.random() * 0.2))} width={70} height={22} color={c.delta > 10 ? "var(--danger)" : "var(--accent-2)"} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Card title="Savings opportunities" subtitle="AI-identified · ranked by addressability"
            action={<button className="pc-btn-mini">Approve all</button>} padding={0}>
        <table className="pc-table">
          <thead><tr><th>Opportunity</th><th>Type</th><th style={{textAlign:"right"}}>Annual savings</th><th>Effort</th><th>Risk</th><th></th></tr></thead>
          <tbody>
            {[
              { o: "Cancel 4 SaaS tools with <30% usage", t: "Software", a: 48000, e: "1 hour", r: "low" },
              { o: "Recode 2 hotel charges → Lodging acct",  t: "Bookkeeping", a: 0, e: "5 min", r: "low" },
              { o: "Renegotiate co-working membership",      t: "Facilities", a: 6800, e: "1 call", r: "low" },
              { o: "Switch payment processor (3.0 → 2.7%)", t: "Payments", a: 14400, e: "2 weeks", r: "low" },
              { o: "Consolidate AWS accounts (4 → 1)",       t: "Cloud", a: 8200, e: "1 day", r: "medium" },
            ].map((r, idx) => (
              <tr key={idx}>
                <td style={{paddingLeft: 14, fontWeight: 500}}>{r.o}</td>
                <td><span className="pc-chip">{r.t}</span></td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500, color: "var(--positive)"}}>{r.a > 0 ? "+" : ""}{fmtUSD(r.a)}</td>
                <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{r.e}</td>
                <td><SevPill sev={r.r === "low" ? "low" : "medium"} /></td>
                <td><button className="pc-btn-mini ghost">Apply</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// SALES CONCENTRATION & REPEAT PATTERNS
// ────────────────────────────────────────────────────────────────────────
function SalesPatternsPage({ data, period: globalPeriod }) {
  const { profit } = data;
  const { PeriodComparerEl } = window.usePeriod(globalPeriod);
  const sorted = [...profit].sort((a, b) => b.revenue - a.revenue);
  const totalRev = sorted.reduce((s, c) => s + c.revenue, 0);
  // Repeat pattern mock data
  const repeatBuckets = [
    { label: "Active (≤30d)",     count: 38, rev: Math.round(totalRev * 0.62), color: "var(--positive)" },
    { label: "Slowing (31-90d)",  count: 24, rev: Math.round(totalRev * 0.28), color: "var(--accent-2)" },
    { label: "At risk (91-180d)", count: 14, rev: Math.round(totalRev * 0.08), color: "var(--warning)" },
    { label: "Churned (>180d)",   count: 8,  rev: Math.round(totalRev * 0.02), color: "var(--danger)" },
  ];

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Total customers" value={sorted.length} accent="var(--accent)" />
        <KPICard label="Top 10 share" value={(sorted.slice(0, 10).reduce((s,c) => s + c.revenue, 0) / totalRev * 100).toFixed(0) + "%"} hint="of revenue" accent="var(--accent-2)" />
        <KPICard label="At-risk customers" value={14} hint={`${fmtUSD(repeatBuckets[2].rev, {compact:true})} of revenue`} accent="var(--warning)" />
        <KPICard label="Upsell candidates" value={11} hint="High-fit, low-penetration" accent="var(--positive)" />
      </div>

      <div className="pc-grid-2">
        <Card title="Repeat purchase pattern" subtitle="Where each customer is in their lifecycle">
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {repeatBuckets.map((b, idx) => (
              <div key={idx}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 6 }}>
                  <span style={{ fontWeight: 500 }}>{b.label}</span>
                  <span><span style={{ fontFamily: "ui-monospace, monospace", color: b.color }}>{b.count}</span> <span style={{ color: "var(--text-3)" }}>· {fmtUSD(b.rev, { compact: true })}</span></span>
                </div>
                <div style={{ height: 8, background: "var(--bg-elev-2)", borderRadius: 1 }}>
                  <div style={{ width: (b.rev / totalRev * 100) + "%", height: "100%", background: b.color, borderRadius: 1 }} />
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card title="At-risk customers" subtitle="Order pattern broke from historical">
          <table className="pc-table compact">
            <thead><tr><th>Customer</th><th style={{textAlign:"right"}}>LTM rev</th><th>Last order</th><th>Trend</th></tr></thead>
            <tbody>
              {[
                { c: "Halcyon Group",    r: 184000, l: "112d ago", t: "down" },
                { c: "Sutter & Knox",    r: 84000,  l: "94d ago",  t: "down" },
                { c: "Vellum Studios",   r: 28000,  l: "138d ago", t: "down" },
                { c: "Meridian Health",  r: 142000, l: "62d ago",  t: "slowing" },
                { c: "Brightside Co.",   r: 64000,  l: "84d ago",  t: "slowing" },
              ].map((r, idx) => (
                <tr key={idx}>
                  <td style={{paddingLeft: 14, fontWeight: 500}}>{r.c}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.r, {compact: true})}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", fontSize: 11.5, color: r.l.includes("1") && parseInt(r.l) > 100 ? "var(--danger)" : "var(--warning)"}}>{r.l}</td>
                  <td><span className="pc-chip" style={{color: r.t === "down" ? "var(--danger)" : "var(--warning)"}}>{r.t}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      <Card title="Upsell candidates" subtitle="Lookalike modeling · customers who fit your top-cohort profile but haven't expanded"
            action={<ExportButton rows={sorted.slice(0, 11)} filename="Upsell_candidates" />} padding={0}>
        <table className="pc-table">
          <thead><tr><th>Customer</th><th>Segment</th><th style={{textAlign:"right"}}>Current ARR</th><th style={{textAlign:"right"}}>Potential ARR</th><th>Fit</th><th>Missing product</th></tr></thead>
          <tbody>
            {[
              { c: "Brightside Co.",    s: "Mid-Market", a: 48000,  p: 124000, f: 88, m: "Premium tier" },
              { c: "Aperture Labs",     s: "Mid-Market", a: 92000,  p: 142000, f: 84, m: "Add-on services" },
              { c: "Quorum Bio",        s: "Mid-Market", a: 38000,  p: 98000,  f: 81, m: "Full platform" },
              { c: "Polaris Retail",    s: "SMB",        a: 14000,  p: 38000,  f: 76, m: "Mid-Market features" },
              { c: "Cascade Foods",     s: "Mid-Market", a: 84000,  p: 124000, f: 72, m: "Renewal upsell" },
              { c: "Vellum Studios",    s: "SMB",        a: 18000,  p: 38000,  f: 68, m: "Premium tier" },
            ].map((r, idx) => (
              <tr key={idx}>
                <td style={{paddingLeft: 14, fontWeight: 500}}>{r.c}</td>
                <td><span className="pc-chip">{r.s}</span></td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.a)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500, color: "var(--positive)"}}>{fmtUSD(r.p)}</td>
                <td><Bullet value={r.f} target={70} max={100} accent={r.f >= 80 ? "var(--positive)" : r.f >= 70 ? "var(--accent-2)" : "var(--warning)"} /></td>
                <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{r.m}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

Object.assign(window, { WeeklyReviewPage, RiskPage, ExpensesPage, SalesPatternsPage });

// ────────────────────────────────────────────────────────────────────────
// PRICING INTELLIGENCE — list vs net, discount leakage, elasticity
// ────────────────────────────────────────────────────────────────────────
function PricingPage({ data, period: globalPeriod }) {
  const { PeriodComparerEl } = window.usePeriod(globalPeriod);
  const { products, profit } = data;
  const items = products.map((p, i) => {
    const listPrice = p.price;
    const avgDiscountPct = [3.2, 4.8, 6.2, 8.4, 11.2, 14.4, 9.8, 12.4, 5.2, 8.8, 18.4, 22.6][i] || 6;
    const netPrice = listPrice * (1 - avgDiscountPct / 100);
    const targetDiscount = listPrice >= 1000 ? 5 : listPrice >= 400 ? 8 : 10;
    const leakage = avgDiscountPct - targetDiscount;
    const realized = (netPrice / listPrice) * 100;
    return {
      sku: p.sku, name: p.name, listPrice, netPrice, avgDiscountPct, targetDiscount,
      leakage, realized, gmAtNet: ((netPrice - p.cost) / netPrice) * 100, gmAtList: ((listPrice - p.cost) / listPrice) * 100,
    };
  });
  const totalLeakage = items.reduce((s, it) => s + (it.leakage > 0 ? (it.listPrice * it.leakage / 100 * 24) : 0), 0); // 24 units avg/mo

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Realized price %"     value="91.4%" delta={-1.8} sub="of list, blended" accent="var(--warning)" />
        <KPICard label="Avg discount"         value="8.6%" delta={1.2} sub="vs. 6% target" accent="var(--warning)" />
        <KPICard label="Discount leakage"     value={fmtUSD(totalLeakage, { compact: true })} hint="vs. target · annualized" accent="var(--danger)" />
        <KPICard label="GM% lift if at target" value="+2.4 pp" hint="If discounts hit target" accent="var(--positive)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Pricing diagnosis</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              <b>3 SKUs discount past target by 8+ points</b> — Meridian Tote and Solas line are bleeding margin to clear stock. Discounts on Premium tier are tightly held (3–5%) but creeping up (+1.4 pp YTD). Tightening discount approval workflow on the 3 outliers recovers roughly <b>{fmtUSD(totalLeakage * 0.6, { compact: true })}</b> annualized with no volume risk.
            </div>
          </div>
        </div>
        <button className="pc-btn-mini">Approve plan</button>
      </div>

      <Card title="Price realization by SKU" subtitle="List price vs. avg net selling price · vs. target discount"
            action={<ExportButton rows={items} filename="Price_realization" />} padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>SKU</th>
              <th>Product</th>
              <th style={{textAlign:"right"}}>List price</th>
              <th style={{textAlign:"right"}}>Avg disc</th>
              <th style={{textAlign:"right"}}>Net price</th>
              <th style={{textAlign:"right"}}>vs target</th>
              <th>Realization</th>
              <th style={{textAlign:"right"}}>GM @ list</th>
              <th style={{textAlign:"right"}}>GM @ net</th>
            </tr>
          </thead>
          <tbody>
            {items.map((it, idx) => (
              <tr key={idx} className={it.leakage > 5 ? "pc-row-danger" : ""}>
                <td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5, color: "var(--text-2)"}}>{it.sku}</td>
                <td style={{fontWeight: 500}}>{it.name}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(it.listPrice)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: it.avgDiscountPct > it.targetDiscount ? "var(--danger)" : "var(--positive)"}}>{it.avgDiscountPct.toFixed(1)}%</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 500}}>{fmtUSD(it.netPrice)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: it.leakage > 0 ? "var(--danger)" : "var(--positive)"}}>{it.leakage > 0 ? "+" : ""}{it.leakage.toFixed(1)} pp</td>
                <td><Bullet value={it.realized} target={92} max={100} accent={it.realized >= 92 ? "var(--positive)" : it.realized >= 85 ? "var(--warning)" : "var(--danger)"} /></td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--positive)"}}>{it.gmAtList.toFixed(1)}%</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: it.gmAtNet >= 50 ? "var(--positive)" : "var(--warning)"}}>{it.gmAtNet.toFixed(1)}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div className="pc-grid-2">
        <Card title="Discount leakage by reason" subtitle="Where margin is leaving the business">
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {[
              { c: "Customer-specific (negotiated)", amt: 184000, pct: 42, color: "var(--accent-2)" },
              { c: "Volume discounts",               amt: 124000, pct: 28, color: "var(--accent)" },
              { c: "Slow-stock liquidation",         amt: 84000,  pct: 19, color: "var(--warning)" },
              { c: "Promotional events",             amt: 38000,  pct: 9,  color: "var(--positive)" },
              { c: "Returns / RMAs",                 amt: 8400,   pct: 2,  color: "var(--danger)" },
            ].map((r, i) => (
              <div key={i}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 6 }}>
                  <span>{r.c}</span>
                  <span><span style={{ fontFamily: "ui-monospace, monospace", color: r.color }}>{fmtUSD(r.amt, { compact: true })}</span> <span style={{ color: "var(--text-3)" }}>· {r.pct}%</span></span>
                </div>
                <div style={{ height: 8, background: "var(--bg-elev-2)", borderRadius: 1 }}>
                  <div style={{ width: r.pct + "%", height: "100%", background: r.color, borderRadius: 1 }} />
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card title="Price elasticity by segment" subtitle="−% volume change per +1% price">
          <table className="pc-table compact">
            <thead><tr><th>Segment</th><th style={{textAlign:"right"}}>Elasticity</th><th>Sensitivity</th><th style={{textAlign:"right"}}>Recommended ↑</th></tr></thead>
            <tbody>
              {[
                { s: "Enterprise",  e: -0.2, rec: "+6%", sens: "low" },
                { s: "Mid-Market", e: -0.4, rec: "+4%", sens: "low" },
                { s: "Wholesale",  e: -0.6, rec: "+3%", sens: "medium" },
                { s: "SMB",        e: -0.9, rec: "+2%", sens: "medium" },
                { s: "DTC",        e: -1.4, rec: "Hold", sens: "high" },
                { s: "Marketplace", e: -1.8, rec: "Test +1%", sens: "high" },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight: 500}}>{r.s}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{r.e.toFixed(1)}</td>
                  <td><span className="pc-statpill" style={{background: r.sens === "low" ? "rgba(110,231,183,0.10)" : r.sens === "medium" ? "rgba(251,191,36,0.10)" : "rgba(248,113,113,0.10)", color: r.sens === "low" ? "var(--positive)" : r.sens === "medium" ? "var(--warning)" : "var(--danger)"}}>{r.sens}</span></td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 500, color: "var(--accent)"}}>{r.rec}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// SUBSCRIPTION ANALYTICS — for subscription / recurring revenue businesses
// ────────────────────────────────────────────────────────────────────────
function SubscriptionPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { curIdx, cmpIdx, compareDeltaSub, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);
  // MRR data — synthetic 12-month trend (index-aligned with PL months)
  const mrrSeries = [184000, 198000, 212000, 224000, 238000, 251000, 264000, 278000, 292000, 308000, 324000, 348000];
  const lastIdx = curIdx[curIdx.length - 1] ?? 11;
  const prevIdx = cmpIdx[cmpIdx.length - 1] ?? Math.max(0, lastIdx - 1);
  const mrr = mrrSeries[lastIdx];
  const mrrPrev = mrrSeries[prevIdx];
  const arr = mrr * 12;
  const customers = 218;
  const grossRetention = 91;
  const netRetention = 118;
  const churnRate = (100 - grossRetention) / 12; // monthly

  // MRR movement decomposition for current month
  const movement = {
    starting: mrrPrev,
    newMrr: 24000,
    expansion: 14000,
    contraction: -5400,
    churn: -8600,
    ending: mrr,
  };

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="MRR" value={fmtUSD(mrr, { compact: true })} delta={deltaPct(mrr, mrrPrev)} sub={compareDeltaSub || "vs. prior period"} spark={mrrSeries} accent="var(--accent)" />
        <KPICard label="ARR" value={fmtUSD(arr, { compact: true })} delta={deltaPct(mrr, mrrPrev)} sub="annualized" accent="var(--accent-2)" />
        <KPICard label="Net retention" value={netRetention + "%"} delta={3.2} sub="vs. trailing 6mo" accent="var(--positive)" />
        <KPICard label="Gross retention" value={grossRetention + "%"} delta={-0.4} sub="vs. trailing 6mo" accent="var(--warning)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>Subscription health</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              <b>Net retention is exceptional at 118%</b> — expansion is outpacing churn handily. The Q2 2025 cohort is showing the strongest survival curve in your history (94% at month-9). One watch item: <b>2 mid-market customers slowing</b> their seat adds — usual leading indicator of contraction. Worth a check-in this week.
            </div>
          </div>
        </div>
      </div>

      <Card title="MRR movement — current month" subtitle="Starting MRR + New + Expansion − Contraction − Churn = Ending MRR">
        <div className="pc-mrr-waterfall">
          {[
            { label: "Starting MRR",  v: movement.starting,  type: "start" },
            { label: "+ New",         v: movement.newMrr,    type: "pos" },
            { label: "+ Expansion",   v: movement.expansion, type: "pos" },
            { label: "− Contraction", v: movement.contraction, type: "neg" },
            { label: "− Churn",       v: movement.churn,     type: "neg" },
            { label: "Ending MRR",    v: movement.ending,    type: "end" },
          ].map((it, i) => (
            <div key={i} className={"pc-mrr-step pc-mrr-" + it.type}>
              <div className="pc-mrr-step-v">{it.v >= 0 ? "" : "−"}{fmtUSD(Math.abs(it.v), { compact: true })}</div>
              <div className="pc-mrr-step-l">{it.label}</div>
            </div>
          ))}
        </div>
      </Card>

      <div className="pc-grid-2">
        <Card title="MRR trend · 12 months" subtitle="Monthly recurring revenue trajectory">
          <AreaChart
            height={240}
            labels={data.pl.labels}
            series={[
              { name: "MRR", values: mrrSeries, color: "var(--accent)" },
            ]}
          />
        </Card>

        <Card title="Cohort retention" subtitle="% of cohort revenue retained · by acquisition quarter">
          <table className="pc-table compact">
            <thead><tr><th>Cohort</th><th style={{textAlign:"right"}}>Customers</th><th style={{textAlign:"right"}}>M0 MRR</th><th>M3</th><th>M6</th><th>M9</th><th>M12</th></tr></thead>
            <tbody>
              {[
                { c: "Q1 2024", n: 14, m0: 32000, ret: [100, 96, 94, 92, 88] },
                { c: "Q2 2024", n: 18, m0: 48000, ret: [100, 98, 94, 91, 86] },
                { c: "Q3 2024", n: 22, m0: 62000, ret: [100, 95, 92, 88, 84] },
                { c: "Q4 2024", n: 19, m0: 54000, ret: [100, 97, 94, 90, null] },
                { c: "Q1 2025", n: 24, m0: 71000, ret: [100, 98, 96, 94, null] },
                { c: "Q2 2025", n: 21, m0: 68000, ret: [100, 99, 96, null, null] },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight: 500}}>{r.c}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign: "right"}}>{r.n}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.m0, {compact: true})}</td>
                  {[1,2,3,4].map(idx => {
                    const v = r.ret[idx];
                    return <td key={idx}>{v === null ? <span style={{color:"var(--text-4)"}}>—</span> : <span style={{color: v >= 90 ? "var(--positive)" : v >= 85 ? "var(--warning)" : "var(--danger)", fontFamily: "ui-monospace, monospace", fontWeight: 500}}>{v}%</span>}</td>;
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      <div className="pc-grid-2">
        <Card title="Top expansion accounts" subtitle="Customers growing their MRR">
          <table className="pc-table compact">
            <thead><tr><th>Customer</th><th style={{textAlign:"right"}}>Old MRR</th><th style={{textAlign:"right"}}>New MRR</th><th style={{textAlign:"right"}}>Δ</th></tr></thead>
            <tbody>
              {[
                { c: "Halcyon Group",     o: 4800,  n: 7200, },
                { c: "Northwind Holdings", o: 8400, n: 11200 },
                { c: "Ironwood Partners", o: 5200, n: 6800 },
                { c: "Aperture Labs",     o: 3200, n: 4400 },
                { c: "Meridian Health",   o: 6400, n: 7600 },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft: 14, fontWeight: 500}}>{r.c}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--text-3)"}}>{fmtUSD(r.o)}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500}}>{fmtUSD(r.n)}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--positive)"}}>+{fmtUSD(r.n - r.o)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="At-risk subscribers" subtitle="Slowing usage, declining seats, or contract due">
          <table className="pc-table compact">
            <thead><tr><th>Customer</th><th style={{textAlign:"right"}}>MRR</th><th>Risk signal</th><th>Renewal</th></tr></thead>
            <tbody>
              {[
                { c: "Cascade Foods",   m: 5200, s: "Seats −20%", r: "Aug 2026" },
                { c: "Sutter & Knox",   m: 3800, s: "Logins −34%", r: "Jul 2026" },
                { c: "Polaris Retail",  m: 1400, s: "Contract due", r: "Jun 2026" },
                { c: "Vellum Studios",  m: 1200, s: "Payment 64d late", r: "Sep 2026" },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft: 14, fontWeight: 500}}>{r.c}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.m)}</td>
                  <td style={{fontSize: 11.5, color: "var(--danger)"}}>{r.s}</td>
                  <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{r.r}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { PricingPage, SubscriptionPage });
