// Network Reports — HQ roll-up version of the operator's Reports & Insights page.
// Same visual style as the operator screen (tabs, KPI grid, chart+actions row,
// peak demand heatmap, category mix, capacity analysis) — but every number is a
// 10-shop roll-up. Adds HQ-only views the operator screen doesn't have: a per-shop
// network capacity calendar, a royalty reconciliation tab, and a cohort comparison
// (corporate vs franchised, mature vs new, region vs region).

// ── Per-period roll-ups (everything scales off KPIS_BY_PERIOD) ──────────
const REPORT_PERIOD_LABELS = { T:'Today', WTD:'Week to date', MTD:'Month to date', QTD:'Quarter to date', YTD:'Year to date' };

// Network-wide AI "next-best actions" — HQ flavour
const NEXT_BEST_ACTIONS = [
  {
    title: 'Push the Spring Refresh template SMS variant',
    detail: 'Email version is the network\'s top performer at 38% open. Porting to SMS at 4 shops with high SMS-consent rates is modeled to lift Q2 net sales by ~$42K.',
    sub: 'Modeled impact: +$42K Q2',
    cta: 'Build SMS variant',
    icon: 'megaphone',
  },
  {
    title: 'Close the loyalty-redemption gap at 3 lagging shops',
    detail: '7 shops redemption above 35%; Scarborough, Richmond Hill and Markham below 15%. Aligning to network average unlocks ~$34K/mo in repeat revenue.',
    sub: 'Modeled impact: +$34K / mo',
    cta: 'Open uplift plan',
    icon: 'gift',
  },
  {
    title: 'Run a network win-back on lapsed clients',
    detail: '3,248 clients with no visit in 60–180 days across the network. Avg client value is $412; a 6% conversion is worth ~$80K.',
    sub: 'At-risk clients: 3,248',
    cta: 'Schedule campaign',
    icon: 'sparkle',
  },
  {
    title: 'Diversify Beard Balm supplier',
    detail: 'Northbridge serves 10/10 shops on a SKU now in stockout at 2 shops; vendor SLA breach already cost ~$8K. ProEdge Distribution offered a 14-day cover.',
    sub: 'Risk reduction',
    cta: 'Open vendor diversification',
    icon: 'box',
  },
];

// Royalty reconciliation per franchisee (8 franchised shops)
const ROYALTIES = [
  { id:'HB002', shop:'Mississauga',       rate: 6.5, reportedSales: 107120, projected: 6963, collected: 6963, status:'paid',    onTime:true,  auto:true },
  { id:'HB003', shop:'Oakville', rate: 6.5, reportedSales: 102440, projected: 6659, collected: 6659, status:'paid',    onTime:true,  auto:true },
  { id:'HB005', shop:'Hamilton',         rate: 6.5, reportedSales:  89960, projected: 5848, collected: 5848, status:'paid',    onTime:true,  auto:true },
  { id:'HB006', shop:'Vaughan',      rate: 6.5, reportedSales:  81120, projected: 5273, collected: 5273, status:'paid',    onTime:true,  auto:true },
  { id:'HB007', shop:'Markham',  rate: 6.5, reportedSales:  74880, projected: 4867, collected: 4867, status:'paid',    onTime:false, auto:true, lateDays: 4 },
  { id:'HB008', shop:'Brampton',      rate: 7.0, reportedSales:  68640, projected: 4805, collected: 4805, status:'paid',    onTime:true,  auto:false },
  { id:'HB009', shop:'Richmond Hill',        rate: 6.5, reportedSales:  59280, projected: 3853, collected:    0, status:'overdue', onTime:false, auto:false, lateDays: 11 },
  { id:'HB010', shop:'Scarborough',       rate: 6.5, reportedSales:  53040, projected: 3448, collected: 1200, status:'partial', onTime:false, auto:false, lateDays: 8, dispute:true },
];

// Cohort benchmarks (gap #9)
const COHORTS = [
  { label:'Corporate (2 shops)',     scope:'corp',  revPerHour: 64.20, util: 81.2, nps: 74, rebook: 71, retention: 65 },
  { label:'Franchised (8 shops)',    scope:'franc', revPerHour: 56.40, util: 69.8, nps: 67, rebook: 64, retention: 53 },
  { label:'Mature (>24mo, 6 shops)', scope:'mature',revPerHour: 60.40, util: 76.1, nps: 71, rebook: 69, retention: 60 },
  { label:'New (<18mo, 4 shops)',    scope:'new',   revPerHour: 53.20, util: 64.4, nps: 64, rebook: 60, retention: 47 },
  { label:'Top quartile',            scope:'top',   revPerHour: 66.00, util: 82.6, nps: 75, rebook: 72, retention: 66 },
  { label:'Bottom quartile',         scope:'bot',   revPerHour: 46.20, util: 59.4, nps: 62, rebook: 59, retention: 42 },
];

// ── Tab strip + period picker (visually matches the operator screen) ──
const ReportTabs = ({ tab, setTab }) => {
  const tabs = [
    ['overview',   'Overview'],
    ['sales',      'Sales'],
    ['royalty',    'Royalty'],
    ['customers',  'Customers'],
    ['finance',    'Finance'],
    ['vendor',     'Vendor'],
    ['cohort',     'Cohort'],
    ['pl',         'P&L'],
  ];
  return (
    <div className="report-tabs">
      {tabs.map(([id, lbl]) => (
        <button key={id} className={'report-tab' + (tab === id ? ' is-on' : '')} onClick={() => setTab(id)}>{lbl}</button>
      ))}
    </div>
  );
};

// ── Reusable: KPI card (white card, AI tag, delta) ─────────────────────
const ReportKpi = ({ label, value, sub, delta, deltaPositive, info, ai = true }) => (
  <article className="r-kpi">
    <div className="r-kpi-top">
      <div className="r-kpi-label">{label}{info && <InfoDot tip={info}/>}</div>
      {ai && <span className="r-kpi-ai">✨ AI</span>}
    </div>
    <div className="r-kpi-value">{value}</div>
    {(delta || sub) && (
      <div className={'r-kpi-delta ' + (deltaPositive === true ? 'is-up' : deltaPositive === false ? 'is-down' : '')}>
        {delta || sub}
      </div>
    )}
  </article>
);

