// BILLING & ANALYTICS PLATFORM — entry (header + 8 grouped tabs with sub-navigation)
const { useState: useBlPlatState } = React;
const Tbl = window.ArbiterTokens;

// 8 grouped primary tabs — each with secondary navigation that maps to renderers
const BL_GROUPS = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    single: true,
  },
  {
    id: 'capture',
    label: 'Time & Capture',
    subs: [
      { id: 'timewip',   label: 'Time & WIP' },
      { id: 'passive',   label: 'Passive Capture' },
      { id: 'ocg',       label: 'OCG Compliance' },
      { id: 'narrative', label: 'Narrative Intelligence' },
    ],
  },
  {
    id: 'prebill',
    label: 'Pre-Bill & Invoicing',
    subs: [
      { id: 'pipeline',   label: 'Billing Pipeline' },
      { id: 'prebill-cmd',label: 'Pre-Bill Command' },
      { id: 'invoices',   label: 'Invoices' },
      { id: 'ebilling-sc',label: 'eBilling Connector' },
      { id: 'ebilling',   label: 'eBilling (Classic)' },
      { id: 'jointrep',   label: 'Joint-Rep / Multi-Entity' },
      { id: 'trust',      label: 'Trust' },
    ],
  },
  {
    id: 'rates',
    label: 'Rates & Pricing',
    subs: [
      { id: 'rates-classic',label: 'Rate Cards' },
      { id: 'rate-arch',    label: 'Rate Card Architect' },
      { id: 'rate-sim',     label: 'Rate Raise Simulator' },
      { id: 'matter-pricing', label: 'Matter Pricing Engine' },
      { id: 'afas',         label: 'AFAs' },
    ],
  },
  {
    id: 'cash',
    label: 'Collections & Cash',
    subs: [
      { id: 'collections', label: 'Collections' },
      { id: 'ar-intel',    label: 'AR Intelligence' },
      { id: 'wip-risk',    label: 'WIP Risk Map' },
      { id: 'budget-pace', label: 'Budget Pacing' },
      { id: 'budgets',     label: 'Budgets (Classic)' },
    ],
  },
  {
    id: 'analytics',
    label: 'Analytics',
    subs: [
      { id: 'realization-c', label: 'Realization' },
      { id: 'realization-w', label: 'Realization Waterfall' },
      { id: 'profit-c',      label: 'Profitability' },
      { id: 'profit-matter', label: 'Matter Profitability' },
      { id: 'lateral-book',  label: 'Lateral & Partner Book' },
      { id: 'benchmark',     label: 'Industry Benchmark' },
      { id: 'churn',         label: 'Client Churn Risk' },
      { id: 'forecast',      label: 'Forecast' },
      { id: 'warroom',       label: 'War Room (Ops)' },
    ],
  },
  {
    id: 'strategy',
    label: 'Executive Strategy',
    subs: [
      { id: 'deal',      label: 'Deal Room' },
      { id: 'partner',   label: 'Partner Capital' },
      { id: 'client',    label: 'Client Intelligence' },
      { id: 'market',    label: 'Market Intelligence' },
      { id: 'franchise', label: 'Franchise Risk' },
    ],
  },
  {
    id: 'activity',
    label: 'Activity',
    single: true,
  },
];

// Default sub-tab for each group (first in its list)
const DEFAULT_SUB = BL_GROUPS.reduce((acc, g) => {
  if (!g.single) acc[g.id] = g.subs[0].id;
  return acc;
}, {});

