// Blueprint-aligned strategic pages (Sections 12, 14.5, 15, 24, 25)
// One-Page Health View · 13-Week Cash Forecast · Capital Allocation · Goal Tracking · Customer Acquisition

const { useState: useStateBP, useMemo: useMemoBP, useEffect: useEffectBP } = React;

// ────────────────────────────────────────────────────────────────────────
// ONE-PAGE HEALTH VIEW (Blueprint §12.1)
// "The single screen the owner opens every morning. Answers: are we healthy right now?"
// 6 tiles + top 3 open anomalies, refreshed hourly for cash / daily for the rest.
// ────────────────────────────────────────────────────────────────────────
function HealthPage({ data, bizType, setPage, period: globalPeriod, setPeriod: setGlobalPeriod, companyProfile }) {
  const { pl, cash, exceptions } = data;
  const { curIdx, cmpIdx, sumAt, period, 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 opex   = sumAt(pl.opex, curIdx);
  const ebitda = sumAt(pl.ebitda, curIdx);

  const revPrior  = sumAt(pl.revenue, cmpIdx);
  const gpPrior   = sumAt(pl.gp, cmpIdx);
  const revBudget = Math.round(rev * 0.96);
  const gpPct = rev > 0 ? (gp / rev) * 100 : 0;
  const gpPctPrior = revPrior > 0 ? (gpPrior / revPrior) * 100 : gpPct;
  const ebitdaPct = rev > 0 ? (ebitda / rev) * 100 : 0;
  const runwayWeeks = Math.min(Math.round(cash.runwayDays / 7), 99);

  // Tile config — locked to blueprint
  const tiles = [
    {
      label: "Revenue · " + periodLabel,
      value: fmtUSD(rev, { compact: true }),
      cmpBudget: revBudget, cmpPrior: revPrior, current: rev,
      sentiment: rev >= revBudget ? "good" : "bad",
      explain: rev >= revBudget
        ? "Tracking " + (((rev / revBudget) - 1) * 100).toFixed(1) + "% ahead of plan."
        : "Tracking " + (((revBudget - rev) / revBudget) * 100).toFixed(1) + "% behind plan.",
      drill: "overview",
    },
    {
      label: "Gross margin",
      value: gpPct.toFixed(1) + "%",
      delta: gpPct - gpPctPrior, unit: "pp",
      sentiment: gpPct >= gpPctPrior ? "good" : "bad",
      explain: gpPct < gpPctPrior
        ? "Margin compressed " + (gpPctPrior - gpPct).toFixed(1) + " pp — input costs the main driver."
        : "Margin expanded " + (gpPct - gpPctPrior).toFixed(1) + " pp vs. prior period.",
      drill: "margin",
    },
    {
      label: "EBITDA · " + periodLabel,
      value: fmtUSD(ebitda, { compact: true }),
      sub: ebitdaPct.toFixed(1) + "% margin",
      delta: -3.2, unit: "pp",
      sentiment: ebitda > 0 ? (ebitdaPct >= 25 ? "good" : "warn") : "bad",
      explain: "Operating profit before depreciation, tax, and interest.",
      drill: "overview",
    },
    {
      label: "Cash on hand",
      value: fmtUSD(cash.startCash, { compact: true }),
      sub: "across all accounts",
      sentiment: "good",
      explain: "Liquid + restricted. Hourly refresh.",
      drill: "cash",
    },
    {
      label: "13-week runway",
      value: runwayWeeks >= 52 ? "12+ months" : runwayWeeks + " weeks",
      sentiment: runwayWeeks >= 26 ? "good" : runwayWeeks >= 13 ? "warn" : "bad",
      explain: runwayWeeks >= 26
        ? "Comfortable. Stress-tested through 20% revenue decline."
        : "Compressing — open the 13-week forecast and review weekly pinch points.",
      drill: "cash",
    },
    {
      label: "Open anomalies",
      value: exceptions.length,
      sub: exceptions.filter(e => e.sev === "critical").length + " critical · " + exceptions.filter(e => e.sev === "high").length + " high",
      sentiment: exceptions.filter(e => e.sev === "critical").length > 0 ? "bad" : exceptions.length > 5 ? "warn" : "good",
      explain: exceptions.filter(e => e.sev === "critical").length > 0
        ? "Critical exceptions present — review the inbox now."
        : "No critical items. Routine maintenance only.",
      drill: "exceptions",
    },
  ];

  // Daily briefing — plain-language summary (one-paragraph CFO narrative)
  const briefing = `${periodLabel} revenue is ${rev >= revBudget ? "ahead" : "behind"} plan by ${Math.abs(((rev / revBudget) - 1) * 100).toFixed(1)}%, with ${revBudget < revPrior ? "softer" : "healthier"} trajectory vs. prior period. Gross margin at ${gpPct.toFixed(1)}% — ${gpPct < gpPctPrior ? "compressed " + (gpPctPrior - gpPct).toFixed(1) + " pp" : "expanded " + (gpPct - gpPctPrior).toFixed(1) + " pp"} vs prior period. Cash position is healthy at ${fmtUSD(cash.startCash, {compact:true})} with ${runwayWeeks >= 52 ? "12+ months" : runwayWeeks + " weeks"} of runway under base case. ${exceptions.length} open anomalies, ${exceptions.filter(e => e.sev === "critical").length} critical.`;

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      {/* Hero — date + briefing */}
      <Card padding={28} style={{ background: "linear-gradient(135deg, rgba(110,231,183,0.05), rgba(99,102,241,0.04))", borderColor: "rgba(110,231,183,0.18)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 24, flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 320 }}>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>{new Date().toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" })}</div>
            <h1 style={{ fontSize: 32, fontFamily: "'Instrument Serif', serif", fontWeight: 400, margin: 0, lineHeight: 1.15 }}>Good morning{companyProfile?.owner_name ? `, ${companyProfile.owner_name.split(" ")[0]}` : ""}{!companyProfile?.owner_name && companyProfile?.name ? ` — ${companyProfile.name}` : ""}.</h1>
            <div style={{ fontSize: 14, color: "var(--text-2)", marginTop: 12, lineHeight: 1.6, maxWidth: 760 }}>
              {briefing}
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="pc-btn-mini ghost"><Icon d={icons.download} size={12} /> Email digest</button>
              <button className="pc-btn-mini ghost"><Icon d={icons.download} size={12} /> Board pack</button>
            </div>
            <div style={{ fontSize: 10.5, color: "var(--text-3)", marginTop: 6 }}>Cash · synced 4m ago · GL · synced 12m ago</div>
          </div>
        </div>
      </Card>

      {/* The 6 tiles — blueprint-mandated */}
      <div className="pc-health-grid">
        {tiles.map((t, idx) => (
          <HealthTile key={idx} {...t} onClick={() => setPage && setPage(t.drill)} />
        ))}
      </div>

      {/* Top 3 anomalies inline + drill */}
      <Card title="Top 3 things to look at today" subtitle="Auto-ranked by $ impact × urgency · drill to act"
            action={<button className="pc-btn-mini ghost" onClick={() => setPage && setPage("exceptions")}>Open inbox →</button>}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {exceptions.slice(0, 3).map((ex, idx) => (
            <div key={ex.id} className="pc-health-anomaly">
              <div className="pc-health-anomaly-num" data-sev={ex.sev}>{idx + 1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4 }}>{ex.title}</div>
                <div style={{ fontSize: 12.5, color: "var(--text-2)", marginTop: 4, lineHeight: 1.5 }}>{ex.detail}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 6 }}>
                  Suggested: <b style={{ color: "var(--text-2)" }}>{ex.ai}</b>
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end" }}>
                <SevPill sev={ex.sev} />
                <button className="pc-btn-mini" onClick={() => setPage && setPage("exceptions")}>Drill ›</button>
              </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function HealthTile({ label, value, sub, delta, unit, cmpBudget, cmpPrior, current, sentiment, explain, onClick }) {
  const dot = { good: "var(--positive)", warn: "var(--warning)", bad: "var(--danger)" }[sentiment] || "var(--text-3)";
  return (
    <div className="pc-health-tile" onClick={onClick}>
      <div className="pc-health-tile-hd">
        <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5, fontWeight: 500 }}>{label}</div>
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: dot, boxShadow: "0 0 8px " + dot }} />
      </div>
      <div className="pc-health-tile-v">{value}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{sub}</div>}
      {(delta !== undefined || cmpBudget !== undefined) && (
        <div style={{ display: "flex", gap: 10, marginTop: 8, fontSize: 11.5, fontFamily: "ui-monospace, monospace" }}>
          {delta !== undefined && (
            <span style={{ color: delta >= 0 ? "var(--positive)" : "var(--danger)" }}>{delta >= 0 ? "▲" : "▼"} {Math.abs(delta).toFixed(1)}{unit ? " " + unit : "%"}</span>
          )}
          {cmpBudget !== undefined && (
            <span style={{ color: current >= cmpBudget ? "var(--positive)" : "var(--danger)" }}>
              vs plan {current >= cmpBudget ? "+" : ""}{(((current - cmpBudget) / cmpBudget) * 100).toFixed(1)}%
            </span>
          )}
          {cmpPrior !== undefined && (
            <span style={{ color: "var(--text-3)" }}>
              vs last year {current >= cmpPrior ? "+" : ""}{(((current - cmpPrior) / cmpPrior) * 100).toFixed(1)}%
            </span>
          )}
        </div>
      )}
      <div style={{ fontSize: 11.5, color: "var(--text-2)", marginTop: 12, lineHeight: 1.5 }}>{explain}</div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// 13-WEEK CASH FORECAST (Blueprint §12.2 + §14.5 stress test)
