// BILLING PLATFORM — AFAs + Forecast + eBilling + Activity
const Tba = window.ArbiterTokens;

function BillingAFAs({ data }) {
  const bl = window.__bl;
  const active = data.afas.filter(a => a.status === 'Active');
  const totalCapped = active.filter(a => a.cap).reduce((s, a) => s + a.cap, 0);
  const totalWorked = active.reduce((s, a) => s + a.worked, 0);
  const totalBilled = active.reduce((s, a) => s + a.billed, 0);

  const typeColor = (t) => ({
    'Capped Fee': { bg: bl.violetBg, color: bl.violet },
    'Fixed Fee': { bg: bl.emeraldBg, color: bl.emerald },
    'Contingency + Hourly': { bg: bl.crimsonBg, color: bl.crimson },
    'Hourly + Success Fee': { bg: bl.amberBg, color: bl.amber },
    'Subscription': { bg: bl.tealBg, color: bl.teal },
  }[t] || { bg: Tba.color.bg.secondary, color: Tba.color.text.secondary });

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Active AFAs</span><span style={bl.statValue}>{active.length}</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>{bl.money(totalWorked)} worked YTD</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Capped / fixed exposure</span><span style={bl.statValue}>{bl.money(totalCapped)}</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>cap-based commitments</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Worked vs billed</span><span style={{ ...bl.statValue, color: totalBilled >= totalWorked ? bl.emerald : bl.amber }}>{((totalBilled / totalWorked) * 100).toFixed(0)}%</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>{bl.money(totalWorked - totalBilled)} at risk</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>AFA revenue mix</span><span style={{ ...bl.statValue, color: bl.teal }}>34%</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>of YTD billings</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>AFA margin delta</span><span style={{ ...bl.statValue, color: bl.emerald }}>+$494K</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>vs hourly equivalent</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '14px' }}>
        {data.afas.map(a => {
          const tc = typeColor(a.type);
          const capPct = a.capUsedPct;
          return (
            <div key={a.id} style={{ ...bl.card, marginBottom: 0 }}>
              <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tba.color.border.light}`, background: `linear-gradient(135deg, ${tc.bg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span style={{ ...bl.tag, background: tc.bg, color: tc.color, fontSize: '11px', padding: '3px 10px' }}>{a.type}</span>
                  <span style={{ fontSize: '10px', fontFamily: Tba.font.mono, color: Tba.color.text.tertiary }}>{a.id}</span>
                </div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tba.color.text.primary }}>{a.matter}</div>
                <div style={{ fontSize: '11px', color: Tba.color.text.tertiary, marginTop: '2px' }}>{a.client}</div>
              </div>
              <div style={{ padding: '14px 16px' }}>
                {/* Cap utilization bar if applicable */}
                {a.cap && (
                  <div style={{ marginBottom: '12px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tba.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>
                      <span>Cap utilization</span>
                      <span style={{ fontFamily: Tba.font.mono, color: capPct > 80 ? bl.crimson : capPct > 60 ? bl.amber : bl.emerald, fontWeight: 700 }}>{capPct.toFixed(1)}%</span>
                    </div>
                    <div style={{ height: '8px', background: Tba.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                      <div style={{ width: `${Math.min(100, capPct)}%`, height: '100%', background: capPct > 80 ? bl.crimson : capPct > 60 ? bl.amber : bl.emerald }} />
                    </div>
                    <div style={{ fontSize: '10px', fontFamily: Tba.font.mono, color: Tba.color.text.tertiary, marginTop: '4px' }}>{bl.money(a.worked)} of {bl.money(a.cap)}</div>
                  </div>
                )}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tba.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Worked</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: Tba.color.text.primary, fontFamily: Tba.font.mono }}>{bl.money(a.worked)}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tba.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Billed</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: bl.teal, fontFamily: Tba.font.mono }}>{bl.money(a.billed)}</div>
                  </div>
                </div>
                <div style={{ fontSize: '10px', color: Tba.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Trigger</div>
                <div style={{ fontSize: '11px', color: Tba.color.text.secondary, lineHeight: 1.5, marginBottom: '10px' }}>{a.trigger}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tba.color.border.light}` }}>
                  <span style={{ fontSize: '10px', color: bl.emerald, fontWeight: 700 }}>{a.perfDelta}</span>
                  <span style={{ ...bl.tag, background: a.status === 'Active' ? bl.emeraldBg : Tba.color.bg.secondary, color: a.status === 'Active' ? bl.emerald : Tba.color.text.tertiary }}>{a.status}</span>
                </div>
                <div style={{ fontSize: '10px', color: Tba.color.text.tertiary, marginTop: '6px' }}>Exit: {a.exitDate}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function BillingForecast({ data }) {
  const bl = window.__bl;
  const f = data.forecast;
  const maxPipe = Math.max(...f.monthly12.map(m => m.pipeline));
  const totalPipeline = f.pipelineStage.reduce((s, p) => s + p.expectedRev, 0);
  const totalMatters = f.pipelineStage.reduce((s, p) => s + p.matters, 0);
  const next12Revenue = f.monthly12.reduce((s, m) => s + m.committed, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Pipeline matters</span><span style={bl.statValue}>{totalMatters}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Pipeline revenue</span><span style={bl.statValue}>${(totalPipeline / 1_000_000).toFixed(1)}M</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>12-mo committed</span><span style={{ ...bl.statValue, color: bl.emerald }}>${next12Revenue.toFixed(1)}M</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>12-mo pipeline</span><span style={{ ...bl.statValue, color: bl.teal }}>${f.monthly12.reduce((s, m) => s + m.pipeline, 0).toFixed(1)}M</span></div>
      </div>

      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>12-month revenue forecast — Pipeline vs Committed</span>
          <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>
            <span style={{ color: bl.teal }}>■ Pipeline</span>
            <span style={{ color: bl.emerald }}>■ Committed</span>
          </div>
        </div>
        <div style={{ padding: '20px 16px 14px', display: 'flex', gap: '8px', alignItems: 'flex-end', height: '200px' }}>
          {f.monthly12.map(m => (
            <div key={m.m} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
              <div style={{ position: 'relative', width: '100%', height: '160px', display: 'flex', justifyContent: 'center' }}>
                <div style={{ width: '70%', height: `${(m.pipeline / maxPipe) * 100}%`, background: bl.teal, opacity: 0.5, borderRadius: '2px 2px 0 0', position: 'absolute', bottom: 0 }} />
                <div style={{ width: '70%', height: `${(m.committed / maxPipe) * 100}%`, background: bl.emerald, borderRadius: '2px 2px 0 0', position: 'absolute', bottom: 0 }} />
              </div>
              <span style={{ fontSize: '9px', color: Tba.color.text.tertiary, fontFamily: Tba.font.mono }}>{m.m}</span>
              <span style={{ fontSize: '10px', fontFamily: Tba.font.mono, color: bl.emerald, fontWeight: 700 }}>${m.committed.toFixed(0)}M</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        <div style={bl.card}>
          <div style={bl.cardH}>New-business pipeline by stage</div>
          <div style={{ padding: '10px 16px' }}>
            {f.pipelineStage.map((s, i) => {
              const max = Math.max(...f.pipelineStage.map(x => x.expectedRev));
              return (
                <div key={s.stage} style={{ padding: '8px 0', borderBottom: i < f.pipelineStage.length - 1 ? `1px solid ${Tba.color.border.light}` : 'none' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', fontSize: '12px' }}>
                    <span style={{ color: Tba.color.text.primary, fontWeight: 500 }}>{s.stage}</span>
                    <span style={{ display: 'flex', gap: '10px' }}>
                      <span style={{ fontFamily: Tba.font.mono, color: Tba.color.text.secondary, fontSize: '11px' }}>{s.matters}</span>
                      <span style={{ fontFamily: Tba.font.mono, color: bl.emerald, fontWeight: 700, fontSize: '11px', minWidth: '64px', textAlign: 'right' }}>{bl.money(s.expectedRev)}</span>
                    </span>
                  </div>
                  <div style={{ height: '4px', background: Tba.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                    <div style={{ width: `${(s.expectedRev / max) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${bl.teal} 0%, ${bl.emerald} 100%)` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={bl.card}>
          <div style={bl.cardH}>Partner compensation outlook</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Partner</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Projected orig.</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Projected comp</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>vs Prior yr</th>
              </tr>
            </thead>
            <tbody>
              {f.partnerComp.map(p => (
                <tr key={p.partner}>
                  <td style={{ ...bl.td, fontWeight: 600, color: Tba.color.text.primary }}>{p.partner}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: Tba.color.text.primary, fontWeight: 700 }}>{bl.money(p.projectedOrig)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: bl.emerald, fontWeight: 700 }}>{bl.money(p.projectedComp)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: p.vsPriorYr >= 0 ? bl.emerald : bl.crimson, fontWeight: 700 }}>{p.vsPriorYr >= 0 ? '+' : ''}{p.vsPriorYr.toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function BillingEBilling({ data }) {
  const bl = window.__bl;
  const totalSubmitted = data.ebilling.reduce((s, e) => s + e.submitted30d, 0);
  const totalAccepted = data.ebilling.reduce((s, e) => s + e.accepted, 0);
  const totalRejected = data.ebilling.reduce((s, e) => s + e.rejected, 0);
  const openQueries = data.ebilling.reduce((s, e) => s + e.openQueries, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Submitted (30d)</span><span style={bl.statValue}>{totalSubmitted}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Accepted</span><span style={{ ...bl.statValue, color: bl.emerald }}>{totalAccepted}</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>{((totalAccepted / totalSubmitted) * 100).toFixed(0)}% acceptance</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Rejected</span><span style={{ ...bl.statValue, color: bl.crimson }}>{totalRejected}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Open queries</span><span style={{ ...bl.statValue, color: bl.amber }}>{openQueries}</span><span style={{ ...bl.statDelta, color: Tba.color.text.tertiary }}>need response</span></div>
      </div>

      <div style={bl.card}>
        <div style={bl.cardH}>Client eBilling systems — {data.ebilling.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Client</th>
              <th style={bl.th}>System</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Submitted 30d</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Accepted</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Rejected</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Avg approve</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Open queries</th>
            </tr>
          </thead>
          <tbody>
            {data.ebilling.map(e => (
              <tr key={e.client}>
                <td style={{ ...bl.td, fontWeight: 600, color: Tba.color.text.primary }}>{e.client}</td>
                <td style={bl.td}><span style={{ ...bl.tag, background: bl.violetBg, color: bl.violet, fontFamily: Tba.font.mono }}>{e.system}</span></td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: Tba.color.text.primary, fontWeight: 600 }}>{e.submitted30d}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: bl.emerald, fontWeight: 700 }}>{e.accepted}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: e.rejected > 0 ? bl.crimson : Tba.color.text.tertiary, fontWeight: e.rejected > 0 ? 700 : 500 }}>{e.rejected}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: e.avgApproveDays > 10 ? bl.amber : Tba.color.text.secondary }}>{e.avgApproveDays}d</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tba.font.mono, color: e.openQueries > 0 ? bl.amber : Tba.color.text.tertiary, fontWeight: e.openQueries > 0 ? 700 : 500 }}>{e.openQueries}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BillingActivity({ data }) {
  const bl = window.__bl;
  const sev = (s) => s === 'error' ? { bg: bl.crimsonBg, color: bl.crimson }
    : s === 'warn' ? { bg: bl.amberBg, color: bl.amber }
    : { bg: bl.emeraldBg, color: bl.emerald };

  return (
    <div style={bl.card}>
      <div style={bl.cardH}>
        <span>Activity log — {data.activity.length} events</span>
        <button style={bl.btnSecondary}>Export CSV</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={bl.th}>Time</th>
            <th style={bl.th}>Actor</th>
            <th style={bl.th}>Action</th>
            <th style={bl.th}>Target</th>
            <th style={bl.th}>Severity</th>
          </tr>
        </thead>
        <tbody>
          {data.activity.map(ev => {
            const ss = sev(ev.severity);
            return (
              <tr key={ev.id}>
                <td style={{ ...bl.td, fontFamily: Tba.font.mono, color: Tba.color.text.tertiary, fontSize: '11px' }}>{ev.time}</td>
                <td style={{ ...bl.td, color: Tba.color.text.primary, fontWeight: 500 }}>
                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: ss.color, marginRight: '8px' }} />
                  {ev.actor}
                </td>
                <td style={{ ...bl.td, color: Tba.color.text.secondary }}>{ev.action}</td>
                <td style={{ ...bl.td, color: Tba.color.text.primary, fontWeight: 500, maxWidth: '440px' }}>{ev.target}</td>
                <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{ev.severity}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.BillingAFAs = BillingAFAs;
window.BillingForecast = BillingForecast;
window.BillingEBilling = BillingEBilling;
window.BillingActivity = BillingActivity;