// ── Sales-over-time chart (matches operator "Daily Sales") ─────────────
const SalesChart = ({ period }) => {
  // synthesize 10-week network revenue series (this period vs last period)
  const seed = ({ T:1, WTD:2, MTD:3, QTD:4, YTD:5 })[period] || 3;
  const thisP  = Array.from({ length: 10 }, (_, i) => 70000 + Math.sin(i * 0.6 + seed) * 18000 + i * 6800 + seed * 1200);
  const lastP  = Array.from({ length: 10 }, (_, i) => 62000 + Math.sin(i * 0.55 + seed + 1) * 16000 + i * 5800 + seed * 900);
  const W = 760, H = 240, P = 40;
  const all = [...thisP, ...lastP];
  const yMax = Math.max(...all) * 1.08;
  const yMin = 0;
  const x = (i) => P + (i / (thisP.length - 1)) * (W - P * 2);
  const y = (v) => H - P + ((yMin - v) / (yMax - yMin)) * (H - P * 2);
  const path = (data) => data.map((v, i) => (i === 0 ? 'M' : 'L') + x(i).toFixed(1) + ',' + y(v).toFixed(1)).join(' ');
  const area = (data) => path(data) + ` L${x(data.length-1).toFixed(1)},${(H-P).toFixed(1)} L${x(0).toFixed(1)},${(H-P).toFixed(1)} Z`;
  const avgThis = thisP.reduce((a,b) => a+b, 0) / thisP.length;
  const avgLast = lastP.reduce((a,b) => a+b, 0) / lastP.length;
  const mom = ((avgThis - avgLast) / avgLast) * 100;

  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="chart" size={16} stroke={2}/>
          <h2>Network sales — {REPORT_PERIOD_LABELS[period]}</h2>
          <span className="r-kpi-ai">✨ AI</span>
        </div>
        <div className="card-head-right">
          <div className="legend"><span className="dot" style={{ background:'#94A3B8' }}/>Last period</div>
          <div className="legend"><span className="dot" style={{ background:'#16A34A' }}/>This period</div>
        </div>
      </header>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display:'block', height: 240 }}>
        <defs>
          <linearGradient id="r-sales-grad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#16A34A" stopOpacity="0.18"/>
            <stop offset="100%" stopColor="#16A34A" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[0.25, 0.5, 0.75, 1].map((t, i) => (
          <g key={i}>
            <line x1={P} x2={W-P} y1={H-P-(H-P*2)*t} y2={H-P-(H-P*2)*t} stroke="#F1F5F9"/>
            <text x={P-6} y={H-P-(H-P*2)*t + 4} textAnchor="end" fontSize="10" fill="#94A3B8">{'$' + Math.round(yMax * t / 1000) + 'K'}</text>
          </g>
        ))}
        <path d={area(thisP)} fill="url(#r-sales-grad)"/>
        <path d={path(lastP)} fill="none" stroke="#94A3B8" strokeWidth="1.5" strokeDasharray="4 4"/>
        <path d={path(thisP)} fill="none" stroke="#16A34A" strokeWidth="2.2"/>
        {thisP.map((v, i) => <circle key={i} cx={x(i)} cy={y(v)} r="3" fill="#16A34A"/>)}
        {Array.from({ length: 5 }, (_, i) => Math.floor(i * (thisP.length - 1) / 4)).map(i => (
          <text key={i} x={x(i)} y={H-P+18} textAnchor="middle" fontSize="10" fill="#94A3B8">Wk {i+1}</text>
        ))}
      </svg>
      <div className="r-chart-foot">
        <div className="r-chart-stat"><span>Avg / period this {period}</span><b>{fmtMoneyFull(Math.round(avgThis))}</b></div>
        <div className="r-chart-stat"><span>Avg / period last {period}</span><b>{fmtMoneyFull(Math.round(avgLast))}</b></div>
        <div className="r-chart-stat"><span>vs last period</span><b style={{ color: mom >= 0 ? '#16A34A' : '#DC2626' }}>{mom >= 0 ? '+' : ''}{mom.toFixed(1)}%</b></div>
      </div>
    </section>
  );
};

// ── Next-best-actions card ────────────────────────────────────────────
const NextBestActions = () => (
  <section className="card">
    <header className="card-head">
      <div className="card-head-left">
        <Icon name="sparkle" size={16} stroke={2}/>
        <h2>Next Best Actions</h2>
        <InfoDot tip="HQ-level actions ranked by modeled $ impact. Each links into the relevant workflow."/>
        <span className="r-kpi-ai">✨ AI</span>
      </div>
    </header>
    <ul className="nba-list">
      {NEXT_BEST_ACTIONS.map((a, i) => (
        <li key={i} className="nba-row">
          <div className="nba-icon"><Icon name={a.icon} size={14} stroke={2}/></div>
          <div className="nba-body">
            <div className="nba-title">{a.title}</div>
            <div className="nba-sub">{a.sub}</div>
            <button className="nba-cta">{a.cta} <Icon name="arrow-right" size={11} stroke={2.4}/></button>
          </div>
        </li>
      ))}
    </ul>
  </section>
);

