// Revenue pages: Sales Analysis (3-level drill), Customer Profitability, Margin

const { useState: useStateR, useMemo: useMemoR } = React;

// ────────────────────────────────────────────────────────────────────────
// SALES ANALYSIS — with full 3-level drill
// ────────────────────────────────────────────────────────────────────────
function SalesPage({ data, onDrill, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { sales, pl } = data;
  const [view, setView] = useStateR("region");
  const [trendGran, setTrendGran] = useStateR("Monthly");
  const [drill, setDrill] = useStateR(null);
  const { curIdx, cmpIdx, sumAt, cmpMult, cmpLbl, compareDeltaSub, compareTo, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);

  const rev      = sumAt(pl.revenue, curIdx);
  const revPrev  = compareTo === "none" ? null : Math.round(sumAt(pl.revenue, cmpIdx) * cmpMult);
  const orders   = Math.round(rev / 5324);
  const ordersPrev = revPrev != null ? Math.round(revPrev / 5324) : null;
  const aov      = orders > 0 ? rev / orders : 0;
  const aovPrev  = ordersPrev > 0 ? revPrev / ordersPrev : null;

  // ── Top sellers (mock data) ──
  const topProducts = useMemoR(() => [
    { name: "Aurelius Pro Kit",  sku: "AUR-100", rev: 384200, units: 257, gm: 59.1, delta: 12.4 },
    { name: "Orion Module 4U",   sku: "ORI-220", rev: 198400, units: 324, gm: 59.5, delta: 8.2 },
    { name: "Polaris Beacon",    sku: "POL-550", rev: 168200, units: 89,  gm: 62.4, delta: 24.1 },
    { name: "Aurelius Lite",     sku: "AUR-101", rev: 134800, units: 151, gm: 57.1, delta: -4.2 },
    { name: "Polaris Mount",     sku: "POL-551", rev: 88400,  units: 361, gm: 68.2, delta: 6.8 },
    { name: "Orion Module 2U",   sku: "ORI-221", rev: 71200,  units: 173, gm: 56.8, delta: -2.1 },
    { name: "Vela Cable Loom",   sku: "VEL-310", rev: 41800,  units: 475, gm: 75.0, delta: 14.2 },
    { name: "Meridian Sleeve",   sku: "MER-440", rev: 18100,  units: 125, gm: 73.8, delta: -28.4 },
  ], []);

  // ── Region detail (drill 1) ──
  const regionDetail = (region) => {
    const r = sales.byRegion.find(x => x.region === region);
    return {
      ...r,
      productMix: topProducts.slice(0, 6).map(p => ({
        ...p,
        rev: Math.round(p.rev * (region === "West" ? 0.42 : region === "East" ? 0.31 : region === "Central" ? 0.21 : 0.14)),
        units: Math.round(p.units * (region === "West" ? 0.42 : region === "East" ? 0.31 : region === "Central" ? 0.21 : 0.14)),
      })),
      customers: data.customers.filter(c => c.region === region).map((c, idx) => ({
        ...c,
        rev: Math.round((48000 + idx * 14000) * (region === "West" ? 1.1 : 0.95)),
        invoices: 4 + (idx % 5),
      })),
    };
  };

  // ── Invoice detail (drill 3) ──
  const invoicesFor = (customer) => [
    { id: "INV-24142", date: "May 12, 2026", amount: 28400, status: "Open", days: 3, items: 4, ship: "Net 30" },
    { id: "INV-24128", date: "May 02, 2026", amount: 62500, status: "Paid", days: -3, items: 7, ship: "Net 15" },
    { id: "INV-24109", date: "Apr 18, 2026", amount: 14200, status: "Open", days: 21, items: 2, ship: "Net 30" },
    { id: "INV-24094", date: "Apr 03, 2026", amount: 38600, status: "Paid", days: -8, items: 9, ship: "Net 30" },
    { id: "INV-24077", date: "Mar 21, 2026", amount: 22100, status: "Overdue", days: 71, items: 5, ship: "Net 30" },
  ];

  return (
    <div className="pc-page">
      {PeriodComparerEl}

      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Revenue (current period)" value={fmtUSD(rev, { compact: true })} delta={revPrev != null ? deltaPct(rev, revPrev) : null} sub={compareDeltaSub} spark={pl.revenue.slice(-12)} accent="var(--accent)" />
        <KPICard label="Orders"     value={orders}  delta={ordersPrev != null ? deltaPct(orders, ordersPrev) : null}  sub={compareDeltaSub} accent="var(--accent-2)" spark={[212,238,251,265,272,orders]} />
        <KPICard label="Avg order value" value={fmtUSD(aov, { compact: true })} delta={aovPrev != null ? deltaPct(aov, aovPrev) : null} sub={compareDeltaSub} accent="var(--warning)" />
        <KPICard label="Repeat customer %" value="64%" delta={2.8} sub={compareDeltaSub} accent="var(--positive)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1 }}>
          <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 }}>What's moving sales</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              Revenue is on a <b style={{ color: "var(--positive)" }}>3-month uptrend</b>, but composition shifted: <b>Polaris Beacon</b> drove +24% while <b>Meridian Sleeve</b> fell -28%. <b>South region</b> dropped 19% MoM — pipeline coverage there is 0.9x vs. company average of 2.4x. Worth a coverage review this week.
            </div>
          </div>
        </div>
        <button className="pc-btn-mini">Ask why</button>
      </div>

      {/* Trend chart */}
      <Card title="Revenue trend" subtitle="12-month run-rate · with prior year comparison"
            action={
              <SegSmall opts={["Monthly","Weekly","Daily"]} value={trendGran} onChange={setTrendGran} />
            }>
        <AreaChart
          height={240}
          labels={sales.months12.map(m => m.month)}
          series={[
            { name: "This year", values: sales.months12.map(m => m.revenue), color: "var(--accent)" },
            { name: "Prior year", values: sales.months12.map(m => Math.round(m.revenue * (0.78 + Math.random() * 0.1))), color: "var(--text-3)", fill: false, dashed: true },
          ]}
        />
      </Card>

      {/* Breakdown view selector */}
      <div className="pc-section-tabs">
        {[
          { k: "region",  l: "By region" },
          { k: "product", l: "By product" },
          { k: "channel", l: "By channel" },
          { k: "segment", l: "By segment" },
        ].map(t => (
          <button key={t.k} className={view === t.k ? "active" : ""} onClick={() => setView(t.k)}>{t.l}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button className="pc-btn-mini ghost"><Icon d={icons.filter} size={12} /> Filters</button>
        <ExportButton
          rows={view === "region" ? sales.byRegion : view === "product" ? topProducts : []}
          filename={"Sales_by_" + view}
        />
      </div>

      {view === "region" && (
        <Card padding={0}>
          <table className="pc-table">
            <thead>
              <tr>
                <th>Region</th>
                <th style={{ textAlign: "right" }}>Revenue</th>
                <th style={{ textAlign: "right" }} title="Compared to the previous month">vs last month</th>
                <th>Trend (90d)</th>
                <th style={{ textAlign: "right" }}>Customers</th>
                <th style={{ textAlign: "right" }}>Avg order</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {sales.byRegion.map((r, idx) => {
                const trend = Array.from({length: 12}, (_, k) => Math.round(r.revenue/12 * (0.7 + Math.random()*0.6)));
                const delta = deltaPct(r.revenue, r.prev);
                return (
                  <tr key={idx} className="pc-clickable" onClick={() => setDrill({ level: 1, region: r.region, data: regionDetail(r.region) })}>
                    <td style={{ paddingLeft: 14, fontWeight: 500 }}>{r.region}</td>
                    <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500 }}>{fmtUSD(r.revenue)}</td>
                    <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", color: delta >= 0 ? "var(--positive)" : "var(--danger)" }}>{fmtPct(delta)}</td>
                    <td><Sparkline values={trend} color={delta >= 0 ? "var(--positive)" : "var(--danger)"} width={84} height={24} /></td>
                    <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right" }}>{r.customers}</td>
                    <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--text-2)" }}>{fmtUSD(Math.round(r.revenue/r.customers/8))}</td>
                    <td><Icon d={icons.chevron} size={12} stroke="var(--text-3)" /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}

      {view === "product" && (
        <Card padding={0}>
          <table className="pc-table">
            <thead>
              <tr>
                <th>Product</th>
                <th>SKU</th>
                <th style={{ textAlign: "right" }}>Revenue</th>
                <th style={{ textAlign: "right" }}>Units</th>
                <th style={{ textAlign: "right" }}>GM%</th>
                <th style={{ textAlign: "right" }}>Δ MoM</th>
                <th>Velocity</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {topProducts.map((p, idx) => (
                <tr key={idx} className="pc-clickable" onClick={() => setDrill({ level: 1, region: p.name, data: { ...regionDetail("West"), region: p.name, productLabel: p.sku } })}>
                  <td style={{ paddingLeft: 14, fontWeight: 500 }}>{p.name}</td>
                  <td style={{ fontFamily: "ui-monospace, monospace", fontSize: 11.5, color: "var(--text-3)" }}>{p.sku}</td>
                  <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 500 }}>{fmtUSD(p.rev)}</td>
                  <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right" }}>{p.units}</td>
                  <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", color: p.gm >= 60 ? "var(--positive)" : "var(--warning)" }}>{p.gm.toFixed(1)}%</td>
                  <td style={{ fontFamily: "ui-monospace, monospace", textAlign: "right", color: p.delta >= 0 ? "var(--positive)" : "var(--danger)" }}>{fmtPct(p.delta)}</td>
                  <td><VelBar pct={Math.min(p.units / 5, 100)} /></td>
                  <td><Icon d={icons.chevron} size={12} stroke="var(--text-3)" /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {view === "channel" && (
        <div className="pc-grid-2">
          <Card title="Revenue by channel" subtitle="Current month">
            <BarChart
              data={[
                { label: "Direct", value: Math.round(rev * 0.38), color: "var(--accent)" },
                { label: "Wholesale", value: Math.round(rev * 0.28), color: "var(--accent-2)" },
                { label: "Marketplace", value: Math.round(rev * 0.21), color: "var(--positive)" },
                { label: "Reseller", value: Math.round(rev * 0.13), color: "var(--warning)" },
              ]}
              colorFn={(d) => d.color}
              height={220}
            />
          </Card>
          <Card title="Channel performance" subtitle="MoM growth + margin">
            <table className="pc-table compact">
              <thead><tr><th>Channel</th><th style={{textAlign:"right"}}>Revenue</th><th style={{textAlign:"right"}}>Δ MoM</th><th style={{textAlign:"right"}}>GM%</th></tr></thead>
              <tbody>
                {[
                  { c: "Direct (own site)", r: rev*0.38, d: 8.4, gm: 64.2 },
                  { c: "Wholesale", r: rev*0.28, d: 12.1, gm: 38.4 },
                  { c: "Marketplace", r: rev*0.21, d: 2.4, gm: 47.8 },
                  { c: "Reseller", r: rev*0.13, d: -4.6, gm: 52.1 },
                ].map((r,i) => (
                  <tr key={i}><td style={{paddingLeft:14}}>{r.c}</td>
                    <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(r.r,{compact:true})}</td>
                    <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: r.d>=0?"var(--positive)":"var(--danger)"}}>{fmtPct(r.d)}</td>
                    <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{r.gm.toFixed(1)}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      )}

      {view === "segment" && (
        <Card padding={0}>
          <table className="pc-table">
            <thead><tr><th>Segment</th><th style={{textAlign:"right"}}>Revenue</th><th style={{textAlign:"right"}}>Customers</th><th style={{textAlign:"right"}}>Avg ACV</th><th style={{textAlign:"right"}}>GM%</th><th>NRR</th></tr></thead>
            <tbody>
              {[
                { s: "Enterprise", r: rev*0.52, c: 11, gm: 54.2, nrr: 118 },
                { s: "Mid-Market", r: rev*0.34, c: 24, gm: 51.4, nrr: 104 },
                { s: "SMB",        r: rev*0.14, c: 38, gm: 47.8, nrr: 92 },
              ].map((r,i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight: 500}}>{r.s}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(r.r,{compact:true})}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{r.c}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(Math.round(r.r/r.c))}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{r.gm.toFixed(1)}%</td>
                  <td><Bullet value={r.nrr} target={100} max={130} accent={r.nrr >= 100 ? "var(--positive)" : "var(--warning)"} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* Drill modal */}
      {drill && (
        <DrillModal
          trail={
            drill.level === 1 ? [{ label: "Sales analysis" }, { label: drill.region }] :
            drill.level === 2 ? [{ label: "Sales analysis" }, { label: drill.region }, { label: drill.customer.name }] :
                                [{ label: "Sales analysis" }, { label: drill.region }, { label: drill.customer.name }, { label: drill.invoice.id }]
          }
          onClose={() => setDrill(null)}
          onPop={(i) => {
            if (i === 0) setDrill(null);
            else if (i === 1) setDrill({ level: 1, region: drill.region, data: drill.data });
            else if (i === 2) setDrill({ level: 2, region: drill.region, data: drill.data, customer: drill.customer });
          }}
        >
          {drill.level === 1 && <DrillRegionDetail d={drill} onCustomer={(c) => setDrill({ ...drill, level: 2, customer: c })} />}
          {drill.level === 2 && <DrillCustomerDetail d={drill} onInvoice={(inv) => setDrill({ ...drill, level: 3, invoice: inv })} invoices={invoicesFor(drill.customer)} />}
          {drill.level === 3 && <DrillInvoiceDetail d={drill} />}
        </DrillModal>
      )}
    </div>
  );
}

function VelBar({ pct }) {
  return (
    <div style={{ width: 60, height: 4, background: "var(--grid)", borderRadius: 1 }}>
      <div style={{ width: pct + "%", height: "100%", background: "linear-gradient(90deg, var(--warning), var(--accent))", borderRadius: 1 }} />
    </div>
  );
}

// ── Drill level 1: Region/product detail ────────────────────────────────
function DrillRegionDetail({ d, onCustomer }) {
  const dt = d.data;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
        <div>
          <h2 style={{ fontSize: 22, fontWeight: 600, margin: 0, marginBottom: 4 }}>{d.region}</h2>
          <div style={{ fontSize: 12, color: "var(--text-3)" }}>
            {dt.customers?.length || 0} active customers · {dt.productMix?.length || 6} product lines
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontSize: 26, fontFamily: "ui-monospace, monospace", fontWeight: 600 }}>{fmtUSD(dt.revenue || 380000, { compact: true })}</div>
          <div style={{ fontSize: 11, color: dt.revenue >= dt.prev ? "var(--positive)" : "var(--danger)" }}>
            {fmtPct(deltaPct(dt.revenue, dt.prev || dt.revenue))} vs. last month
          </div>
        </div>
      </div>

      <div className="pc-grid-2" style={{ gap: 16, marginBottom: 16 }}>
        <div className="pc-card-inner">
          <div className="pc-card-title" style={{ marginBottom: 12 }}>Revenue by product</div>
          <BarChart
            data={(dt.productMix || []).map((p, i) => ({ label: p.sku, value: p.rev, color: ["var(--accent)","var(--accent-2)","var(--positive)","var(--warning)","#8b5cf6","#ec4899"][i % 6] }))}
            colorFn={(d) => d.color}
            height={140}
            yFmt={(v) => fmtUSD(v, { compact: true })}
          />
        </div>
        <div className="pc-card-inner">
          <div className="pc-card-title" style={{ marginBottom: 12 }}>14-day trend</div>
          <AreaChart
            height={150}
            labels={Array.from({length: 14}, (_, i) => i % 2 === 0 ? (14 - i) + "d" : "")}
            series={[{ name: "Daily revenue", values: Array.from({length: 14}, () => Math.round(12000 + Math.random()*8000)), color: "var(--accent)" }]}
            legend={false}
          />
        </div>
      </div>

      <div className="pc-card-inner" style={{ padding: 0 }}>
        <div style={{ padding: "12px 14px", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--border)" }}>
          <div className="pc-card-title">Customers in {d.region}</div>
          <span style={{ fontSize: 11, color: "var(--text-3)" }}>Click a customer for invoice-level detail</span>
        </div>
        <table className="pc-table compact">
          <thead><tr><th>Customer</th><th>Segment</th><th style={{textAlign:"right"}}>Revenue</th><th style={{textAlign:"right"}}>Invoices</th><th>Since</th><th></th></tr></thead>
          <tbody>
            {(dt.customers || []).map((c, i) => (
              <tr key={i} className="pc-clickable" onClick={() => onCustomer(c)}>
                <td style={{paddingLeft:14, fontWeight:500}}>{c.name}</td>
                <td><span className="pc-chip">{c.segment}</span></td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(c.rev)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{c.invoices}</td>
                <td style={{color:"var(--text-3)", fontSize: 11.5}}>{c.since}</td>
                <td><Icon d={icons.chevron} size={11} stroke="var(--text-3)" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <AIInsight>
        <b>{d.region}</b> revenue is <b>{deltaPct(dt.revenue, dt.prev) >= 0 ? "up" : "down"} {Math.abs(deltaPct(dt.revenue, dt.prev)).toFixed(1)}%</b> MoM, primarily driven by {dt.productMix?.[0]?.name || "Aurelius Pro Kit"}. <b>2 customers</b> haven't ordered in 60+ days vs. their typical pattern — flagged for outreach.
      </AIInsight>
    </div>
  );
}

// ── Drill level 2: Customer detail ──────────────────────────────────────
function DrillCustomerDetail({ d, onInvoice, invoices }) {
  const c = d.customer;
  const totalRev = invoices.reduce((s, i) => s + i.amount, 0);

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
        <div>
          <h2 style={{ fontSize: 22, fontWeight: 600, margin: 0, marginBottom: 4 }}>{c.name}</h2>
          <div style={{ fontSize: 12, color: "var(--text-3)", display: "flex", gap: 12, alignItems: "center" }}>
            <span className="pc-chip">{c.segment}</span>
            <span>{c.region} · Customer since {c.since}</span>
            <span>·</span>
            <span>{c.id}</span>
          </div>
        </div>
        <button className="pc-btn-mini ghost">View customer profile</button>
      </div>

      <div className="pc-kpi-grid pc-kpi-grid-4" style={{ marginBottom: 16 }}>
        <MiniKPI label="LTM revenue"     value={fmtUSD(totalRev)} delta={8.4} />
        <MiniKPI label="Open AR"         value={fmtUSD(invoices.filter(i => i.status !== "Paid").reduce((s,i)=>s+i.amount, 0))} accent="var(--warning)" />
        <MiniKPI label="Avg days to pay" value="34d" delta={-2.1} />
        <MiniKPI label="Margin"          value="56%" delta={-1.4} />
      </div>

      <div className="pc-card-inner" style={{ padding: 0, marginBottom: 16 }}>
        <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border)" }}>
          <div className="pc-card-title">Invoice history</div>
        </div>
        <table className="pc-table compact">
          <thead><tr><th>Invoice</th><th>Date</th><th style={{textAlign:"right"}}>Amount</th><th>Status</th><th>Days to pay</th><th>Items</th><th>Terms</th><th></th></tr></thead>
          <tbody>
            {invoices.map((inv, i) => (
              <tr key={i} className="pc-clickable" onClick={() => onInvoice(inv)}>
                <td style={{paddingLeft:14, fontFamily: "ui-monospace, monospace", fontSize: 11.5, fontWeight: 500}}>{inv.id}</td>
                <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{inv.date}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 500}}>{fmtUSD(inv.amount)}</td>
                <td><StatusPill s={inv.status} /></td>
                <td style={{fontFamily:"ui-monospace, monospace", fontSize: 11.5, color: inv.days > 30 ? "var(--danger)" : "var(--text-2)"}}>{inv.days < 0 ? Math.abs(inv.days) + "d before" : inv.days + "d"}</td>
                <td style={{fontFamily:"ui-monospace, monospace", fontSize: 11.5, color: "var(--text-3)"}}>{inv.items}</td>
                <td style={{fontSize: 11, color: "var(--text-3)"}}>{inv.ship}</td>
                <td><Icon d={icons.chevron} size={11} stroke="var(--text-3)" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <AIInsight>
        {c.name}'s pay rhythm is <b>34 days on average</b>. The 71-day invoice (INV-24077) is a 2.7-sigma anomaly — typical drivers are PO mismatch, internal approval delay, or a dispute. Recommend a check-in call before escalating to formal collections.
      </AIInsight>
    </div>
  );
}

function StatusPill({ s }) {
  const map = {
    Paid:    { c: "var(--positive)", b: "rgba(110,231,183,0.10)" },
    Open:    { c: "var(--accent-2)", b: "rgba(99,102,241,0.10)" },
    Overdue: { c: "var(--danger)", b: "rgba(248,113,113,0.10)" },
  };
  const m = map[s] || map.Open;
  return <span className="pc-statpill" style={{ color: m.c, background: m.b }}>{s}</span>;
}

function MiniKPI({ label, value, delta, accent = "var(--accent)" }) {
  return (
    <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--grid)", borderRadius: 6, padding: 12 }}>
      <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 600, fontFamily: "ui-monospace, monospace", marginTop: 4 }}>{value}</div>
      {delta !== undefined && (
        <div style={{ fontSize: 11, color: delta >= 0 ? "var(--positive)" : "var(--danger)", marginTop: 2 }}>
          {fmtPct(delta)} vs last month
        </div>
      )}
    </div>
  );
}

// ── Drill level 3: Invoice detail ────────────────────────────────────────
function DrillInvoiceDetail({ d }) {
  const inv = d.invoice;
  const lineItems = [
    { sku: "AUR-100", name: "Aurelius Pro Kit", qty: 4, unit: 1495, ext: 5980 },
    { sku: "ORI-220", name: "Orion Module 4U",  qty: 8, unit: 612,  ext: 4896 },
    { sku: "VEL-310", name: "Vela Cable Loom",  qty: 24, unit: 88,  ext: 2112 },
    { sku: "POL-551", name: "Polaris Mount",    qty: 12, unit: 245, ext: 2940 },
  ];
  const subtotal = lineItems.reduce((s, l) => s + l.ext, 0);
  const tax = Math.round(subtotal * 0.0825);
  const shipping = 380;

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>Invoice</div>
          <h2 style={{ fontSize: 22, fontWeight: 600, margin: 0, fontFamily: "ui-monospace, monospace" }}>{inv.id}</h2>
          <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>
            Issued {inv.date} · Terms {inv.ship} · Customer {d.customer.name}
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <StatusPill s={inv.status} />
          <div style={{ fontSize: 28, fontWeight: 600, fontFamily: "ui-monospace, monospace", marginTop: 6 }}>{fmtUSD(inv.amount)}</div>
        </div>
      </div>

      <div className="pc-card-inner" style={{ padding: 0, marginBottom: 16 }}>
        <table className="pc-table compact">
          <thead><tr><th>SKU</th><th>Product</th><th style={{textAlign:"right"}}>Qty</th><th style={{textAlign:"right"}}>Unit</th><th style={{textAlign:"right"}}>Extended</th></tr></thead>
          <tbody>
            {lineItems.map((l, i) => (
              <tr key={i}>
                <td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5, color: "var(--text-2)"}}>{l.sku}</td>
                <td>{l.name}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{l.qty}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(l.unit)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight:500}}>{fmtUSD(l.ext)}</td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr><td colSpan={4} style={{textAlign:"right", paddingRight: 14, color: "var(--text-3)"}}>Subtotal</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(subtotal)}</td></tr>
            <tr><td colSpan={4} style={{textAlign:"right", paddingRight: 14, color: "var(--text-3)"}}>Tax (8.25%)</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(tax)}</td></tr>
            <tr><td colSpan={4} style={{textAlign:"right", paddingRight: 14, color: "var(--text-3)"}}>Shipping</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(shipping)}</td></tr>
            <tr><td colSpan={4} style={{textAlign:"right", paddingRight: 14, fontWeight:600, color: "var(--text)"}}>Total</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 600, color: "var(--accent)"}}>{fmtUSD(subtotal + tax + shipping)}</td></tr>
          </tfoot>
        </table>
      </div>

      <div className="pc-grid-2" style={{ gap: 16 }}>
        <div className="pc-card-inner">
          <div className="pc-card-title" style={{ marginBottom: 12 }}>Margin contribution</div>
          <table className="pc-table compact">
            <tbody>
              <tr><td style={{paddingLeft:14}}>Revenue</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(inv.amount)}</td></tr>
              <tr><td style={{paddingLeft:14, color: "var(--text-3)"}}>Cost of goods</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-2)"}}>({fmtUSD(Math.round(inv.amount * 0.42))})</td></tr>
              <tr><td style={{paddingLeft:14, color: "var(--text-3)"}}>Picking + ship</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-2)"}}>({fmtUSD(180)})</td></tr>
              <tr><td style={{paddingLeft:14, fontWeight: 500}}>Gross profit</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--positive)", fontWeight: 500}}>{fmtUSD(Math.round(inv.amount * 0.58 - 180))}</td></tr>
              <tr><td style={{paddingLeft:14, color: "var(--text-3)"}}>GM %</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--positive)"}}>57.8%</td></tr>
            </tbody>
          </table>
        </div>
        <div className="pc-card-inner">
          <div className="pc-card-title" style={{ marginBottom: 12 }}>GL postings</div>
          <table className="pc-table compact">
            <thead><tr><th>Account</th><th style={{textAlign:"right"}}>Debit</th><th style={{textAlign:"right"}}>Credit</th></tr></thead>
            <tbody>
              <tr><td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5}}>1100 AR</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(inv.amount)}</td><td></td></tr>
              <tr><td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5}}>4000 Revenue</td><td></td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(subtotal)}</td></tr>
              <tr><td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5}}>2200 Sales Tax</td><td></td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(tax)}</td></tr>
              <tr><td style={{paddingLeft:14, fontFamily:"ui-monospace, monospace", fontSize: 11.5}}>4090 Shipping Rev</td><td></td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(shipping)}</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// CUSTOMER PROFITABILITY