// "When do we run out, and what is the next pinch point?"
// ────────────────────────────────────────────────────────────────────────
function ThirteenWeekCash({ data }) {
  const [scenario, setScenario] = useStateBP("base"); // base | rev_10 | rev_20 | rev_30
  // Build 13-week table from cash.proj (90 days)
  const weeks = [];
  let opening = data.cash.startCash;
  for (let w = 0; w < 13; w++) {
    const baseInflows = 184000 + Math.round(Math.sin(w / 2) * 22000) + (w % 4 === 0 ? 32000 : 0);
    const basePayroll = w % 2 === 0 ? 92000 : 0; // biweekly
    const baseRent = w % 4 === 0 ? 38500 : 0;
    const baseAP = 38000 + (w % 3 === 0 ? 22000 : 0);
    const baseOther = 12000 + (w % 4 === 0 ? 42000 : 0); // tax cycle quarterly
    // Scenario adjustments
    const revMult = scenario === "rev_10" ? 0.9 : scenario === "rev_20" ? 0.8 : scenario === "rev_30" ? 0.7 : 1.0;
    const inflows = Math.round(baseInflows * revMult);
    const outflows = basePayroll + baseRent + baseAP + baseOther;
    const net = inflows - outflows;
    const closing = opening + net;
    // Risk band
    const monthlyBurn = 380000;
    let risk;
    if (closing < monthlyBurn) risk = "red";
    else if (closing < monthlyBurn * 1.5) risk = "yellow";
    else risk = "green";
    weeks.push({ week: "W" + (20 + w), opening, inflows, payroll: basePayroll, rent: baseRent, ap: baseAP, other: baseOther, outflows, net, closing, risk });
    opening = closing;
  }
  const minClosing = Math.min(...weeks.map(w => w.closing));
  const minWeek = weeks.find(w => w.closing === minClosing);

  return (
    <Card title="13-week cash forecast" subtitle="Weekly direct-method projection · risk-banded by minimum cash floor"
          action={
            <div style={{ display: "flex", gap: 8 }}>
              <div className="pc-seg-sm">
                {[
                  { v: "base",    l: "Base" },
                  { v: "rev_10",  l: "−10% rev" },
                  { v: "rev_20",  l: "−20% rev" },
                  { v: "rev_30",  l: "−30% rev" },
                ].map(s => <button key={s.v} className={scenario === s.v ? "active" : ""} onClick={() => setScenario(s.v)}>{s.l}</button>)}
              </div>
              <ExportButton rows={weeks} filename="13_week_cash" />
            </div>
          } padding={0}>
      <table className="pc-table">
        <thead>
          <tr>
            <th>Week</th>
            <th style={{textAlign:"right"}}>Opening</th>
            <th style={{textAlign:"right"}}>Inflows</th>
            <th style={{textAlign:"right"}}>Payroll</th>
            <th style={{textAlign:"right"}}>Rent</th>
            <th style={{textAlign:"right"}}>AP</th>
            <th style={{textAlign:"right"}}>Other</th>
            <th style={{textAlign:"right"}}>Net</th>
            <th style={{textAlign:"right"}}>Closing</th>
            <th>Risk</th>
          </tr>
        </thead>
        <tbody>
          {weeks.map((w, idx) => (
            <tr key={idx} className={w.risk === "red" ? "pc-row-danger" : ""}>
              <td style={{paddingLeft:14, fontFamily: "ui-monospace, monospace", fontSize: 11.5, fontWeight: 500}}>{w.week}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-3)"}}>{fmtUSD(w.opening, { compact: true })}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--positive)"}}>+{fmtUSD(w.inflows, { compact: true })}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: w.payroll > 0 ? "var(--text-2)" : "var(--text-4)"}}>{w.payroll > 0 ? "−" + fmtUSD(w.payroll, {compact:true}) : "—"}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: w.rent > 0 ? "var(--text-2)" : "var(--text-4)"}}>{w.rent > 0 ? "−" + fmtUSD(w.rent, {compact:true}) : "—"}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-2)"}}>−{fmtUSD(w.ap, { compact: true })}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-2)"}}>−{fmtUSD(w.other, { compact: true })}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: w.net >= 0 ? "var(--positive)" : "var(--danger)"}}>{w.net >= 0 ? "+" : "−"}{fmtUSD(Math.abs(w.net), { compact: true })}</td>
              <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 600}}>{fmtUSD(w.closing, { compact: true })}</td>
              <td><span className="pc-risk-pill" style={{
                background: w.risk === "red" ? "rgba(248,113,113,0.10)" : w.risk === "yellow" ? "rgba(251,191,36,0.10)" : "rgba(110,231,183,0.10)",
                color: w.risk === "red" ? "var(--danger)" : w.risk === "yellow" ? "var(--warning)" : "var(--positive)",
              }}>{w.risk === "red" ? "Tight" : w.risk === "yellow" ? "Watch" : "Healthy"}</span></td>
            </tr>
          ))}
        </tbody>
      </table>
      <div style={{ padding: "14px 18px", borderTop: "1px solid var(--border)" }}>
        <AIInsight>
          {scenario === "base"
            ? <>Under base case, the tightest week is <b>{minWeek.week}</b> at <b>{fmtUSD(minClosing, { compact: true })}</b> closing. All 13 weeks stay above the 1× monthly-burn floor.</>
            : <>Under <b>{scenario.replace("rev_", "−").replace("_", " ")} revenue stress</b>, the tightest week is <b>{minWeek.week}</b> at <b>{fmtUSD(minClosing, { compact: true })}</b>. {minClosing < 380000 ? <span style={{color: "var(--danger)"}}>Cash falls below the 1× monthly-burn floor — initiate the revolver draw or accelerate Atlas collections this week.</span> : "Cash remains above the safety floor. No action required."}</>}
        </AIInsight>
      </div>
    </Card>
  );
}