// ── Peak demand heatmap (per-hour utilization across the network) ──────
const PeakDemandHeatmap = ({ period }) => {
  // Generate a 7×10 grid (Mon..Sun × 9AM..6PM) of utilization %
  // Deterministic from period seed; reflects realistic network pattern.
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const hours = ['9AM','10AM','11AM','12PM','1PM','2PM','3PM','4PM','5PM','6PM'];
  const baseUtil = window.FRANCHISE_DATA.KPIS_BY_PERIOD[period].utilization;
  const seed = ({ T:1, WTD:2, MTD:3, QTD:4, YTD:5 })[period] || 3;
  const rng = (i) => ((seed * 9301 + i * 49297) % 233280) / 233280;
  const cellPattern = (day, hour) => {
    // Friday + Saturday + weekday evenings are peak; midweek mornings are weak
    let m = 1;
    if (day === 4 || day === 5) m += 0.18;
    if (day === 6) m += 0.05;
    if (hour >= 6 && hour <= 8) m += 0.12;
    if (day < 4 && hour < 3) m -= 0.18;
    if (day === 6 && hour > 6) m -= 0.15;
    const jitter = (rng(day * 13 + hour * 7) - 0.5) * 0.18;
    const v = Math.max(20, Math.min(98, Math.round(baseUtil * m + jitter * 30)));
    return v;
  };
  const allValues = days.flatMap((_, d) => hours.map((_, h) => cellPattern(d, h)));
  const peakSlots = allValues.filter(v => v >= 90).length;
  const range = `${Math.min(...allValues)}% – ${Math.max(...allValues)}%`;

  const utilColor = (v) => {
    if (v >= 90) return ['#0F766E', '#fff'];
    if (v >= 80) return ['#14B8A6', '#fff'];
    if (v >= 70) return ['#2DD4BF', '#0F172A'];
    if (v >= 60) return ['#5EEAD4', '#0F172A'];
    if (v >= 50) return ['#99F6E4', '#0F172A'];
    if (v >= 40) return ['#CCFBF1', '#0F172A'];
    return ['#F0FDFA', '#475569'];
  };

  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="clock" size={16} stroke={2}/>
          <h2>Peak Demand Heatmap</h2>
          <InfoDot tip="Network utilization profile by day-of-week × hour-of-day for the selected period. Cells colored by % of chair-hours booked."/>
          <span className="r-kpi-ai">✨ AI</span>
        </div>
        <div className="card-head-right">
          <span className="muted" style={{ fontSize: 11.5 }}>Peak slots: {peakSlots} · Range: {range}</span>
        </div>
      </header>
      <div className="heatmap">
        <div className="heat-corner"/>
        {hours.map(h => <div key={h} className="heat-col-label">{h}</div>)}
        {days.map((d, di) => (
          <React.Fragment key={d}>
            <div className="heat-row-label">{d}</div>
            {hours.map((_, hi) => {
              const v = cellPattern(di, hi);
              const [bg, fg] = utilColor(v);
              return (
                <div key={hi} className="heat-cell" style={{ background: bg, color: fg }} title={`${d} ${hours[hi]} · ${v}% util`}>{v}%</div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
      <div className="heat-legend">
        {[['Very Low (<40%)','#F0FDFA'],['Low (40–50%)','#CCFBF1'],['Medium (50–60%)','#99F6E4'],['Good (60–70%)','#5EEAD4'],['High (70–80%)','#2DD4BF'],['Very High (80–90%)','#14B8A6'],['Peak (90%+)','#0F766E']].map(([lbl, c]) => (
          <span key={lbl} className="heat-legend-item"><span className="heat-legend-dot" style={{ background: c }}/>{lbl}</span>
        ))}
      </div>
    </section>
  );
};

// ── Network capacity calendar (per-location × day-of-week) ─────────────
// This is the missing HQ-level operational view from gap #1.
const NetworkCapacityCalendar = () => {
  const LOCATIONS = window.FRANCHISE_DATA.LOCATIONS;
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  // Deterministic per-location-per-day fill rates
  const rng = (a, b) => ((a * 9301 + b * 49297) % 233280) / 233280;
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="calendar" size={16} stroke={2}/>
          <h2>Network capacity — this week</h2>
          <InfoDot tip="Each row is a shop; each column is a day. Cells show booked %, with available chair-hours and staffing gaps. Use it to spot empty shops and trigger marketing."/>
          <span className="card-head-count">10 shops × 7 days</span>
        </div>
        <div className="card-head-right">
          <button className="ghost-btn small">Export CSV</button>
        </div>
      </header>
      <div className="cap-cal-wrap">
        <table className="cap-cal">
          <thead>
            <tr>
              <th>Shop</th>
              {days.map(d => <th key={d} className="cap-day-head">{d}</th>)}
              <th className="num">Week total</th>
            </tr>
          </thead>
          <tbody>
            {LOCATIONS.map((loc, li) => {
              const cells = days.map((d, di) => {
                const base = loc.utilization;
                const variance = (rng(li, di) - 0.5) * 24;
                const fri = di === 4 ? 12 : 0;
                const sat = di === 5 ? 6 : 0;
                const mon = di === 0 ? -8 : 0;
                const v = Math.max(20, Math.min(98, Math.round(base + variance + fri + sat + mon)));
                return v;
              });
              const weekAvg = Math.round(cells.reduce((a,b) => a+b, 0) / cells.length);
              return (
                <tr key={loc.id}>
                  <td>
                    <div className="lb-name">{loc.name.replace('Hawke & Blade — ', '')}</div>
                    <div className="lb-sub">{loc.id} · {loc.city}</div>
                  </td>
                  {cells.map((v, di) => {
                    const cls = v >= 85 ? 'cap-cell cap-peak' : v >= 70 ? 'cap-cell cap-good' : v >= 55 ? 'cap-cell cap-mid' : v >= 40 ? 'cap-cell cap-low' : 'cap-cell cap-empty';
                    return (
                      <td key={di} className={cls}>
                        <div className="cap-cell-v">{v}%</div>
                        <div className="cap-cell-sub">{Math.round((100-v) * 0.72)}h open</div>
                        {v < 50 && <div className="cap-cell-tag">UNDERBOOKED</div>}
                        {v >= 92 && <div className="cap-cell-tag cap-cell-tag-peak">PEAK</div>}
                      </td>
                    );
                  })}
                  <td className="num"><span className={'pill ' + (weekAvg >= 75 ? 'pill-live' : '')} style={weekAvg < 60 ? { background:'#FEE2E2', color:'#B91C1C' } : weekAvg < 75 ? { background:'#FEF3C7', color:'#92400E' } : undefined}>{weekAvg}%</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </section>
  );
};

// ── Category mix card ──────────────────────────────────────────────────
const CategoryMix = () => {
  const rows = [
    { label:'Men',           pct: 64, value: 26840, color:'#16A34A' },
    { label:'Retail',        pct: 24, value: 10120, color:'#3B82F6' },
    { label:'Women',         pct:  9, value:  3960, color:'#F59E0B' },
    { label:'Seniors / Kids',pct:  3, value:  1340, color:'#A855F7' },
  ];
  const max = Math.max(...rows.map(r => r.pct));
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="chart" size={16} stroke={2}/>
          <h2>Category Mix — Month to Date</h2>
          <span className="r-kpi-ai">✨ AI</span>
        </div>
      </header>
      <ul className="bar-list">
        {rows.map(r => (
          <li key={r.label}>
            <div className="bar-list-head">
              <div><div className="bar-list-name">{r.label}</div><div className="bar-list-sub">{fmtMoneyFull(r.value)}</div></div>
              <div className="bar-list-val">{r.pct}%</div>
            </div>
            <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: (r.pct/max*100) + '%', background: r.color }}/></div>
          </li>
        ))}
      </ul>
      <div className="r-foot">
        <div className="r-foot-stat"><span>Total Revenue</span><b>$42,260</b></div>
        <div className="r-foot-stat"><span>Top Category</span><b>Men</b></div>
      </div>
    </section>
  );
};

// ── Capacity analysis (booked / cancelled / no-show / idle) ─────────────
const CapacityAnalysis = ({ period }) => {
  const k = window.FRANCHISE_DATA.KPIS_BY_PERIOD[period];
  const total = k.availableHours;
  const cancelled = Math.round(k.bookedHours * (k.cancellationRate / 100));
  const noShow = Math.round(k.bookedHours * (k.noShowRate / 100));
  const idle = total - k.bookedHours;
  const rows = [
    { label:'Booked',    pct: Math.round((k.bookedHours / total) * 100), value: k.bookedHours, color:'#16A34A' },
    { label:'Cancelled', pct: Math.round((cancelled / total) * 100),      value: cancelled,     color:'#F59E0B' },
    { label:'No-show',   pct: Math.round((noShow / total) * 100),         value: noShow,        color:'#EF4444' },
    { label:'Idle',      pct: Math.round((idle / total) * 100),           value: idle,          color:'#94A3B8' },
  ];
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="clock" size={16} stroke={2}/>
          <h2>Capacity Analysis — {REPORT_PERIOD_LABELS[period]}</h2>
          <span className="r-kpi-ai">✨ AI</span>
        </div>
      </header>
      <ul className="bar-list">
        {rows.map(r => (
          <li key={r.label}>
            <div className="bar-list-head">
              <div><div className="bar-list-name">{r.label}</div><div className="bar-list-sub">{r.value.toLocaleString()} hrs</div></div>
              <div className="bar-list-val">{r.pct}%</div>
            </div>
            <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: r.pct + '%', background: r.color }}/></div>
          </li>
        ))}
      </ul>
      <div className="r-foot">
        <div className="r-foot-stat"><span>Total chair-hours</span><b>{total.toLocaleString()} hrs</b></div>
        <div className="r-foot-stat"><span>Biggest leak</span><b style={{ color:'#475569' }}>Idle ({rows[3].pct}%)</b></div>
      </div>
    </section>
  );
};

// ── Top locations leaderboard (for the right rail) ──────────────────────
const TopLocationsCard = () => {
  const LOCATIONS = [...window.FRANCHISE_DATA.LOCATIONS].sort((a,b) => b.revenue - a.revenue).slice(0, 5);
  const max = Math.max(...LOCATIONS.map(l => l.revenue));
  return (
    <section className="card">
      <header className="card-head">
        <div className="card-head-left">
          <Icon name="building" size={16} stroke={2}/>
          <h2>Top Locations</h2>
          <span className="r-kpi-ai">✨ AI</span>
        </div>
      </header>
      <ul className="op-list">
        {LOCATIONS.map((l, i) => (
          <li key={l.id}>
            <div className="op-rank">{i + 1}</div>
            <div className="op-meta">
              <div className="op-name">{l.name.replace('Hawke & Blade — ', '')}</div>
              <div className="op-sub">{l.utilization}% util · NPS {l.nps} · {l.city}</div>
            </div>
            <div className="op-num">
              <div className="op-num-v">{fmtMoneyFull(l.revenue)}</div>
              <div className="op-sub" style={{ color: l.sssYoY >= 0 ? '#16A34A' : '#DC2626' }}>{l.sssYoY >= 0 ? '+' : ''}{l.sssYoY}% YoY</div>
            </div>
          </li>
        ))}
      </ul>
      <div className="r-foot">
        <div className="r-foot-stat"><span>Network Revenue</span><b>{fmtMoneyFull(LOCATIONS.reduce((a,l) => a + l.revenue, 0))}</b></div>
        <div className="r-foot-stat"><span>Top Shop</span><b>{LOCATIONS[0].name.replace('Hawke & Blade — ', '')}</b></div>
      </div>
    </section>
  );
};

// ═══════════════════════════════════════════════════════════════════════
// TAB CONTENT
// ═══════════════════════════════════════════════════════════════════════

const OverviewTab = ({ period }) => {
  const k = window.FRANCHISE_DATA.KPIS_BY_PERIOD[period];
  const cancellations = Math.round(k.bookedHours * (k.cancellationRate / 100) * (k.revPerHour));
  return (
    <React.Fragment>
      <div className="r-kpi-grid">
        <ReportKpi label="Total Net Sales"    value={fmtMoney(k.netSales)}                          delta={`${k.netSales >= 700000 ? '+11.2%' : '+8.4%'} vs last period`} deltaPositive info="Total gross sales across all 10 locations for the selected period."/>
        <ReportKpi label="Service Sales"      value={fmtMoney(k.serviceSales)}                       delta={`${((k.serviceSales/k.netSales)*100).toFixed(1)}% of net sales`} deltaPositive info="Revenue from services only. Excludes retail."/>
        <ReportKpi label="Retail Sales"       value={fmtMoney(k.productSales)}                       delta={`${((k.productSales/k.netSales)*100).toFixed(1)}% of net sales`} deltaPositive info="Revenue from retail products only."/>
        <ReportKpi label="Royalty (projected)"value={fmtMoney(k.royalties)}                          delta="8 franchised shops"          info="Modeled royalty income from franchised shops at each agreement's rate."/>
        <ReportKpi label="Available Hours"    value={k.availableHours.toLocaleString() + ' hrs'}     sub="Network capacity for period"   info="Total chair-hours scheduled across all 10 shops."/>
        <ReportKpi label="Utilization %"      value={k.utilization.toFixed(1) + '%'}                 delta={k.utilization >= 75 ? 'on target' : `${(75 - k.utilization).toFixed(1)}% gap to 75%`} deltaPositive={k.utilization >= 75} info="Booked ÷ available chair-hours. Target 75%."/>
        <ReportKpi label="Rev / Booked Hr"    value={'$' + k.revPerHour.toFixed(2)}                  delta="+4.2% vs last period" deltaPositive info="Service revenue per booked chair-hour."/>
        <ReportKpi label="Cancellation Rate"  value={k.cancellationRate.toFixed(1) + '%'}            delta={`~${fmtMoneyFull(cancellations)} lost`} deltaPositive={k.cancellationRate <= 5} info="% of appointments cancelled. Industry benchmark <5%."/>
      </div>

      <div className="r-two">
        <SalesChart period={period}/>
        <NextBestActions/>
      </div>

      <PeakDemandHeatmap period={period}/>

      <div className="r-two">
        <NetworkCapacityCalendar/>
        <TopLocationsCard/>
      </div>

      <div className="r-two">
        <CategoryMix/>
        <CapacityAnalysis period={period}/>
      </div>
    </React.Fragment>
  );
};

// Sales — by location/category/service breakdown (rolls up TOP_SERVICES per location)
const SalesTab = ({ period }) => {
  const mult = window.FRANCHISE_DATA.PERIOD_MULT[period];
  const LOCATIONS = window.FRANCHISE_DATA.LOCATIONS;
  const services = window.FRANCHISE_DATA.TOP_SERVICES;
  const products = window.FRANCHISE_DATA.TOP_PRODUCTS;
  const maxSvc = Math.max(...services.map(s => s.revenue * mult));
  const maxPrd = Math.max(...products.map(p => p.revenue * mult));
  return (
    <React.Fragment>
      <div className="r-kpi-grid">
        <ReportKpi label="Network Sales"      value={fmtMoney(LOCATIONS.reduce((a, l) => a + l.revenue * mult, 0))} delta="+9.4% YoY" deltaPositive/>
        <ReportKpi label="Avg basket"          value="$48.20" delta="+3.1% vs last period" deltaPositive/>
        <ReportKpi label="Avg ticket"          value="$62.40" delta="+1.8% vs last period" deltaPositive/>
        <ReportKpi label="Retail attach rate"  value="14.2%" delta="Below 18% target" deltaPositive={false}/>
      </div>

      <div className="r-two">
        <section className="card">
          <header className="card-head">
            <div className="card-head-left"><Icon name="scissors" size={16} stroke={2}/><h2>Top services — network</h2><span className="r-kpi-ai">✨ AI</span></div>
          </header>
          <ul className="bar-list">
            {services.map(s => (
              <li key={s.name}>
                <div className="bar-list-head">
                  <div><div className="bar-list-name">{s.name}</div><div className="bar-list-sub">{s.share}% share · {s.yoy >= 0 ? '+' : ''}{s.yoy}% YoY</div></div>
                  <div className="bar-list-val">{fmtMoney(s.revenue * mult)}</div>
                </div>
                <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: ((s.revenue * mult)/maxSvc*100).toFixed(0) + '%', background: s.color }}/></div>
              </li>
            ))}
          </ul>
        </section>
        <section className="card">
          <header className="card-head">
            <div className="card-head-left"><Icon name="box" size={16} stroke={2}/><h2>Top products — network</h2><span className="r-kpi-ai">✨ AI</span></div>
          </header>
          <ul className="bar-list">
            {products.map(p => (
              <li key={p.name}>
                <div className="bar-list-head">
                  <div><div className="bar-list-name">{p.name}</div><div className="bar-list-sub">{p.sku} · {Math.round(p.units * mult / 30)} units · {p.yoy >= 0 ? '+' : ''}{p.yoy}% YoY</div></div>
                  <div className="bar-list-val">{fmtMoney(p.revenue * mult)}</div>
                </div>
                <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: ((p.revenue * mult)/maxPrd*100).toFixed(0) + '%', background: p.color }}/></div>
              </li>
            ))}
          </ul>
        </section>
      </div>

      <section className="card">
        <header className="card-head">
          <div className="card-head-left"><Icon name="building" size={16} stroke={2}/><h2>Sales by location</h2><span className="card-head-count">10 shops</span></div>
        </header>
        <div className="lb-table-wrap">
          <table className="lb-table cat-table">
            <thead>
              <tr>
                <th>Location</th><th>Type</th><th className="num">Sales</th><th className="num">YoY</th><th className="num">$ / Booked Hr</th><th className="num">Utilization</th><th>Status</th>
              </tr>
            </thead>
            <tbody>
              {[...LOCATIONS].sort((a,b) => b.revenue - a.revenue).map(l => (
                <tr key={l.id}>
                  <td><div className="lb-name">{l.name.replace('Hawke & Blade — ', '')}</div><div className="lb-sub">{l.id} · {l.city}</div></td>
                  <td><span className={'type-badge type-' + l.type}>{l.type}</span></td>
                  <td className="num strong">{fmtMoneyFull(l.revenue * mult)}</td>
                  <td className="num" style={{ color: l.sssYoY >= 0 ? '#16A34A' : '#DC2626', fontWeight: 600 }}>{l.sssYoY >= 0 ? '+' : ''}{l.sssYoY}%</td>
                  <td className="num">${l.revPerHour.toFixed(2)}</td>
                  <td className="num">{l.utilization}%</td>
                  <td>
                    {l.compliance === 'green' && <span className="pill pill-live"><span className="pill-dot" style={{ background:'#16A34A' }}/>Healthy</span>}
                    {l.compliance === 'amber' && <span className="pill" style={{ background:'#FEF3C7', color:'#92400E' }}><span className="pill-dot" style={{ background:'#F59E0B' }}/>Watch</span>}
                    {l.compliance === 'red'   && <span className="pill" style={{ background:'#FEE2E2', color:'#B91C1C' }}><span className="pill-dot" style={{ background:'#DC2626' }}/>Risk</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </React.Fragment>
  );
};

// Royalty — projected vs collected detail (covers gap #5)
const RoyaltyTab = () => {
  const totalProjected = ROYALTIES.reduce((a, r) => a + r.projected, 0);
  const totalCollected = ROYALTIES.reduce((a, r) => a + r.collected, 0);
  const outstanding = totalProjected - totalCollected;
  const overdue = ROYALTIES.filter(r => r.status === 'overdue' || r.status === 'partial');
  return (
    <React.Fragment>
      <div className="r-kpi-grid">
        <ReportKpi label="Projected (MTD)"        value={fmtMoneyFull(totalProjected)} delta="8 franchised shops" ai={false} info="Modeled royalty income at each franchisee's agreement rate."/>
        <ReportKpi label="Collected (MTD)"        value={fmtMoneyFull(totalCollected)} delta={`${((totalCollected/totalProjected)*100).toFixed(1)}% collected`} deltaPositive ai={false}/>
        <ReportKpi label="Outstanding"            value={fmtMoneyFull(outstanding)}    delta={overdue.length + ' shops overdue'} deltaPositive={false} ai={false}/>
        <ReportKpi label="Auto-debit coverage"    value="6 of 8"                       delta="2 shops on manual" ai={false}/>
      </div>

      <section className="card">
        <header className="card-head">
          <div className="card-head-left">
            <Icon name="dollar" size={16} stroke={2}/>
            <h2>Royalty reconciliation</h2>
            <InfoDot tip="Per-franchisee royalty: reported sales × agreement rate, what we projected, and what we've actually collected. Drives the franchise-revenue line."/>
            <span className="card-head-count">8 franchised shops</span>
          </div>
          <div className="card-head-right">
            <button className="ghost-btn small">Export reconciliation</button>
            <button className="ghost-btn small">Settle disputes</button>
          </div>
        </header>
        <div className="lb-table-wrap">
          <table className="lb-table cat-table">
            <thead>
              <tr>
                <th>Shop</th>
                <th className="num">Rate</th>
                <th className="num">Reported sales (MTD)</th>
                <th className="num">Projected</th>
                <th className="num">Collected</th>
                <th className="num">Outstanding</th>
                <th>Auto-debit</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {ROYALTIES.map(r => {
                const out = r.projected - r.collected;
                return (
                  <tr key={r.id}>
                    <td><div className="lb-name">{r.shop}</div><div className="lb-sub">{r.id}</div></td>
                    <td className="num">{r.rate.toFixed(1)}%</td>
                    <td className="num">{fmtMoneyFull(r.reportedSales)}</td>
                    <td className="num strong">{fmtMoneyFull(r.projected)}</td>
                    <td className="num">{fmtMoneyFull(r.collected)}</td>
                    <td className="num" style={{ color: out > 0 ? '#DC2626' : '#16A34A', fontWeight: out > 0 ? 600 : 400 }}>{out > 0 ? fmtMoneyFull(out) : '—'}</td>
                    <td>{r.auto ? <span className="pill pill-live"><span className="pill-dot" style={{ background:'#16A34A' }}/>Auto</span> : <span className="pill" style={{ background:'#F1F5F9', color:'#64748B' }}>Manual</span>}</td>
                    <td>
                      {r.status === 'paid'    && r.onTime  && <span className="pill pill-live"><span className="pill-dot" style={{ background:'#16A34A' }}/>Paid on time</span>}
                      {r.status === 'paid'    && !r.onTime && <span className="pill" style={{ background:'#FEF3C7', color:'#92400E' }}><span className="pill-dot" style={{ background:'#F59E0B' }}/>Paid · {r.lateDays}d late</span>}
                      {r.status === 'overdue' && <span className="pill" style={{ background:'#FEE2E2', color:'#B91C1C' }}><span className="pill-dot" style={{ background:'#DC2626' }}/>Overdue {r.lateDays}d</span>}
                      {r.status === 'partial' && <span className="pill" style={{ background:'#FFEDD5', color:'#9A3412' }}><span className="pill-dot" style={{ background:'#F97316' }}/>Partial · {r.dispute ? 'disputed' : 'underpaid'}</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </section>

      <div className="r-two">
        <section className="card">
          <header className="card-head"><div className="card-head-left"><Icon name="warn" size={16} stroke={2}/><h2>Aging — outstanding royalty</h2></div></header>
          <ul className="bar-list">
            {[['0–7 days', 1200, '#16A34A'],['8–14 days', 2200, '#F59E0B'],['15–30 days', 1853, '#F97316'],['31+ days', 0, '#DC2626']].map(([label, val, color]) => (
              <li key={label}>
                <div className="bar-list-head">
                  <div><div className="bar-list-name">{label}</div><div className="bar-list-sub">{val === 0 ? 'No bucket' : 'Across 2 shops'}</div></div>
                  <div className="bar-list-val">{fmtMoneyFull(val)}</div>
                </div>
                <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: (val / 2200 * 100) + '%', background: color }}/></div>
              </li>
            ))}
          </ul>
        </section>
        <section className="card">
          <header className="card-head"><div className="card-head-left"><Icon name="warn" size={16} stroke={2}/><h2>Disputes & adjustments</h2></div></header>
          <ul className="stub-list">
            <li><b>Scarborough</b> · disputes $2,248 — reporting May 1–7 net sales as "training day discounts excluded". Review franchise agreement §8.2.</li>
            <li><b>Richmond Hill</b> · overdue 11d — auto-debit failed twice (NSF). Manual collection in progress.</li>
            <li><b>Brampton</b> · 7% rate exception in agreement (vs default 6.5%). Confirmed correct.</li>
            <li><b>Markham</b> · 4d late this period, on time 5 of last 6. Trending OK.</li>
          </ul>
        </section>
      </div>
    </React.Fragment>
  );
};

// Customers tab — network retention/churn rollup
const CustomersTab = () => (
  <React.Fragment>
    <div className="r-kpi-grid">
      <ReportKpi label="Total clients"           value="38,640" delta="+1,240 this month" deltaPositive/>
      <ReportKpi label="Active loyalty members"  value="15,840" delta="41% penetration" deltaPositive/>
      <ReportKpi label="Avg client lifetime $"   value="$412"   delta="+8.0% YoY" deltaPositive/>
      <ReportKpi label="Network churn"           value="6.8%"   delta="2 shops above 10%" deltaPositive={false}/>
    </div>
    <section className="card">
      <header className="card-head"><div className="card-head-left"><Icon name="users" size={16} stroke={2}/><h2>Retention by cohort — last 12 months</h2><span className="r-kpi-ai">✨ AI</span></div></header>
      <div className="r-retention-grid">
        <div className="r-retention-row r-retention-head">
          <div>Acquisition month</div>
          {[1,2,3,4,5,6,7,8,9,10,11,12].map(m => <div key={m} className="r-ret-month">M{m}</div>)}
        </div>
        {['May 25','Apr 25','Mar 25','Feb 25','Jan 25','Dec 24','Nov 24','Oct 24'].map((mo, i) => (
          <div key={mo} className="r-retention-row">
            <div className="r-ret-label">{mo}</div>
            {Array.from({ length: 12 }, (_, m) => {
              if (m < i) return <div key={m} className="r-ret-cell r-ret-empty"></div>;
              const v = Math.max(20, 100 - (m - i) * (6 + i * 0.4));
              const bg = `oklch(${(0.45 + (v/100) * 0.4).toFixed(2)} 0.10 165)`;
              return <div key={m} className="r-ret-cell" style={{ background: bg, color: v > 60 ? '#fff' : '#0F172A' }}>{Math.round(v)}%</div>;
            })}
          </div>
        ))}
      </div>
    </section>
  </React.Fragment>
);

// Finance tab — corporate vs franchise separation (gap #8)
const FinanceTab = () => (
  <React.Fragment>
    <div className="r-kpi-grid">
      <ReportKpi label="Corporate revenue (MTD)" value="$162K" delta="2 corporate shops" ai={false}/>
      <ReportKpi label="Franchisee gross sales"  value="$650K" delta="8 franchised shops" ai={false}/>
      <ReportKpi label="Royalty income"          value="$55.7K" delta="+11.2% YoY" deltaPositive ai={false}/>
      <ReportKpi label="Marketing fund (2%)"     value="$13.0K" delta="Collected" deltaPositive ai={false}/>
      <ReportKpi label="Vendor rebates"          value="$4.2K"  delta="From Northbridge + ProEdge" ai={false}/>
      <ReportKpi label="Platform subscription"   value="$8.4K"  delta="$1,050/shop/mo" ai={false}/>
      <ReportKpi label="Training & support fees" value="$2.1K"  delta="3 onboardings" ai={false}/>
      <ReportKpi label="Corporate operating $"   value="$184K"  delta="22.6% margin" deltaPositive ai={false}/>
    </div>
    <section className="card">
      <header className="card-head"><div className="card-head-left"><Icon name="dollar" size={16} stroke={2}/><h2>Corporate vs Franchise income</h2><InfoDot tip="Franchise CEOs need to see corporate-owned vs franchised income separated. Different mental models for both — corp is full P&L, franchised is royalty + fund + rebates."/></div></header>
      <table className="lb-table cat-table">
        <thead>
          <tr>
            <th>Line</th>
            <th className="num">Corporate (2 shops)</th>
            <th className="num">Franchise (8 shops)</th>
            <th className="num">Combined</th>
          </tr>
        </thead>
        <tbody>
          <tr><td>Gross sales (reported)</td><td className="num">$162,400</td><td className="num">$650,000</td><td className="num strong">$812,400</td></tr>
          <tr><td>Royalty income</td><td className="num muted">—</td><td className="num">$55,731</td><td className="num strong">$55,731</td></tr>
          <tr><td>Marketing fund (2%)</td><td className="num muted">—</td><td className="num">$13,000</td><td className="num strong">$13,000</td></tr>
          <tr><td>Vendor rebates</td><td className="num">$840</td><td className="num">$3,360</td><td className="num strong">$4,200</td></tr>
          <tr><td>Platform subscription</td><td className="num muted">—</td><td className="num">$8,400</td><td className="num strong">$8,400</td></tr>
          <tr><td>Training & support fees</td><td className="num muted">—</td><td className="num">$2,100</td><td className="num strong">$2,100</td></tr>
          <tr style={{ background:'#F8FAFC' }}><td className="strong">Operating revenue to HQ</td><td className="num strong">$163,240</td><td className="num strong">$82,591</td><td className="num strong" style={{ color:'#16A34A' }}>$895,231</td></tr>
        </tbody>
      </table>
    </section>
  </React.Fragment>
);

// Vendor tab — vendor spend rollup
const VendorTab = () => (
  <React.Fragment>
    <div className="r-kpi-grid">
      <ReportKpi label="Total vendor spend (MTD)" value="$23.7K" delta="7 active vendors" ai={false}/>
      <ReportKpi label="Concentration top 1"      value="35.5%"  delta="Northbridge — single-vendor risk" deltaPositive={false} ai={false}/>
      <ReportKpi label="On-time delivery"         value="89.8%"  delta="1 vendor under SLA" deltaPositive={false} ai={false}/>
      <ReportKpi label="Open POs"                 value="8"      delta="$14.3K total" ai={false}/>
    </div>
    <section className="card">
      <header className="card-head"><div className="card-head-left"><Icon name="box" size={16} stroke={2}/><h2>Vendor spend by category</h2></div></header>
      <ul className="bar-list">
        {[
          { name:'Northbridge Beauty Wholesale', spend:8420, pct:35.5, color:'#16A34A' },
          { name:'Atlas Salon Supply',           spend:6240, pct:26.3, color:'#0EA5E9' },
          { name:'ProEdge Distribution',         spend:4180, pct:17.6, color:'#A855F7' },
          { name:'MZ Trading',                   spend:2360, pct: 9.9, color:'#F97316' },
          { name:'Maple Grooming Imports',         spend:1840, pct: 7.8, color:'#EAB308' },
          { name:'Richmond Hill Local Supply',        spend: 680, pct: 2.9, color:'#94A3B8' },
        ].map(v => (
          <li key={v.name}>
            <div className="bar-list-head">
              <div><div className="bar-list-name">{v.name}</div><div className="bar-list-sub">{v.pct}% of vendor spend</div></div>
              <div className="bar-list-val">{fmtMoneyFull(v.spend)}</div>
            </div>
            <div className="bar-list-bar"><div className="bar-list-fill" style={{ width: (v.pct/35.5*100) + '%', background: v.color }}/></div>
          </li>
        ))}
      </ul>
    </section>
  </React.Fragment>
);

// Cohort tab — gap #9
const CohortTab = () => {
  const max = (key) => Math.max(...COHORTS.map(c => c[key]));
  return (
    <React.Fragment>
      <div className="r-kpi-grid">
        <ReportKpi label="Top vs Bottom quartile" value="42.9%" delta="Gap in $/booked hr" deltaPositive={false}/>
        <ReportKpi label="Corporate vs Franchise" value="13.8%" delta="$/booked hr difference"/>
        <ReportKpi label="Mature vs New"          value="13.5%" delta="$/booked hr difference"/>
        <ReportKpi label="Median rev/hr (mature)" value="$60.40" delta="Per booked chair-hour" ai={false}/>
      </div>
      <section className="card">
        <header className="card-head"><div className="card-head-left"><Icon name="chart" size={16} stroke={2}/><h2>Cohort benchmarks</h2><InfoDot tip="Compare segments side-by-side so insights are credible. 'Scarborough is underperforming' becomes 'Scarborough is 28% below shops of similar age'."/></div></header>
        <table className="lb-table cat-table">
          <thead>
            <tr>
              <th>Cohort</th>
              <th className="num">Rev / booked hr</th>
              <th className="num">Utilization</th>
              <th className="num">NPS</th>
              <th className="num">Rebook</th>
              <th className="num">Retention</th>
            </tr>
          </thead>
          <tbody>
            {COHORTS.map(c => (
              <tr key={c.scope}>
                <td><div className="lb-name">{c.label}</div></td>
                <td className="num">${c.revPerHour.toFixed(2)}</td>
                <td className="num">{c.util.toFixed(1)}%</td>
                <td className="num"><span className={'nps-chip ' + (c.nps >= 70 ? 'good' : c.nps >= 65 ? 'mid' : 'low')}>{c.nps}</span></td>
                <td className="num">{c.rebook}%</td>
                <td className="num">{c.retention}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </React.Fragment>
  );
};

// P&L tab — Network operating P&L
const PLTab = () => (
  <React.Fragment>
    <div className="r-kpi-grid">
      <ReportKpi label="Network revenue"   value="$895K"  delta="+11.2% YoY" deltaPositive ai={false}/>
      <ReportKpi label="Cost of goods"     value="$184K"  delta="20.5% of revenue" ai={false}/>
      <ReportKpi label="Payroll"           value="$284K"  delta="31.7% of revenue" deltaPositive={false} ai={false}/>
      <ReportKpi label="Operating profit"  value="$184K"  delta="20.6% margin" deltaPositive ai={false}/>
    </div>
    <section className="card">
      <header className="card-head"><div className="card-head-left"><Icon name="chart" size={16} stroke={2}/><h2>Operating P&L — Month to Date</h2></div></header>
      <table className="lb-table cat-table">
        <thead><tr><th>Line</th><th className="num">Amount</th><th className="num">% of revenue</th></tr></thead>
        <tbody>
          <tr><td>Service revenue</td><td className="num">$698,200</td><td className="num">78.0%</td></tr>
          <tr><td>Retail revenue</td><td className="num">$114,200</td><td className="num">12.8%</td></tr>
          <tr><td>Royalty income</td><td className="num">$55,731</td><td className="num">6.2%</td></tr>
          <tr><td>Marketing fund + fees</td><td className="num">$27,300</td><td className="num">3.0%</td></tr>
          <tr style={{ background:'#F8FAFC' }}><td className="strong">Total revenue</td><td className="num strong">$895,431</td><td className="num strong">100.0%</td></tr>
          <tr><td>Cost of goods sold</td><td className="num" style={{ color:'#DC2626' }}>($184,200)</td><td className="num">20.5%</td></tr>
          <tr><td>Payroll & commissions</td><td className="num" style={{ color:'#DC2626' }}>($284,400)</td><td className="num">31.7%</td></tr>
          <tr><td>Rent & occupancy</td><td className="num" style={{ color:'#DC2626' }}>($112,800)</td><td className="num">12.6%</td></tr>
          <tr><td>Marketing</td><td className="num" style={{ color:'#DC2626' }}>($48,600)</td><td className="num">5.4%</td></tr>
          <tr><td>G&A + tech</td><td className="num" style={{ color:'#DC2626' }}>($81,400)</td><td className="num">9.1%</td></tr>
          <tr style={{ background:'#F0FDF4' }}><td className="strong">Operating profit</td><td className="num strong" style={{ color:'#16A34A' }}>$184,031</td><td className="num strong" style={{ color:'#16A34A' }}>20.6%</td></tr>
        </tbody>
      </table>
    </section>
  </React.Fragment>
);

// ═══════════════════════════════════════════════════════════════════════
// MAIN PAGE
// ═══════════════════════════════════════════════════════════════════════
const ReportsPage = () => {
  const [tab, setTab] = React.useState('overview');
  const [period, setPeriod] = React.useState('MTD');

  return (
    <div className="page">
      <div className="pageheader">
        <div>
          <h1 className="pageheader-title">Reports & Insights</h1>
          <p className="pageheader-sub">Network roll-up: cross-location financials, royalty reconciliation, capacity, customers, vendors, and cohort comparisons.</p>
        </div>
        <div className="pageheader-tools">
          <div className="r-search">
            <Icon name="search" size={14}/>
            <input placeholder="Search reports…"/>
          </div>
          <div className="pageheader-tool">
            <label>Period</label>
            <div className="seg-group">
              {['T','WTD','MTD','QTD','YTD'].map(p => (
                <button key={p} className={'seg' + (period === p ? ' is-on' : '')} onClick={() => setPeriod(p)}>{p}</button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <ReportTabs tab={tab} setTab={setTab}/>

      {tab === 'overview'  && <OverviewTab period={period}/>}
      {tab === 'sales'     && <SalesTab period={period}/>}
      {tab === 'royalty'   && <RoyaltyTab/>}
      {tab === 'customers' && <CustomersTab/>}
      {tab === 'finance'   && <FinanceTab/>}
      {tab === 'vendor'    && <VendorTab/>}
      {tab === 'cohort'    && <CohortTab/>}
      {tab === 'pl'        && <PLTab/>}
    </div>
  );
};

Object.assign(window, { ReportsPage });