// ────────────────────────────────────────────────────────────────────────
function CustomerProfitPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { profit } = data;
  const { PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);
  const [sortBy, setSortBy] = useStateR("netProfit");
  const [filter, setFilter] = useStateR("all");

  const filtered = profit.filter(c => filter === "all" || c.segment.toLowerCase() === filter.toLowerCase());
  const sorted = [...filtered].sort((a, b) => b[sortBy] - a[sortBy]);
  const totalNet = profit.reduce((s, c) => s + c.netProfit, 0);
  const totalRev = profit.reduce((s, c) => s + c.revenue, 0);

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Total customers"     value={profit.length} accent="var(--accent)" />
        <KPICard label="Total revenue (LTM)" value={fmtUSD(totalRev, { compact: true })} accent="var(--accent)" />
        <KPICard label="Net profit (LTM)"    value={fmtUSD(totalNet, { compact: true })} sub={`${(totalNet/totalRev*100).toFixed(1)}% net margin`} accent="var(--positive)" />
        <KPICard label="Unprofitable customers" value={profit.filter(c => c.netProfit < 0).length} hint="Net of support cost" accent="var(--danger)" />
      </div>

      <div className="pc-grid-2-1">
        <Card title="Profit concentration" subtitle="Top 5 customers contribute X% of net profit">
          <BarChart
            data={sorted.slice(0, 10).map((c, i) => ({ label: c.name.slice(0, 9), value: c.netProfit, color: c.netProfit < 0 ? "var(--danger)" : i < 3 ? "var(--accent)" : "var(--accent-2)" }))}
            colorFn={(d) => d.color}
            height={220}
          />
        </Card>
        <Card title="By segment" subtitle="Net margin">
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {["Enterprise", "Mid-Market", "SMB"].map(seg => {
              const segs = profit.filter(c => c.segment === seg);
              const rev = segs.reduce((s, c) => s + c.revenue, 0);
              const net = segs.reduce((s, c) => s + c.netProfit, 0);
              const margin = (net / rev * 100);
              return (
                <div key={seg}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 6 }}>
                    <span style={{ fontWeight: 500 }}>{seg}</span>
                    <span style={{ fontFamily: "ui-monospace, monospace", color: margin >= 20 ? "var(--positive)" : "var(--warning)" }}>{margin.toFixed(1)}%</span>
                  </div>
                  <Bullet value={margin} target={20} max={45} accent={margin >= 20 ? "var(--positive)" : "var(--warning)"} />
                  <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 4 }}>
                    {segs.length} customers · {fmtUSD(rev, { compact: true })} revenue · {fmtUSD(net, { compact: true })} net
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      <Card title="Customer profitability ranking" subtitle="LTM (Last twelve months)"
            action={
              <div style={{ display: "flex", gap: 8 }}>
                <div className="pc-seg-sm">
                  {["all","enterprise","mid-market","smb"].map(s =>
                    <button key={s} className={filter === s ? "active" : ""} onClick={() => setFilter(s)}>{s === "all" ? "All" : s[0].toUpperCase() + s.slice(1)}</button>
                  )}
                </div>
                <ExportButton rows={sorted} filename="Customer_profitability" />
              </div>
            } padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>#</th>
              <th>Customer</th>
              <th>Segment</th>
              <th onClick={() => setSortBy("revenue")} style={{textAlign:"right", cursor:"pointer"}}>Revenue ↓</th>
              <th onClick={() => setSortBy("gpPct")} style={{textAlign:"right", cursor:"pointer"}}>GM%</th>
              <th onClick={() => setSortBy("supportCost")} style={{textAlign:"right", cursor:"pointer"}}>Support</th>
              <th onClick={() => setSortBy("netProfit")} style={{textAlign:"right", cursor:"pointer"}}>Net profit</th>
              <th style={{textAlign:"right"}}>Net %</th>
              <th>Last order</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((c, i) => (
              <tr key={c.id} className={c.netProfit < 0 ? "pc-row-danger" : ""}>
                <td style={{paddingLeft:14, color:"var(--text-3)", fontFamily:"ui-monospace, monospace", fontSize: 11.5}}>{i+1}</td>
                <td style={{fontWeight: 500}}>{c.name}</td>
                <td><span className="pc-chip">{c.segment}</span></td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(c.revenue)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{c.gpPct}%</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color:"var(--text-3)"}}>{fmtUSD(c.supportCost)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight:500, color: c.netProfit < 0 ? "var(--danger)" : "var(--positive)"}}>{fmtUSD(c.netProfit)}</td>
                <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: c.netMargin >= 20 ? "var(--positive)" : c.netMargin >= 10 ? "var(--warning)" : "var(--danger)"}}>{c.netMargin}%</td>
                <td style={{fontSize:11, color:"var(--text-3)"}}>{c.lastOrder}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// MARGIN ANALYTICS