function BillingPlatform() {
  const [activeGroup, setActiveGroup] = useBlPlatState('dashboard');
  const [subByGroup, setSubByGroup] = useBlPlatState(DEFAULT_SUB);
  const bl = window.__bl;
  const data = window.BILLING_DATA;
  const k = data.kpis;

  const group = BL_GROUPS.find(g => g.id === activeGroup);
  const activeSub = group && !group.single ? subByGroup[group.id] : null;

  const renderContent = () => {
    if (activeGroup === 'dashboard')  return <BillingDashboard data={data} />;
    if (activeGroup === 'activity')   return <BillingActivity data={data} />;

    switch (activeSub) {
      // Time & Capture
      case 'timewip':        return <BillingTimeWIP data={data} />;
      case 'passive':        return <window.Ba1Passive />;
      case 'ocg':            return <window.Ba2OcgCompliance />;
      case 'narrative':      return <window.Ba3Narrative />;
      // Pre-Bill & Invoicing
      case 'pipeline':       return <BillingPipeline data={data} />;
      case 'prebill-cmd':    return <window.Ba7PreBill />;
      case 'invoices':       return <BillingInvoices data={data} />;
      case 'ebilling-sc':    return <window.Ba8Ebilling />;
      case 'ebilling':       return <BillingEBilling data={data} />;
      case 'jointrep':       return <window.Ba9JointRep />;
      case 'trust':          return <BillingTrust data={data} />;
      // Rates & Pricing
      case 'rates-classic':  return <BillingRates data={data} />;
      case 'rate-arch':      return <window.Ba4RateCardArchitect />;
      case 'rate-sim':       return <window.Ba5RateRaiseSim />;
      case 'matter-pricing': return <window.Ba6MatterPricing />;
      case 'afas':           return <BillingAFAs data={data} />;
      // Collections & Cash
      case 'collections':    return <BillingCollections data={data} />;
      case 'ar-intel':       return <window.Ba10ArIntel />;
      case 'wip-risk':       return <window.Ba11WipRisk />;
      case 'budget-pace':    return <window.Ba12BudgetPacing />;
      case 'budgets':        return <BillingBudgets data={data} />;
      // Analytics
      case 'realization-c':  return <BillingRealization data={data} />;
      case 'realization-w':  return <window.Ba13Realization />;
      case 'profit-c':       return <BillingProfitability data={data} />;
      case 'profit-matter':  return <window.Ba14Profitability />;
      case 'lateral-book':   return <window.Ba15LateralBook />;
      case 'benchmark':      return <window.Ba16Benchmark />;
      case 'churn':          return <window.Ba17ChurnRisk />;
      case 'forecast':       return <BillingForecast data={data} />;
      case 'warroom':        return <window.Ba18WarRoom />;
      // Executive Strategy
      case 'deal':           return <window.DealRoomHub />;
      case 'partner':        return <window.PartnerCapitalHub />;
      case 'client':         return <window.ClientIntelHub />;
      case 'market':         return <window.MarketIntelHub />;
      case 'franchise':      return <window.FranchiseRiskHub />;
      default: return <BillingDashboard data={data} />;
    }
  };

  // Pill style aligned with other platform sub-navigation (ba.subTab pattern)
  const subTabStyle = (active) => ({
    padding: '8px 14px',
    fontSize: '11px',
    fontWeight: active ? 700 : 500,
    color: active ? '#fff' : Tbl.color.text.tertiary,
    background: active ? bl.emerald : 'transparent',
    border: `1px solid ${active ? bl.emerald : Tbl.color.border.light}`,
    borderRadius: '6px',
    cursor: 'pointer',
    letterSpacing: '0.02em',
    whiteSpace: 'nowrap',
  });

  return (
    <div style={bl.container}>
      <div style={bl.header}>
        <div style={bl.headerTitle}>
          <div style={bl.blIcon}>$</div>
          <div>
            <div style={bl.title}>Billing &amp; Analytics Platform</div>
            <div style={bl.subtitle}>Time &amp; Capture · Pre-Bill &amp; Invoicing · Rates · Collections · Analytics · Executive Strategy</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: Tbl.color.bg.secondary, border: `1px solid ${Tbl.color.border.light}` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: Tbl.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>YTD Billed</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: Tbl.color.text.primary, fontFamily: Tbl.font.mono }}>{bl.money(k.ytdBilled)}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: bl.emeraldBg, border: `1px solid ${bl.emeraldBorder}` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: bl.emerald, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Realization</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: bl.emerald, fontFamily: Tbl.font.mono }}>{k.realizationOverall}%</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: bl.amberBg, border: `1px solid ${bl.amber}22` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: bl.amber, textTransform: 'uppercase', letterSpacing: '0.06em' }}>AR 91+</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: bl.amber, fontFamily: Tbl.font.mono }}>{bl.money(k.arOver90)}</span>
          </div>
          {k.trustAlerts > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: bl.crimsonBg, border: `1px solid ${bl.crimson}22` }}>
              <span style={{ fontSize: '10px', fontWeight: 600, color: bl.crimson, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Trust alerts</span>
              <span style={{ fontSize: '14px', fontWeight: 700, color: bl.crimson, fontFamily: Tbl.font.mono }}>{k.trustAlerts}</span>
            </div>
          )}
          <button style={bl.btnPrimary}>+ New invoice</button>
        </div>
      </div>

      {/* PRIMARY TABS — 8 groups */}
      <div style={{ ...bl.tabs, overflowX: 'auto' }}>
        {BL_GROUPS.map(g => (
          <button key={g.id} onClick={() => setActiveGroup(g.id)}
            style={{ ...bl.tab, ...(activeGroup === g.id ? bl.tabActive : {}) }}>
            {g.label}
          </button>
        ))}
      </div>

      {/* SECONDARY SUB-TABS — pill style aligned with platform convention */}
      {group && !group.single && (
        <div style={{ display: 'flex', gap: '8px', padding: '14px 20px 2px', flexWrap: 'wrap', borderBottom: `1px solid ${Tbl.color.border.light}` }}>
          {group.subs.map(s => (
            <button key={s.id} onClick={() => setSubByGroup({ ...subByGroup, [group.id]: s.id })}
              style={subTabStyle(activeSub === s.id)}>
              {s.label}
            </button>
          ))}
        </div>
      )}

      <div style={bl.body}>
        {renderContent()}
      </div>
    </div>
  );
}

window.BillingPlatform = BillingPlatform;