// ────────────────────────────────────────────────────────────────────────
// CAPITAL ALLOCATION VIEW (Blueprint §24)
// "Every $ of FCF has one of 5 destinations — give the owner a structured view"
// ────────────────────────────────────────────────────────────────────────
function CapitalPage({ data }) {
  const projectedFCF12mo = 1840000;
  const reservePolicy = 380000 * 6; // 6 months burn target
  const currentReserve = data.cash.startCash;
  const reserveGap = Math.max(0, reservePolicy - currentReserve);

  // Marginal returns from internal data (mock)
  const reinvestChannels = [
    { c: "Inventory (fast-movers)", cost: 240000, return: 432000, irr: 38, payback: 7, conf: 86, why: "POL & AUR run-rate × replenish cycle. Closes the POL-550 stockout exposure." },
    { c: "Marketing — paid",         cost: 180000, return: 318000, irr: 31, payback: 9, conf: 74, why: "Last 6mo CAC = $284, LTV/CAC = 4.2x at current targeting." },
    { c: "Senior hire (Sales)",      cost: 285000, return: 480000, irr: 28, payback: 11, conf: 68, why: "Sales coverage gap in South region; 2-rep precedent ramp 9mo." },
    { c: "Production capacity",      cost: 420000, return: 612000, irr: 22, payback: 14, conf: 62, why: "Aurelius backlog supports Line 2 capacity add." },
    { c: "Store expansion",          cost: 380000, return: 460000, irr: 16, payback: 18, conf: 54, why: "Cherry Creek relocation; Pearl District demos match." },
  ];

  return (
    <div className="pc-page">
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Projected FCF · 12mo" value={fmtUSD(projectedFCF12mo, { compact: true })} hint="Base forecast" accent="var(--positive)" />
        <KPICard label="Cash reserve target" value={fmtUSD(reservePolicy, { compact: true })} hint="6× monthly burn" accent="var(--accent)" />
        <KPICard label="Reserve gap"          value={reserveGap === 0 ? "Funded" : fmtUSD(reserveGap, { compact: true })} hint={reserveGap === 0 ? "Above policy" : "to top up"} accent={reserveGap === 0 ? "var(--positive)" : "var(--warning)"} />
        <KPICard label="Discretionary capital" value={fmtUSD(projectedFCF12mo - reserveGap, { compact: true })} hint="Available to deploy" accent="var(--accent-2)" />
      </div>

      <Card title="Capital allocation framework" subtitle="Every dollar of free cash flow has one of 5 destinations">
        <div className="pc-cap-strip">
          {[
            { l: "Reinvest",     v: 0.42, color: "var(--accent)" },
            { l: "Pay down debt", v: 0.18, color: "var(--accent-2)" },
            { l: "Build reserves", v: 0.14, color: "var(--positive)" },
            { l: "Owner draws",  v: 0.16, color: "var(--warning)" },
            { l: "Acquisitions", v: 0.10, color: "#8b5cf6" },
          ].map((b, idx) => (
            <div key={idx} className="pc-cap-bucket" style={{ flex: b.v, background: b.color + "26", borderTop: "3px solid " + b.color }}>
              <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.4 }}>{b.l}</div>
              <div style={{ fontSize: 18, fontWeight: 600, fontFamily: "ui-monospace, monospace", marginTop: 4 }}>{fmtUSD(projectedFCF12mo * b.v, { compact: true })}</div>
              <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{(b.v * 100).toFixed(0)}% of FCF</div>
            </div>
          ))}
        </div>
      </Card>

      <Card title="Reinvestment opportunities · ranked by marginal IRR" subtitle="Where each next dollar earns the best return based on your historical conversion rates"
            action={<ExportButton rows={reinvestChannels} filename="Reinvestment_options" />} padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>Opportunity</th>
              <th style={{textAlign:"right"}}>Capital required</th>
              <th style={{textAlign:"right"}}>12-mo return</th>
              <th style={{textAlign:"right"}}>IRR</th>
              <th style={{textAlign:"right"}}>Payback</th>
              <th>Confidence</th>
              <th>Why</th>
            </tr>
          </thead>
          <tbody>
            {reinvestChannels.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.cost)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--positive)"}}>+{fmtUSD(r.return)}</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", fontWeight: 600, color: r.irr >= 25 ? "var(--positive)" : r.irr >= 15 ? "var(--warning)" : "var(--text-2)"}}>{r.irr}%</td>
                <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{r.payback} mo</td>
                <td><ConfBar v={r.conf} /></td>
                <td style={{fontSize: 11.5, color: "var(--text-2)"}}>{r.why}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div className="pc-grid-2">
        <Card title="Debt schedule" subtitle="Optional pay-down impact">
          <table className="pc-table compact">
            <thead><tr><th>Facility</th><th style={{textAlign:"right"}}>Balance</th><th style={{textAlign:"right"}}>Rate</th><th style={{textAlign:"right"}}>Pay-off saves</th></tr></thead>
            <tbody>
              {[
                { f: "Revolving LOC",       b: 340000, r: 8.4, sav: 28560 },
                { f: "Equipment lease",     b: 184000, r: 6.8, sav: 12512 },
                { f: "SBA Term loan",       b: 412000, r: 7.2, sav: 29664 },
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{paddingLeft: 14, fontWeight: 500}}>{r.f}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{fmtUSD(r.b)}</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right"}}>{r.r}%</td>
                  <td style={{fontFamily: "ui-monospace, monospace", textAlign: "right", color: "var(--positive)"}}>+{fmtUSD(r.sav)}/yr</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Owner distributions" subtitle="Tax-reserved view">
          <table className="pc-table compact">
            <tbody>
              <tr><td style={{paddingLeft:14}}>YTD draws taken</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(124000)}</td></tr>
              <tr><td style={{paddingLeft:14}}>Tax reserve (30% est)</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(37200)}</td></tr>
              <tr><td style={{paddingLeft:14}}>Available for additional distribution</td><td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--positive)", fontWeight: 500}}>{fmtUSD(248000)}</td></tr>
              <tr><td style={{paddingLeft:14, color: "var(--text-3)"}}>Recommended cadence</td><td style={{textAlign:"right", color: "var(--text-3)", fontSize: 11.5}}>Quarterly · post-close</td></tr>
            </tbody>
          </table>
          <AIInsight>
            With reserves above target and runway healthy, Q2 distribution of <b>{fmtUSD(62000)}</b> stays within tax-safe-harbor and preserves reinvestment capacity for the inventory + marketing opportunities above.
          </AIInsight>
        </Card>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// GOAL & TARGET TRACKING (Blueprint §25)
