// BILLING & ANALYTICS — advanced data seeds + ba token namespace
// 18 opportunities × sample data sized for a $400M AmLaw book
(function () {
  const Tb = window.ArbiterTokens;
  const bl = window.__bl;

  // ── ba accent palette (violet = advanced BI / ML layers) ──
  const ba = {
    violet: '#7C3AED', violetDeep: '#6D28D9', violetBg: 'rgba(124,58,237,0.06)', violetBorder: 'rgba(124,58,237,0.22)',
    indigo: '#4338CA', indigoBg: 'rgba(67,56,202,0.06)',
    card: { background: Tb.color.bg.card, border: `1px solid ${Tb.color.border.light}`, borderRadius: Tb.radius.lg, overflow: 'hidden', marginBottom: '16px' },
    cardH: { padding: '10px 16px', borderBottom: `1px solid ${Tb.color.border.light}`, fontSize: '12px', fontWeight: 600, color: Tb.color.text.primary, display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
    subTab: { padding: '8px 14px', fontSize: '11px', fontWeight: 500, color: Tb.color.text.tertiary, background: 'transparent', border: `1px solid ${Tb.color.border.light}`, borderRadius: '6px', cursor: 'pointer', letterSpacing: '0.02em' },
    subTabActive: { background: '#7C3AED', color: '#fff', borderColor: '#7C3AED', fontWeight: 700 },
    btn: { padding: '6px 12px', borderRadius: '6px', border: `1px solid ${Tb.color.border.light}`, background: Tb.color.bg.card, fontSize: '11px', fontWeight: 600, color: Tb.color.text.primary, cursor: 'pointer', letterSpacing: '0.02em' },
    btnPrimary: { padding: '6px 14px', borderRadius: '6px', border: 'none', background: '#7C3AED', color: '#fff', fontSize: '11px', fontWeight: 700, cursor: 'pointer', letterSpacing: '0.04em', textTransform: 'uppercase' },
    btnDanger: { padding: '6px 14px', borderRadius: '6px', border: 'none', background: '#B91C1C', color: '#fff', fontSize: '11px', fontWeight: 700, cursor: 'pointer', letterSpacing: '0.04em', textTransform: 'uppercase' },
  };
  window.ba = ba;

  // ── 1. Passive Time Capture — inferred daily time candidates ──
  const passiveCapture = [
    { id: 'PC-001', date: '2026-04-21', user: 'M. Kirkland', matter: 'M-2026-0042', matterName: 'Redstone v. Meridian', source: 'Outlook meeting', signal: 'Meeting: Redstone prep w/ J. Chen · 1.4h', confidence: 0.96, hours: 1.4, suggestedNarrative: 'Conferred with J. Chen re: deposition preparation and exhibit strategy for Redstone matter.', task: 'L330', activity: 'A104', status: 'pending' },
    { id: 'PC-002', date: '2026-04-21', user: 'M. Kirkland', matter: 'M-2026-0042', matterName: 'Redstone v. Meridian', source: 'Doc edits', signal: '14 edits to MSJ_Brief_v12.docx · 2.8h', confidence: 0.94, hours: 2.8, suggestedNarrative: 'Revised motion for summary judgment brief; incorporated case citations and record references.', task: 'L240', activity: 'A103', status: 'pending' },
    { id: 'PC-003', date: '2026-04-21', user: 'M. Kirkland', matter: 'M-2026-0087', matterName: 'Apex Data Breach', source: 'Call log', signal: 'Call with GC Taylor · 0.7h', confidence: 0.88, hours: 0.7, suggestedNarrative: 'Telephone conference with client general counsel regarding breach notification strategy and regulatory timeline.', task: 'L120', activity: 'A106', status: 'pending' },
    { id: 'PC-004', date: '2026-04-21', user: 'J. Chen', matter: 'M-2026-0042', matterName: 'Redstone v. Meridian', source: 'Nexus research', signal: '9 queries · 3 saved · 1.9h', confidence: 0.91, hours: 1.9, suggestedNarrative: 'Researched Second Circuit authority on contract repudiation and anticipatory breach doctrines.', task: 'L110', activity: 'A102', status: 'pending' },
    { id: 'PC-005', date: '2026-04-20', user: 'M. Kirkland', matter: 'M-2025-0091', matterName: 'Pacific Shipping Antitrust', source: 'Outlook email', signal: '7 client emails · 0.6h', confidence: 0.82, hours: 0.6, suggestedNarrative: 'Corresponded with client regarding DOJ second request response coordination.', task: 'L330', activity: 'A101', status: 'pending' },
    { id: 'PC-006', date: '2026-04-20', user: 'S. Patel', matter: 'M-2026-0087', matterName: 'Apex Data Breach', source: 'Doc review (Discovery)', signal: '412 docs coded · 4.2h', confidence: 0.97, hours: 4.2, suggestedNarrative: 'Conducted privilege review of custodian production; coded documents for responsiveness and privilege.', task: 'L320', activity: 'A104', status: 'pending' },
    { id: 'PC-007', date: '2026-04-19', user: 'J. Chen', matter: 'M-2026-0042', matterName: 'Redstone v. Meridian', source: 'Calendar + doc', signal: 'Depo prep session · 2.1h', confidence: 0.89, hours: 2.1, suggestedNarrative: 'Prepared deposition outline and witness preparation notes for 30(b)(6) deposition of Meridian CFO.', task: 'L330', activity: 'A104', status: 'approved' },
  ];

  // ── 2. OCG Compliance — client billing guideline rules ──
  const ocgRules = [
    { id: 'OCG-001', client: 'Redstone Capital LLC', rule: 'Block-billing prohibited', detail: 'Each narrative must describe a single discrete task.', severity: 'critical', autoBlock: true },
    { id: 'OCG-002', client: 'Redstone Capital LLC', rule: 'Minimum 0.1h increments', detail: 'No rounding above tenth-of-hour.', severity: 'high', autoBlock: true },
    { id: 'OCG-003', client: 'Redstone Capital LLC', rule: 'No partners on doc review', detail: 'Task code L320 billed by partners requires pre-approval.', severity: 'critical', autoBlock: true },
    { id: 'OCG-004', client: 'Apex Industries Inc.', rule: 'Task & activity codes required', detail: 'Every entry must carry UTBMS task code and activity code.', severity: 'critical', autoBlock: true },
    { id: 'OCG-005', client: 'Apex Industries Inc.', rule: 'Associate rate cap $650/hr', detail: 'No associate may exceed $650/hr regardless of class year.', severity: 'high', autoBlock: true },
    { id: 'OCG-006', client: 'Apex Industries Inc.', rule: 'Travel time at 50%', detail: 'Non-working travel billed at 50%.', severity: 'medium', autoBlock: false },
    { id: 'OCG-007', client: 'Pacific Shipping Co.', rule: 'Monthly invoicing required', detail: 'Invoices must be submitted within 30 days of month close.', severity: 'high', autoBlock: false },
    { id: 'OCG-008', client: 'Pacific Shipping Co.', rule: 'No research over 2h without pre-approval', detail: 'L110 > 2h requires written client consent.', severity: 'high', autoBlock: true },
    { id: 'OCG-009', client: 'Nordic Bank AG', rule: 'Staffing limit: 4 timekeepers', detail: 'No more than 4 active timekeepers per matter.', severity: 'critical', autoBlock: true },
    { id: 'OCG-010', client: 'Nordic Bank AG', rule: 'No travel charges', detail: 'Firm absorbs all travel.', severity: 'critical', autoBlock: true },
  ];
  const ocgViolations = [
    { id: 'OCGV-001', entryId: 'TE-2204', client: 'Redstone Capital LLC', timekeeper: 'M. Kirkland', rule: 'OCG-001', detail: 'Narrative contains 3 discrete tasks', value: 2800, status: 'flagged' },
    { id: 'OCGV-002', entryId: 'TE-2207', client: 'Apex Industries Inc.', timekeeper: 'J. Chen', rule: 'OCG-005', detail: 'Associate rate $715/hr exceeds cap of $650', value: 4290, status: 'flagged' },
    { id: 'OCGV-003', entryId: 'TE-2212', client: 'Pacific Shipping Co.', timekeeper: 'S. Patel', rule: 'OCG-008', detail: 'Research block of 3.4h lacks pre-approval', value: 2380, status: 'flagged' },
    { id: 'OCGV-004', entryId: 'TE-2218', client: 'Nordic Bank AG', timekeeper: 'T. Rees', rule: 'OCG-010', detail: 'Travel expense $412 submitted', value: 412, status: 'flagged' },
    { id: 'OCGV-005', entryId: 'TE-2221', client: 'Redstone Capital LLC', timekeeper: 'M. Kirkland', rule: 'OCG-003', detail: 'Partner L320 doc review without approval', value: 1900, status: 'resolved' },
  ];

  // ── 3. Narrative Intelligence ──
  const narrativeFlags = [
    { id: 'NAR-001', entryId: 'TE-2301', original: 'Reviewed documents.', issue: 'Vague', severity: 'high', suggestion: 'Reviewed production documents from custodian [Name] regarding [subject matter]; coded for responsiveness and privilege.' },
    { id: 'NAR-002', entryId: 'TE-2304', original: 'Worked on brief.', issue: 'Vague + future tense', severity: 'high', suggestion: 'Drafted Section III(B) of MSJ brief addressing [legal theory]; incorporated [N] record citations.' },
    { id: 'NAR-003', entryId: 'TE-2308', original: 'Call with client; reviewed emails; drafted memo; attended meeting.', issue: 'Block billing — 4 tasks', severity: 'critical', suggestion: 'Split into 4 separate entries per client OCG.' },
    { id: 'NAR-004', entryId: 'TE-2311', original: 'Research re: contract issues.', issue: 'Missing specificity', severity: 'medium', suggestion: 'Researched [state] law on [specific doctrine] re: contract issues raised in Count II.' },
    { id: 'NAR-005', entryId: 'TE-2315', original: 'Preparing for hearing.', issue: 'Present-continuous tense prohibited', severity: 'medium', suggestion: 'Prepared for preliminary injunction hearing; outlined argument and reviewed exhibits.' },
  ];

  // ── 4. Rate Card Architect ──
  const rateCards = [
    { id: 'RC-STD-2026', name: 'Standard 2026', effective: '2026-01-01', tier: 'standard', tiers: [
      { role: 'Senior Partner', rate: 1450 }, { role: 'Partner', rate: 1180 }, { role: 'Counsel', rate: 895 },
      { role: 'Senior Associate', rate: 745 }, { role: 'Mid Associate', rate: 625 }, { role: 'Jr Associate', rate: 485 },
      { role: 'Paralegal', rate: 345 },
    ]},
    { id: 'RC-REDSTONE', name: 'Redstone Capital LLC', effective: '2026-01-01', tier: 'client', parent: 'RC-STD-2026', client: 'Redstone Capital LLC', discount: 0.08, tiers: [
      { role: 'Senior Partner', rate: 1334 }, { role: 'Partner', rate: 1086 }, { role: 'Counsel', rate: 823 },
      { role: 'Senior Associate', rate: 686 }, { role: 'Mid Associate', rate: 575 }, { role: 'Jr Associate', rate: 446 },
      { role: 'Paralegal', rate: 317 },
    ]},
    { id: 'RC-APEX', name: 'Apex Industries Inc.', effective: '2026-01-01', tier: 'client', parent: 'RC-STD-2026', client: 'Apex Industries Inc.', discount: 0.12, capAssociate: 650, tiers: [
      { role: 'Senior Partner', rate: 1276 }, { role: 'Partner', rate: 1038 }, { role: 'Counsel', rate: 788 },
      { role: 'Senior Associate', rate: 650 }, { role: 'Mid Associate', rate: 550 }, { role: 'Jr Associate', rate: 427 },
      { role: 'Paralegal', rate: 304 },
    ]},
    { id: 'RC-PAC', name: 'Pacific Shipping Co.', effective: '2026-01-01', tier: 'client', parent: 'RC-STD-2026', client: 'Pacific Shipping Co.', discount: 0.15, tiers: [
      { role: 'Senior Partner', rate: 1233 }, { role: 'Partner', rate: 1003 }, { role: 'Counsel', rate: 761 },
      { role: 'Senior Associate', rate: 633 }, { role: 'Mid Associate', rate: 531 }, { role: 'Jr Associate', rate: 412 },
      { role: 'Paralegal', rate: 293 },
    ]},
  ];
  const rateChangeRequests = [
    { id: 'RCR-001', rateCard: 'RC-STD-2026', proposal: '+4% across all tiers', effective: '2027-01-01', impact: 14200000, clientsAffected: 42, status: 'pending approval', proposedBy: 'Finance Committee' },
    { id: 'RCR-002', rateCard: 'RC-APEX', proposal: 'Raise associate cap from $650 to $685', effective: '2027-01-01', impact: 820000, clientsAffected: 1, status: 'drafting', proposedBy: 'M. Kirkland' },
  ];

  // ── 5. Rate Raise Simulator — scenarios ──
  const rateRaiseScenarios = [
    { label: 'Conservative', raisePct: 3, pushbackProb: 0.12, expectedRealization: 89.2, netRevenueDelta: 9800000, collectionLagDays: 2 },
    { label: 'Firm Proposal', raisePct: 4, pushbackProb: 0.22, expectedRealization: 87.8, netRevenueDelta: 12400000, collectionLagDays: 4 },
    { label: 'Aggressive', raisePct: 6, pushbackProb: 0.41, expectedRealization: 84.1, netRevenueDelta: 14900000, collectionLagDays: 9 },
    { label: 'Peer-Matched', raisePct: 5, pushbackProb: 0.29, expectedRealization: 86.5, netRevenueDelta: 13800000, collectionLagDays: 6 },
  ];

  // ── 6. Matter Pricing Engine — historical benchmarks ──
  const pricingBenchmarks = [
    { matterType: 'Securities Class Action Defense', medianFee: 8400000, p25: 5200000, p75: 14800000, avgDurationMos: 22, winRateByPrice: [
      { priceIndex: 0.7, winProb: 0.84 }, { priceIndex: 0.9, winProb: 0.71 }, { priceIndex: 1.0, winProb: 0.62 }, { priceIndex: 1.15, winProb: 0.41 }, { priceIndex: 1.3, winProb: 0.22 },
    ], recommendedStaffing: 'Lead partner + 2 counsel + 4 associates + 2 paralegals' },
    { matterType: 'M&A — Public Buyer $1-5B', medianFee: 4200000, p25: 2800000, p75: 6100000, avgDurationMos: 6, winRateByPrice: [
      { priceIndex: 0.7, winProb: 0.88 }, { priceIndex: 0.9, winProb: 0.74 }, { priceIndex: 1.0, winProb: 0.66 }, { priceIndex: 1.15, winProb: 0.48 }, { priceIndex: 1.3, winProb: 0.29 },
    ], recommendedStaffing: 'Lead partner + 1 counsel + 3 associates' },
    { matterType: 'Antitrust/DOJ Second Request', medianFee: 12200000, p25: 7800000, p75: 18400000, avgDurationMos: 14, winRateByPrice: [
      { priceIndex: 0.7, winProb: 0.82 }, { priceIndex: 0.9, winProb: 0.68 }, { priceIndex: 1.0, winProb: 0.59 }, { priceIndex: 1.15, winProb: 0.38 }, { priceIndex: 1.3, winProb: 0.19 },
    ], recommendedStaffing: 'Lead partner + 3 counsel + 6 associates + 3 paralegals + econ expert' },
    { matterType: 'Patent Infringement Defense', medianFee: 6800000, p25: 4100000, p75: 11200000, avgDurationMos: 26, winRateByPrice: [
      { priceIndex: 0.7, winProb: 0.79 }, { priceIndex: 0.9, winProb: 0.66 }, { priceIndex: 1.0, winProb: 0.57 }, { priceIndex: 1.15, winProb: 0.36 }, { priceIndex: 1.3, winProb: 0.18 },
    ], recommendedStaffing: 'Lead partner + 2 counsel + 3 associates + tech advisor' },
  ];

  // ── 7. Pre-Bill Command Center ──
  const preBillIssues = [
    { id: 'PB-001', invoice: 'INV-2026-0912', client: 'Redstone Capital LLC', matter: 'Redstone v. Meridian', type: 'Block billing', severity: 'critical', entries: 4, value: 11200, action: 'Split entries' },
    { id: 'PB-002', invoice: 'INV-2026-0912', client: 'Redstone Capital LLC', matter: 'Redstone v. Meridian', type: 'Vague narrative', severity: 'high', entries: 7, value: 9800, action: 'Rewrite narratives' },
    { id: 'PB-003', invoice: 'INV-2026-0918', client: 'Apex Industries Inc.', matter: 'Apex Data Breach', type: 'Rate cap exceeded', severity: 'critical', entries: 12, value: 14820, action: 'Apply cap or write-down' },
    { id: 'PB-004', invoice: 'INV-2026-0921', client: 'Pacific Shipping Co.', matter: 'Pacific Shipping Antitrust', type: 'OCG staffing violation', severity: 'high', entries: 3, value: 8200, action: 'Reassign or approve' },
    { id: 'PB-005', invoice: 'INV-2026-0924', client: 'Nordic Bank AG', matter: 'Nordic Regulatory Review', type: 'Task-code mismatch', severity: 'medium', entries: 5, value: 3400, action: 'Reclassify' },
    { id: 'PB-006', invoice: 'INV-2026-0927', client: 'Titan Logistics', matter: 'Titan Employment Class', type: 'Hour outlier (>8h/day)', severity: 'medium', entries: 2, value: 2800, action: 'Verify with timekeeper' },
    { id: 'PB-007', invoice: 'INV-2026-0931', client: 'Redstone Capital LLC', matter: 'Redstone v. Meridian', type: 'Weekend work unauthorized', severity: 'medium', entries: 3, value: 4200, action: 'Request authorization' },
    { id: 'PB-008', invoice: 'INV-2026-0934', client: 'Apex Industries Inc.', matter: 'Apex IP Portfolio', type: 'Partner on L320', severity: 'high', entries: 6, value: 7640, action: 'Reassign to associate' },
  ];

  // ── 8. eBilling Super-Connector ──
  const ebillingVendors = [
    { id: 'EB-TYM', name: 'Tymetrix 360', client: 'Apex Industries Inc.', format: 'LEDES 98BI v2', connected: true, lastSync: '2026-04-22 08:14' },
    { id: 'EB-LT', name: 'LegalTracker (Thomson)', client: 'Redstone Capital LLC', format: 'LEDES 98B', connected: true, lastSync: '2026-04-22 07:48' },
    { id: 'EB-CL', name: 'CounselLink', client: 'Pacific Shipping Co.', format: 'LEDES XML 2.1', connected: true, lastSync: '2026-04-22 09:02' },
    { id: 'EB-PSP', name: 'Passport', client: 'Titan Logistics', format: 'LEDES 98B', connected: true, lastSync: '2026-04-21 16:30' },
    { id: 'EB-SER', name: 'Serengeti', client: 'Nordic Bank AG', format: 'LEDES XML 2.0', connected: false, lastSync: null },
    { id: 'EB-CLB', name: 'Collaborati', client: 'Mercer Insurance', format: 'LEDES 98BI', connected: true, lastSync: '2026-04-20 11:15' },
    { id: 'EB-TC', name: 'TeamConnect', client: 'Titan Logistics', format: 'LEDES XML 2.1', connected: true, lastSync: '2026-04-22 06:40' },
    { id: 'EB-ONT', name: 'Onit', client: 'Apex Industries Inc.', format: 'LEDES XML 2.1', connected: true, lastSync: '2026-04-22 08:02' },
  ];
  const ebillingSubmissions = [
    { id: 'EBS-001', invoice: 'INV-2026-0841', vendor: 'Tymetrix 360', client: 'Apex Industries Inc.', submitted: '2026-04-10', amount: 412800, status: 'Paid', reduction: 0 },
    { id: 'EBS-002', invoice: 'INV-2026-0847', vendor: 'LegalTracker', client: 'Redstone Capital LLC', submitted: '2026-04-12', amount: 389200, status: 'Paid', reduction: 0 },
    { id: 'EBS-003', invoice: 'INV-2026-0852', vendor: 'CounselLink', client: 'Pacific Shipping Co.', submitted: '2026-04-14', amount: 621400, status: 'Reduced', reduction: 24800, reductionReason: 'Rate variance — associate $685 exceeds agreed $650' },
    { id: 'EBS-004', invoice: 'INV-2026-0858', vendor: 'Passport', client: 'Titan Logistics', submitted: '2026-04-16', amount: 182100, status: 'Rejected', reduction: 182100, reductionReason: 'Missing pre-approval for experts' },
    { id: 'EBS-005', invoice: 'INV-2026-0862', vendor: 'Tymetrix 360', client: 'Apex Industries Inc.', submitted: '2026-04-18', amount: 298400, status: 'Pending', reduction: 0 },
    { id: 'EBS-006', invoice: 'INV-2026-0867', vendor: 'Onit', client: 'Apex Industries Inc.', submitted: '2026-04-19', amount: 334200, status: 'Appealed', reduction: 18400, reductionReason: 'Block-billing — 14 entries flagged' },
  ];

  // ── 9. Joint-Rep / Multi-Entity ──
  const jointMatters = [
    { id: 'JM-001', matter: 'Helios Semiconductor IPO', parties: [
      { entity: 'Helios Holdings Inc.', allocPct: 60, allocBasis: 'revenue' },
      { entity: 'Helios Asia Pte Ltd', allocPct: 28, allocBasis: 'revenue', currency: 'SGD' },
      { entity: 'Helios Europe GmbH', allocPct: 12, allocBasis: 'revenue', currency: 'EUR' },
    ], ytdFees: 4120000, ytdCosts: 218000 },
    { id: 'JM-002', matter: 'Titan-Apex Joint Defense', parties: [
      { entity: 'Titan Logistics', allocPct: 50, allocBasis: 'headcount' },
      { entity: 'Apex Industries Inc.', allocPct: 50, allocBasis: 'headcount' },
    ], ytdFees: 1840000, ytdCosts: 94000 },
    { id: 'JM-003', matter: 'Nordic Cross-Border Merger', parties: [
      { entity: 'Nordic Bank AG', allocPct: 45, allocBasis: 'asset', currency: 'EUR' },
      { entity: 'Nordic Finance UK Ltd', allocPct: 35, allocBasis: 'asset', currency: 'GBP' },
      { entity: 'Nordic US Inc.', allocPct: 20, allocBasis: 'asset' },
    ], ytdFees: 2980000, ytdCosts: 142000 },
  ];

  // ── 10. AR Intelligence ──
  const arPredictions = [
    { client: 'Redstone Capital LLC', outstanding: 1482000, predictedDaysToPay: 42, historicalAvg: 38, riskScore: 'Low', trend: 'stable', collectionAction: 'Standard' },
    { client: 'Apex Industries Inc.', outstanding: 2410000, predictedDaysToPay: 58, historicalAvg: 49, riskScore: 'Moderate', trend: 'slowing', collectionAction: 'Partner call recommended' },
    { client: 'Pacific Shipping Co.', outstanding: 884000, predictedDaysToPay: 71, historicalAvg: 54, riskScore: 'Elevated', trend: 'deteriorating', collectionAction: 'Escalate to GC' },
    { client: 'Titan Logistics', outstanding: 318000, predictedDaysToPay: 112, historicalAvg: 68, riskScore: 'High', trend: 'late-stage', collectionAction: 'Pre-litigation hold' },
    { client: 'Nordic Bank AG', outstanding: 612000, predictedDaysToPay: 35, historicalAvg: 36, riskScore: 'Low', trend: 'stable', collectionAction: 'Standard' },
    { client: 'Mercer Insurance', outstanding: 421000, predictedDaysToPay: 62, historicalAvg: 51, riskScore: 'Moderate', trend: 'slowing', collectionAction: 'Reminder letter' },
    { client: 'Helios Holdings', outstanding: 1120000, predictedDaysToPay: 44, historicalAvg: 41, riskScore: 'Low', trend: 'stable', collectionAction: 'Standard' },
  ];

  // ── 11. WIP Risk Map ──
  const wipRisk = [
    { matter: 'Redstone v. Meridian', client: 'Redstone Capital LLC', wipValue: 2840000, daysAged: 42, writeDownProb: 0.08, cashAccelOpportunity: 1420000, recommendedAction: 'Bill now' },
    { matter: 'Apex Data Breach', client: 'Apex Industries Inc.', wipValue: 1910000, daysAged: 68, writeDownProb: 0.18, cashAccelOpportunity: 1528000, recommendedAction: 'Bill + negotiate' },
    { matter: 'Pacific Shipping Antitrust', client: 'Pacific Shipping Co.', wipValue: 3240000, daysAged: 94, writeDownProb: 0.34, cashAccelOpportunity: 2138400, recommendedAction: 'Review + partner decision' },
    { matter: 'Titan Employment Class', client: 'Titan Logistics', wipValue: 820000, daysAged: 148, writeDownProb: 0.52, cashAccelOpportunity: 393600, recommendedAction: 'Write-down imminent' },
    { matter: 'Nordic Regulatory Review', client: 'Nordic Bank AG', wipValue: 1420000, daysAged: 28, writeDownProb: 0.04, cashAccelOpportunity: 1363200, recommendedAction: 'Bill now' },
    { matter: 'Helios Semiconductor IPO', client: 'Helios Holdings', wipValue: 684000, daysAged: 21, writeDownProb: 0.03, cashAccelOpportunity: 663480, recommendedAction: 'Bill now' },
  ];

  // ── 12. Budget Pacing ──
  const budgetPacing = [
    { matter: 'Redstone v. Meridian', client: 'Redstone Capital LLC', budget: 4500000, spent: 3240000, pctUsed: 72, monthsRemaining: 5, projectedFinal: 4680000, variance: 180000, varPct: 4.0, status: 'Minor overrun', alertLevel: 'amber' },
    { matter: 'Apex Data Breach', client: 'Apex Industries Inc.', budget: 2800000, spent: 2190000, pctUsed: 78.2, monthsRemaining: 3, projectedFinal: 2920000, variance: 120000, varPct: 4.3, status: 'Minor overrun', alertLevel: 'amber' },
    { matter: 'Pacific Shipping Antitrust', client: 'Pacific Shipping Co.', budget: 8500000, spent: 7480000, pctUsed: 88.0, monthsRemaining: 4, projectedFinal: 10200000, variance: 1700000, varPct: 20.0, status: 'Major overrun', alertLevel: 'crimson' },
    { matter: 'Titan Employment Class', client: 'Titan Logistics', budget: 1800000, spent: 1240000, pctUsed: 68.9, monthsRemaining: 6, projectedFinal: 1840000, variance: 40000, varPct: 2.2, status: 'On track', alertLevel: 'emerald' },
    { matter: 'Nordic Regulatory Review', client: 'Nordic Bank AG', budget: 3200000, spent: 1640000, pctUsed: 51.3, monthsRemaining: 7, projectedFinal: 3080000, variance: -120000, varPct: -3.8, status: 'Under budget', alertLevel: 'emerald' },
    { matter: 'Helios Semiconductor IPO', client: 'Helios Holdings', budget: 6500000, spent: 4120000, pctUsed: 63.4, monthsRemaining: 2, projectedFinal: 6580000, variance: 80000, varPct: 1.2, status: 'On track', alertLevel: 'emerald' },
  ];

  // ── 13. Realization Waterfall ──
  const realizationWaterfall = [
    { stage: 'Standard Value (rack)', amount: 184200000, pct: 100 },
    { stage: 'Agreed-Rate Discount', amount: -14800000, pct: -8.0, reason: 'Client-negotiated rates' },
    { stage: 'Worked Value', amount: 169400000, pct: 92.0 },
    { stage: 'Pre-Bill Write-Down', amount: -6200000, pct: -3.4, reason: 'OCG violations, narrative rewrites, staffing adjustments' },
    { stage: 'Billed Value', amount: 163200000, pct: 88.6 },
    { stage: 'eBilling Reductions', amount: -3100000, pct: -1.7, reason: 'Rate variances, unapproved time, rejections' },
    { stage: 'AFA/Cap Overrun (unrecovered)', amount: -1800000, pct: -1.0, reason: '3 matters above cap' },
    { stage: 'Client Courtesy Write-Offs', amount: -2400000, pct: -1.3, reason: 'Relationship & good-will' },
    { stage: 'Collected Value', amount: 155900000, pct: 84.6 },
  ];

  // ── 14. Matter Profitability (fully loaded) ──
  const matterProfitability = [
    { matter: 'Redstone v. Meridian', client: 'Redstone Capital LLC', revenue: 4120000, directCost: 1890000, allocatedOverhead: 620000, totalCost: 2510000, margin: 1610000, marginPct: 39.1, partnerROI: 3.8 },
    { matter: 'Apex Data Breach', client: 'Apex Industries Inc.', revenue: 3280000, directCost: 1540000, allocatedOverhead: 498000, totalCost: 2038000, margin: 1242000, marginPct: 37.9, partnerROI: 3.6 },
    { matter: 'Pacific Shipping Antitrust', client: 'Pacific Shipping Co.', revenue: 7480000, directCost: 4120000, allocatedOverhead: 1218000, totalCost: 5338000, margin: 2142000, marginPct: 28.6, partnerROI: 2.4 },
    { matter: 'Titan Employment Class', client: 'Titan Logistics', revenue: 1240000, directCost: 784000, allocatedOverhead: 238000, totalCost: 1022000, margin: 218000, marginPct: 17.6, partnerROI: 1.4 },
    { matter: 'Nordic Regulatory Review', client: 'Nordic Bank AG', revenue: 1640000, directCost: 742000, allocatedOverhead: 238000, totalCost: 980000, margin: 660000, marginPct: 40.2, partnerROI: 4.2 },
    { matter: 'Helios Semiconductor IPO', client: 'Helios Holdings', revenue: 4120000, directCost: 1840000, allocatedOverhead: 601000, totalCost: 2441000, margin: 1679000, marginPct: 40.8, partnerROI: 4.1 },
  ];
  const clientProfitabilityDecile = [
    { client: 'Redstone Capital LLC', revenue: 22400000, margin: 9180000, marginPct: 41.0, decile: 1 },
    { client: 'Apex Industries Inc.', revenue: 18200000, margin: 6744000, marginPct: 37.1, decile: 2 },
    { client: 'Helios Holdings', revenue: 14800000, margin: 5824000, marginPct: 39.4, decile: 2 },
    { client: 'Pacific Shipping Co.', revenue: 12400000, margin: 3384000, marginPct: 27.3, decile: 4 },
    { client: 'Nordic Bank AG', revenue: 9240000, margin: 3784000, marginPct: 40.9, decile: 1 },
    { client: 'Mercer Insurance', revenue: 5480000, margin: 1684000, marginPct: 30.7, decile: 3 },
    { client: 'Titan Logistics', revenue: 4120000, margin: 614000, marginPct: 14.9, decile: 8 },
  ];

  // ── 15. Lateral & Partner Book ──
  const partnerBook = [
    { partner: 'M. Kirkland', practice: 'Litigation', bookValue: 22400000, bookTrend12mo: [18200000, 19100000, 19800000, 20400000, 20900000, 21400000, 21800000, 22000000, 22200000, 22300000, 22350000, 22400000], clientConcentration: 0.38, flightRisk: 0.08, originationDecay: 0.04, compVsPeer: 'P85' },
    { partner: 'S. Patel', practice: 'Regulatory', bookValue: 14800000, bookTrend12mo: [12400000, 12900000, 13200000, 13600000, 13900000, 14100000, 14300000, 14500000, 14600000, 14700000, 14750000, 14800000], clientConcentration: 0.52, flightRisk: 0.14, originationDecay: 0.09, compVsPeer: 'P72' },
    { partner: 'J. Chen', practice: 'Corporate/M&A', bookValue: 18600000, bookTrend12mo: [21400000, 21100000, 20800000, 20400000, 19900000, 19600000, 19300000, 19100000, 18900000, 18800000, 18700000, 18600000], clientConcentration: 0.41, flightRisk: 0.62, originationDecay: 0.21, compVsPeer: 'P58', alert: 'Declining book, elevated flight risk' },
    { partner: 'T. Rees', practice: 'Finance', bookValue: 9400000, bookTrend12mo: [7800000, 8000000, 8200000, 8400000, 8600000, 8800000, 9000000, 9100000, 9200000, 9300000, 9350000, 9400000], clientConcentration: 0.29, flightRisk: 0.11, originationDecay: 0.06, compVsPeer: 'P78' },
    { partner: 'D. Okafor', practice: 'Litigation', bookValue: 16200000, bookTrend12mo: [14200000, 14500000, 14800000, 15100000, 15400000, 15600000, 15800000, 15900000, 16000000, 16100000, 16150000, 16200000], clientConcentration: 0.31, flightRisk: 0.09, originationDecay: 0.05, compVsPeer: 'P82' },
  ];

  // ── 16. Industry Benchmark Overlay ──
  const industryBenchmarks = [
    { metric: 'Demand Growth (YoY)', firm: 4.2, peerBand: [2.8, 5.1], citigroup: 3.4, wellsFargo: 3.6, peerMonitor: 3.8, assessment: 'Above peer' },
    { metric: 'Rate Growth (YoY)', firm: 6.8, peerBand: [5.4, 7.2], citigroup: 6.1, wellsFargo: 6.4, peerMonitor: 6.6, assessment: 'In peer band' },
    { metric: 'Productivity (hrs/FTE)', firm: 1820, peerBand: [1740, 1860], citigroup: 1782, wellsFargo: 1798, peerMonitor: 1812, assessment: 'Above peer' },
    { metric: 'Expense Growth (YoY)', firm: 5.8, peerBand: [4.1, 6.2], citigroup: 5.2, wellsFargo: 5.4, peerMonitor: 5.6, assessment: 'In peer band' },
    { metric: 'PPP', firm: 3640000, peerBand: [2980000, 3840000], citigroup: 3210000, wellsFargo: 3350000, peerMonitor: 3420000, assessment: 'Above peer' },
    { metric: 'Net Income Margin', firm: 0.412, peerBand: [0.358, 0.438], citigroup: 0.385, wellsFargo: 0.394, peerMonitor: 0.401, assessment: 'Above peer' },
    { metric: 'Collected Realization', firm: 0.846, peerBand: [0.812, 0.884], citigroup: 0.832, wellsFargo: 0.841, peerMonitor: 0.848, assessment: 'In peer band' },
    { metric: 'Inventory Days', firm: 118, peerBand: [102, 142], citigroup: 126, wellsFargo: 121, peerMonitor: 118, assessment: 'In peer band' },
  ];

  // ── 17. Client Concentration & Churn Risk ──
  const churnRisk = [
    { client: 'Redstone Capital LLC', revenue: 22400000, pctOfBook: 11.2, churnProb: 0.08, revenueAtRisk: 1792000, signals: ['Stable billings', 'Engaged partner', 'On-time payment'], status: 'Healthy' },
    { client: 'Apex Industries Inc.', revenue: 18200000, pctOfBook: 9.1, churnProb: 0.18, revenueAtRisk: 3276000, signals: ['Billed hours -12% YoY', 'New GC hired Q1', 'RFP activity detected'], status: 'Watch' },
    { client: 'Pacific Shipping Co.', revenue: 12400000, pctOfBook: 6.2, churnProb: 0.34, revenueAtRisk: 4216000, signals: ['Matter mix shifting off core', 'AR 91+ increasing', 'Partner relationship strain'], status: 'At Risk' },
    { client: 'Titan Logistics', revenue: 4120000, pctOfBook: 2.1, churnProb: 0.48, revenueAtRisk: 1977600, signals: ['No new matters Q4', 'AR 120+ days', 'Competitor pitch detected'], status: 'High Risk' },
    { client: 'Nordic Bank AG', revenue: 9240000, pctOfBook: 4.6, churnProb: 0.11, revenueAtRisk: 1016400, signals: ['Stable', 'Recent rate renegotiation'], status: 'Healthy' },
    { client: 'Mercer Insurance', revenue: 5480000, pctOfBook: 2.7, churnProb: 0.22, revenueAtRisk: 1205600, signals: ['Key partner retirement announced', 'Transition plan pending'], status: 'Watch' },
    { client: 'Helios Holdings', revenue: 14800000, pctOfBook: 7.4, churnProb: 0.09, revenueAtRisk: 1332000, signals: ['Growing mandate', 'Positive feedback'], status: 'Healthy' },
  ];

  // ── 18. Executive War Room KPI cockpit ──
  const warRoomKPIs = {
    realization: { value: 84.6, priorYr: 82.1, budget: 85.0, peerBand: [81.2, 88.4] },
    ube: { value: 1820, priorYr: 1784, budget: 1800, peerBand: [1740, 1860] },
    arDays: { value: 68, priorYr: 74, budget: 65, peerBand: [58, 78] },
    pipeline: { value: 142000000, priorYr: 118000000, budget: 135000000, peerBand: [100000000, 160000000] },
    productivity: { value: 92.4, priorYr: 89.8, budget: 91.0, peerBand: [86.0, 94.0] },
    utilization: { value: 78.4, priorYr: 76.2, budget: 78.0, peerBand: [72.0, 81.0] },
    lateralROI: { value: 2.8, priorYr: 2.2, budget: 2.5, peerBand: [1.8, 3.2] },
    pppGrowth: { value: 8.4, priorYr: 5.2, budget: 6.0, peerBand: [3.8, 9.2] },
  };

  window.BILLING_ANALYTICS_DATA = {
    passiveCapture, ocgRules, ocgViolations, narrativeFlags,
    rateCards, rateChangeRequests, rateRaiseScenarios, pricingBenchmarks,
    preBillIssues, ebillingVendors, ebillingSubmissions, jointMatters,
    arPredictions, wipRisk, budgetPacing,
    realizationWaterfall, matterProfitability, clientProfitabilityDecile,
    partnerBook, industryBenchmarks, churnRisk, warRoomKPIs,
  };
})();