// ────────────────────────────────────────────────────────────────────────
function MarginPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { pl } = data;
  const { curIdx, cmpIdx, sumAt, compareTo, cmpLbl, compareDeltaSub, PeriodComparerEl } = window.usePeriod(globalPeriod, setGlobalPeriod);

  const months = pl.labels;
  const gmPct = pl.gp.map((g, i) => g / pl.revenue[i] * 100);

  const curGm = sumAt(pl.gp, curIdx) / sumAt(pl.revenue, curIdx) * 100;
  const cmpGm = compareTo === "none" ? null : sumAt(pl.gp, cmpIdx) / sumAt(pl.revenue, cmpIdx) * 100;
  const t6 = pl.gp.slice(-6).reduce((s,v)=>s+v,0) / pl.revenue.slice(-6).reduce((s,v)=>s+v,0) * 100;

  return (
    <div className="pc-page">
      {PeriodComparerEl}

      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Gross margin (current)" value={curGm.toFixed(1) + "%"} delta={cmpGm != null ? curGm - cmpGm : null} sub={cmpGm != null ? "pp vs " + cmpLbl : "—"} accent="var(--accent)" />
        <KPICard label="Trailing 6mo GM%"       value={t6.toFixed(1) + "%"} accent="var(--accent)" />
        <KPICard label="Margin exceptions"      value={3} hint="Open this month" accent="var(--warning)" />
        <KPICard label="Margin variance"        value="±2.8 pp" hint="Std deviation 12mo" accent="var(--accent-2)" />
      </div>

      <Card title="Gross margin bridge" subtitle="Last month → this month · price/cost/mix decomposition">
        <MarginBridge />
        <AIInsight>
          GM compression of <b>1.8 pp</b> is <b>92% cost-driven</b> (not price or mix). The dominant driver is <b>Aurelius Pro Kit</b> input cost +9% on lots received after Apr 18. If you pass through 4% of that to wholesale customers (still below MSRP gap), you'd recover <b>1.2 pp</b> of the compression.
        </AIInsight>
      </Card>

      <div className="pc-grid-2">
        <Card title="GM% by product line" subtitle="Trailing 30 days">
          <table className="pc-table compact">
            <thead><tr><th>Line</th><th style={{textAlign:"right"}}>Revenue</th><th>GM%</th><th style={{textAlign:"right"}}>Δ vs avg</th></tr></thead>
            <tbody>
              {[
                { l: "Premium",   r: 552400, gm: 60.2, d: -2.1 },
                { l: "Core",      r: 269600, gm: 58.1, d: 0.4 },
                { l: "Accessory", r: 130200, gm: 72.4, d: 1.2 },
                { l: "Soft Goods", r: 28100, gm: 65.4, d: -1.8 },
                { l: "Legacy",    r: 12200, gm: 38.4, d: -6.4 },
              ].map((r,i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14}}>{r.l}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(r.r, {compact: true})}</td>
                  <td><Bullet value={r.gm} target={55} max={80} accent={r.gm >= 55 ? "var(--positive)" : "var(--warning)"} /></td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: r.d >= 0 ? "var(--positive)" : "var(--danger)"}}>{r.d >= 0 ? "+" : ""}{r.d.toFixed(1)} pp</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="GM% trend · 12 months">
          <AreaChart
            height={260}
            labels={months}
            yFmt={(v) => v.toFixed(0) + "%"}
            series={[
              { name: "Actual",  values: gmPct, color: "var(--accent)" },
              { name: "Target",  values: gmPct.map(() => 56), color: "var(--positive)", fill: false, dashed: true },
            ]}
          />
        </Card>
      </div>
    </div>
  );
}