// "Seasonality-aware pace — not linear"
// ────────────────────────────────────────────────────────────────────────
function GoalsPage({ data }) {
  // Annual goals with seasonality curves
  const goals = [
    {
      name: "FY26 Revenue", target: 18800000, current: 7124000,
      seasonal: [0.07, 0.07, 0.08, 0.08, 0.08, 0.09, 0.08, 0.08, 0.09, 0.10, 0.09, 0.09],
      monthsIn: 4.5, owner: "Mara · CEO",
      explain: "Q4-loaded business · 38% of revenue lands Oct–Dec."
    },
    {
      name: "Gross margin %", target: 56.0, current: 48.4, isPct: true,
      monthsIn: 4.5, owner: "Iris · Finance",
      explain: "V-201 cost step set us back · pricing action recommended."
    },
    {
      name: "EBITDA $", target: 4400000, current: 1620000,
      seasonal: [0.06, 0.06, 0.07, 0.08, 0.08, 0.09, 0.09, 0.09, 0.10, 0.10, 0.09, 0.09],
      monthsIn: 4.5, owner: "Theo · CFO",
      explain: "Operating profit · pre-tax · pre-interest."
    },
    {
      name: "New customers", target: 84, current: 31, isCount: true,
      seasonal: [0.08, 0.08, 0.09, 0.09, 0.09, 0.09, 0.08, 0.07, 0.08, 0.09, 0.08, 0.08],
      monthsIn: 4.5, owner: "Devon · Sales",
      explain: "Net new logos · ex-renewals."
    },
    {
      name: "Headcount",      target: 30, current: 24, isCount: true,
      monthsIn: 4.5, owner: "Lena · Ops",
      explain: "Net headcount with planned 6 hires loaded by Q3."
    },
    {
      name: "Net retention %", target: 115, current: 118, isPct: true,
      monthsIn: 4.5, owner: "Devon · Sales",
      explain: "Already above target · driven by Halcyon + Northwind expansion."
    },
  ];

  return (
    <div className="pc-page">
      <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 }}>Pace is seasonality-aware</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              You are <b>not</b> "behind" on revenue in May if your historical pattern delivers 38% of the year in Q4. The pace bar below the headline number compares actual-to-date against the <i>seasonally-expected</i> level at this point in the year — the only honest measure.
            </div>
          </div>
        </div>
      </div>

      <div className="pc-goals-grid">
        {goals.map((g, i) => <GoalCard key={i} goal={g} />)}
      </div>
    </div>
  );
}

function GoalCard({ goal }) {
  // Seasonally-expected progress
  let expectedFraction;
  if (goal.seasonal) {
    const fullMonths = Math.floor(goal.monthsIn);
    const partial = goal.monthsIn - fullMonths;
    expectedFraction = goal.seasonal.slice(0, fullMonths).reduce((s, v) => s + v, 0) + (goal.seasonal[fullMonths] || 0) * partial;
  } else {
    expectedFraction = goal.monthsIn / 12;
  }
  const expected = goal.target * expectedFraction;
  const actual = goal.current;
  const actualFraction = actual / goal.target;
  const pace = actual / expected; // > 1 = ahead

  const status = pace >= 1.02 ? "ahead" : pace >= 0.95 ? "on" : pace >= 0.85 ? "behind" : "way_behind";
  const statusLabel = { ahead: "Ahead of pace", on: "On pace", behind: "Behind pace", way_behind: "Critically behind" }[status];
  const statusColor = { ahead: "var(--positive)", on: "var(--positive)", behind: "var(--warning)", way_behind: "var(--danger)" }[status];

  const formatVal = (v) => goal.isPct ? v.toFixed(1) + "%" : goal.isCount ? Math.round(v).toLocaleString() : fmtUSD(v, { compact: true });

  return (
    <div className="pc-goal-card">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div>
          <div style={{ fontSize: 11.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>{goal.name}</div>
          <div style={{ fontSize: 24, fontWeight: 600, fontFamily: "ui-monospace, monospace", marginTop: 6, fontVariantNumeric: "tabular-nums" }}>{formatVal(actual)}</div>
          <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 2 }}>
            Target {formatVal(goal.target)} · {Math.round((1 - goal.monthsIn / 12) * 365)} days remaining
          </div>
        </div>
        <span className="pc-statpill" style={{ background: statusColor + "26", color: statusColor }}>{statusLabel}</span>
      </div>

      {/* Dual progress: actual + expected */}
      <div className="pc-goal-progress">
        <div className="pc-goal-progress-track">
          <div className="pc-goal-progress-actual" style={{ width: Math.min(actualFraction * 100, 100) + "%", background: statusColor }} />
          <div className="pc-goal-progress-marker" style={{ left: Math.min(expectedFraction * 100, 100) + "%" }} title={"Expected at this point: " + formatVal(expected)} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10.5, color: "var(--text-3)", marginTop: 6, fontFamily: "ui-monospace, monospace" }}>
          <span>Actual {(actualFraction * 100).toFixed(0)}%</span>
          <span style={{ color: statusColor }}>Pace {pace >= 1 ? "+" : ""}{((pace - 1) * 100).toFixed(0)}%</span>
          <span>Expected {(expectedFraction * 100).toFixed(0)}%</span>
        </div>
      </div>

      <div style={{ fontSize: 11.5, color: "var(--text-2)", marginTop: 12, lineHeight: 1.55, paddingTop: 12, borderTop: "1px solid var(--border)" }}>
        {goal.explain}
      </div>
      <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 8 }}>Owner: <b style={{ color: "var(--text-2)" }}>{goal.owner}</b></div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────