function MarginBridge() {
  // Waterfall-style bridge
  const items = [
    { label: "Last month GM%", value: 57.2, type: "start" },
    { label: "Price",          value: -0.4, type: "negative" },
    { label: "Volume mix",     value: 0.2,  type: "positive" },
    { label: "Product mix",    value: -0.2, type: "negative" },
    { label: "Input cost",     value: -1.6, type: "negative" },
    { label: "Freight",        value: 0.0,  type: "neutral" },
    { label: "This month GM%", value: 55.2, type: "end" },
  ];
  const max = 60;
  const min = 50;
  const range = max - min;
  let running = items[0].value;

  return (
    <div style={{ position: "relative", height: 200, padding: "16px 8px 28px", display: "flex", alignItems: "flex-end", justifyContent: "space-around" }}>
      {items.map((it, i) => {
        let h, bottom, color, top, label;
        if (it.type === "start" || it.type === "end") {
          h = ((it.value - min) / range) * 160;
          bottom = 28;
          color = it.type === "start" ? "var(--text-3)" : "var(--accent)";
          top = it.value;
          label = it.value.toFixed(1) + "%";
        } else {
          h = Math.abs(it.value) / range * 160;
          if (it.value >= 0) {
            bottom = ((running - min) / range) * 160 + 28;
          } else {
            bottom = ((running + it.value - min) / range) * 160 + 28;
          }
          color = it.value > 0 ? "var(--positive)" : it.value < 0 ? "var(--danger)" : "var(--text-4)";
          top = running;
          label = (it.value > 0 ? "+" : "") + it.value.toFixed(1) + " pp";
          running += it.value;
        }
        return (
          <div key={i} style={{ position: "relative", flex: 1, height: "100%" }}>
            <div style={{
              position: "absolute", left: "20%", right: "20%",
              height: Math.max(h, 2), bottom,
              background: color, borderRadius: 2,
            }} />
            <div style={{
              position: "absolute", bottom: bottom + Math.max(h, 2) + 4, left: 0, right: 0,
              textAlign: "center", fontSize: 11, fontFamily: "ui-monospace, monospace",
              color: it.type === "start" || it.type === "end" ? "var(--text)" : color,
            }}>
              {label}
            </div>
            <div style={{
              position: "absolute", bottom: 6, left: 0, right: 0,
              textAlign: "center", fontSize: 10.5, color: "var(--text-3)",
            }}>
              {it.label}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { SalesPage, CustomerProfitPage, MarginPage, MiniKPI, StatusPill });