// CUSTOMER ACQUISITION + COHORT RETENTION (Blueprint §15.1 + §15.2)
// "CAC, payback, LTV/CAC, cohort retention by acquisition month"
// ────────────────────────────────────────────────────────────────────────
function AcquisitionPage({ data, period: globalPeriod, setPeriod: setGlobalPeriod }) {
  const { PeriodComparerEl, compareDeltaSub } = window.usePeriod(globalPeriod, setGlobalPeriod);
  // Channels with full unit economics
  const channels = [
    { c: "Paid Search",   spend: 84000,  newCust: 124, firstOrder: 412, gpFirst: 198, ltv: 2840, ltvMargin: 1420 },
    { c: "Paid Social",   spend: 62000,  newCust: 142, firstOrder: 342, gpFirst: 165, ltv: 1840, ltvMargin: 920 },
    { c: "Organic Search", spend: 18000, newCust: 84,  firstOrder: 488, gpFirst: 234, ltv: 3120, ltvMargin: 1560 },
    { c: "Referral",      spend: 8000,   newCust: 38,  firstOrder: 614, gpFirst: 294, ltv: 4280, ltvMargin: 2140 },
    { c: "Direct mail",   spend: 24000,  newCust: 28,  firstOrder: 412, gpFirst: 198, ltv: 2120, ltvMargin: 1060 },
    { c: "Marketplace",   spend: 0,      newCust: 84,  firstOrder: 184, gpFirst: 64,  ltv: 720,  ltvMargin: 360 },
  ];

  // Cohort retention table (% of cohort revenue retained)
  const cohorts = [
    { c: "May 2024", n: 38, ret: [100, 84, 72, 61, 54, 48, 44, 41, 38, 36, 34, 32] },
    { c: "Aug 2024", n: 42, ret: [100, 86, 74, 64, 56, 50, 46, 43, 40, 38, 36, null] },
    { c: "Nov 2024", n: 51, ret: [100, 88, 76, 67, 60, 54, 50, 47, 44, null, null, null] },
    { c: "Feb 2025", n: 48, ret: [100, 89, 78, 70, 64, 59, 55, null, null, null, null, null] },
    { c: "May 2025", n: 56, ret: [100, 91, 81, 73, 68, 64, null, null, null, null, null, null] },
    { c: "Aug 2025", n: 62, ret: [100, 92, 84, 78, 72, null, null, null, null, null, null, null] },
    { c: "Nov 2025", n: 71, ret: [100, 94, 87, 81, null, null, null, null, null, null, null, null] },
    { c: "Feb 2026", n: 68, ret: [100, 95, 89, null, null, null, null, null, null, null, null, null] },
  ];

  const totalSpend = channels.reduce((s, c) => s + c.spend, 0);
  const totalNew = channels.reduce((s, c) => s + c.newCust, 0);
  const blendedCAC = totalSpend / totalNew;
  const blendedLTV = channels.reduce((s, c) => s + c.ltvMargin * c.newCust, 0) / totalNew;
  const blendedRatio = blendedLTV / blendedCAC;

  return (
    <div className="pc-page">
      {PeriodComparerEl}
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Blended CAC"      value={fmtUSD(blendedCAC, { decimals: 0 })} delta={-4.2} sub={compareDeltaSub || "vs trailing 6mo"} accent="var(--accent)" />
        <KPICard label="Blended LTV / margin" value={fmtUSD(blendedLTV, { compact: true })} delta={8.4} sub="vs trailing 6mo" accent="var(--accent-2)" />
        <KPICard label="LTV / CAC"        value={blendedRatio.toFixed(1) + "x"} hint="3.0x is healthy" accent={blendedRatio >= 3 ? "var(--positive)" : "var(--warning)"} />
        <KPICard label="Payback period"   value="11 mo" delta={-2.1} sub="vs trailing 6mo" accent="var(--positive)" />
      </div>

      <Card title="Acquisition channel economics" subtitle="CAC · payback · LTV / CAC by channel"
            action={<ExportButton rows={channels} filename="Acquisition_channels" />} padding={0}>
        <table className="pc-table">
          <thead>
            <tr>
              <th>Channel</th>
              <th style={{textAlign:"right"}}>Spend</th>
              <th style={{textAlign:"right"}}>New customers</th>
              <th style={{textAlign:"right"}}>CAC</th>
              <th style={{textAlign:"right"}}>Avg first order</th>
              <th style={{textAlign:"right"}}>Payback (months)</th>
              <th style={{textAlign:"right"}}>LTV margin</th>
              <th style={{textAlign:"right"}}>LTV / CAC</th>
              <th>Verdict</th>
            </tr>
          </thead>
          <tbody>
            {channels.map((r, i) => {
              const cac = r.spend / Math.max(r.newCust, 1);
              const payback = cac / (r.gpFirst || 1) * 6; // crude
              const ratio = r.ltvMargin / Math.max(cac, 1);
              const verdict = cac === 0 ? "Free" : ratio >= 4 ? "Scale" : ratio >= 3 ? "Hold" : ratio >= 2 ? "Watch" : "Cut";
              const verdictColor = verdict === "Cut" ? "var(--danger)" : verdict === "Watch" ? "var(--warning)" : "var(--positive)";
              return (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight: 500}}>{r.c}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(r.spend)}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{r.newCust}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 500}}>{cac === 0 ? "—" : fmtUSD(cac, { decimals: 0 })}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-2)"}}>{fmtUSD(r.firstOrder)}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: payback > 18 ? "var(--danger)" : payback > 12 ? "var(--warning)" : "var(--positive)"}}>{cac === 0 ? "—" : payback.toFixed(0)}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right"}}>{fmtUSD(r.ltvMargin)}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", fontWeight: 600, color: ratio >= 3 ? "var(--positive)" : "var(--warning)"}}>{cac === 0 ? "—" : ratio.toFixed(1) + "x"}</td>
                  <td><span className="pc-statpill" style={{background: verdictColor + "26", color: verdictColor}}>{verdict}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      <Card title="Cohort retention" subtitle="% of cohort revenue retained by month since acquisition · the trust signal of the customer base"
            action={<ExportButton rows={cohorts} filename="Cohort_retention" />} padding={0}>
        <div style={{ overflowX: "auto" }}>
          <table className="pc-table compact" style={{ minWidth: 880 }}>
            <thead>
              <tr>
                <th>Cohort</th>
                <th style={{textAlign:"right"}}>N</th>
                {["M0","M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11"].map(m => <th key={m} style={{textAlign:"center"}}>{m}</th>)}
              </tr>
            </thead>
            <tbody>
              {cohorts.map((c, i) => (
                <tr key={i}>
                  <td style={{paddingLeft:14, fontWeight:500}}>{c.c}</td>
                  <td style={{fontFamily:"ui-monospace, monospace", textAlign:"right", color: "var(--text-3)"}}>{c.n}</td>
                  {c.ret.map((v, idx) => (
                    <td key={idx} style={{textAlign: "center", padding: "6px 4px"}}>
                      {v === null
                        ? <span style={{color: "var(--text-4)"}}>—</span>
                        : <span className="pc-cohort-cell" style={{ background: `rgba(110,231,183,${v / 130})`, color: v >= 60 ? "var(--text)" : v >= 40 ? "var(--text-2)" : "var(--danger)" }}>{v}%</span>
                      }
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ padding: "14px 18px", borderTop: "1px solid var(--border)" }}>
          <AIInsight>
            Recent cohorts (Aug 2025 onward) retain <b>~8 percentage points better</b> than mid-2024 cohorts at the same age — the Polaris launch and the post-onboarding flow improvements are working. Sustaining this trajectory adds <b>~$420K of recurring LTV margin</b> per year at current acquisition pace.
          </AIInsight>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { HealthPage, ThirteenWeekCash, CapitalPage, GoalsPage, AcquisitionPage });
