// BILLING PLATFORM — Billing pipeline + Invoices
const { useState: useBlInvState, useMemo: useBlInvMemo } = React;
const Tbi = window.ArbiterTokens;

function BillingPipeline({ data }) {
  const bl = window.__bl;
  const stages = ['Draft', 'Partner Review', 'LEDES Export', 'Client Portal', 'Sent'];
  const byStage = stages.map(s => ({
    stage: s,
    prebills: data.preBills.filter(p => p.stage === s),
    total: data.preBills.filter(p => p.stage === s).reduce((acc, p) => acc + p.amount, 0),
  }));

  const totalPipeline = data.preBills.reduce((s, p) => s + p.amount, 0);
  const totalWritedown = data.preBills.reduce((s, p) => s + p.writedown, 0);
  const avgWritedownPct = (totalWritedown / totalPipeline * 100).toFixed(1);

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Pipeline total</span>
          <span style={bl.statValue}>{bl.money(totalPipeline)}</span>
          <span style={{ ...bl.statDelta, color: Tbi.color.text.tertiary }}>{data.preBills.length} pre-bills</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>In partner review</span>
          <span style={{ ...bl.statValue, color: bl.amber }}>{data.preBills.filter(p => p.stage === 'Partner Review').length}</span>
          <span style={{ ...bl.statDelta, color: Tbi.color.text.tertiary }}>{bl.money(data.preBills.filter(p => p.stage === 'Partner Review').reduce((s, p) => s + p.amount, 0))}</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Avg write-down</span>
          <span style={{ ...bl.statValue, color: avgWritedownPct > 5 ? bl.amber : bl.emerald }}>{avgWritedownPct}%</span>
          <span style={{ ...bl.statDelta, color: Tbi.color.text.tertiary }}>{bl.money(totalWritedown)} total</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Due within 3 days</span>
          <span style={{ ...bl.statValue, color: bl.crimson }}>{data.preBills.filter(p => p.reviewDays <= 3 && p.reviewDays > 0).length}</span>
          <span style={{ ...bl.statDelta, color: Tbi.color.text.tertiary }}>review required</span>
        </div>
      </div>

      {/* Stage pipeline */}
      <div style={{ ...bl.card }}>
        <div style={bl.cardH}>
          <span>Pre-bill pipeline by stage</span>
          <button style={bl.btnPrimary}>+ Generate pre-bills</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${stages.length}, 1fr)`, gap: '1px', background: Tbi.color.border.light }}>
          {byStage.map((s, i) => (
            <div key={s.stage} style={{ background: Tbi.color.bg.card, padding: '12px', minHeight: '220px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px', alignItems: 'baseline' }}>
                <div>
                  <div style={{ fontSize: '10px', color: Tbi.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>Stage {i + 1}</div>
                  <div style={{ fontSize: '12px', fontWeight: 700, color: Tbi.color.text.primary, marginTop: '2px' }}>{s.stage}</div>
                </div>
                <span style={{ ...bl.tag, background: bl.emeraldBg, color: bl.emerald }}>{s.prebills.length}</span>
              </div>
              <div style={{ fontSize: '10px', color: Tbi.color.text.tertiary, marginBottom: '8px', fontFamily: Tbi.font.mono }}>{bl.money(s.total)}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
                {s.prebills.map(p => (
                  <div key={p.id} style={{ background: Tbi.color.bg.secondary, border: `1px solid ${Tbi.color.border.light}`, borderRadius: '5px', padding: '8px' }}>
                    <div style={{ fontSize: '11px', fontWeight: 600, color: Tbi.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.matter}</div>
                    <div style={{ fontSize: '10px', color: Tbi.color.text.tertiary, fontFamily: Tbi.font.mono, marginTop: '2px' }}>{p.id} · {bl.money(p.amount)}</div>
                    {p.writedownPct > 0 && (
                      <div style={{ fontSize: '10px', color: p.writedownPct > 5 ? bl.amber : bl.emerald, marginTop: '2px' }}>−{p.writedownPct.toFixed(1)}% write-down</div>
                    )}
                    {p.reviewDays > 0 && (
                      <div style={{ fontSize: '10px', color: p.reviewDays <= 3 ? bl.crimson : Tbi.color.text.tertiary, marginTop: '2px' }}>{p.reviewDays}d to client due</div>
                    )}
                  </div>
                ))}
                {s.prebills.length === 0 && <div style={{ fontSize: '10px', color: Tbi.color.text.tertiary, textAlign: 'center', padding: '20px 0' }}>No pre-bills</div>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Detail table */}
      <div style={bl.card}>
        <div style={bl.cardH}>All pre-bills</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Pre-bill</th>
              <th style={bl.th}>Matter</th>
              <th style={bl.th}>Client</th>
              <th style={bl.th}>Partner</th>
              <th style={bl.th}>Stage</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Amount</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Entries</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Write-down</th>
              <th style={bl.th}>Due to client</th>
            </tr>
          </thead>
          <tbody>
            {data.preBills.map(p => {
              const stageColor = p.stage === 'Sent' ? { bg: bl.emeraldBg, color: bl.emerald }
                : p.stage === 'Client Portal' ? { bg: bl.tealBg, color: bl.teal }
                : p.stage === 'Partner Review' ? { bg: bl.amberBg, color: bl.amber }
                : p.stage === 'LEDES Export' ? { bg: bl.violetBg, color: bl.violet }
                : { bg: Tbi.color.bg.secondary, color: Tbi.color.text.secondary };
              return (
                <tr key={p.id}>
                  <td style={{ ...bl.td, fontFamily: Tbi.font.mono, color: Tbi.color.text.primary, fontWeight: 600 }}>{p.id}</td>
                  <td style={{ ...bl.td, color: Tbi.color.text.primary, fontWeight: 500, maxWidth: '240px' }}>{p.matter}</td>
                  <td style={{ ...bl.td, color: Tbi.color.text.secondary }}>{p.client}</td>
                  <td style={{ ...bl.td, color: Tbi.color.text.secondary }}>{p.billingPartner}</td>
                  <td style={bl.td}><span style={{ ...bl.tag, background: stageColor.bg, color: stageColor.color }}>{p.stage}</span></td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: Tbi.color.text.primary, fontWeight: 700 }}>{bl.money(p.amount)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: Tbi.color.text.secondary }}>{p.entries}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: p.writedownPct > 5 ? bl.amber : Tbi.color.text.tertiary }}>
                    {p.writedown ? `${bl.money(p.writedown)} (${p.writedownPct.toFixed(1)}%)` : '—'}
                  </td>
                  <td style={{ ...bl.td, fontFamily: Tbi.font.mono, fontSize: '11px', color: p.reviewDays <= 3 && p.reviewDays > 0 ? bl.crimson : Tbi.color.text.secondary }}>{p.dueToClient}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BillingInvoices({ data }) {
  const bl = window.__bl;
  const [statusFilter, setStatusFilter] = useBlInvState('All');
  const [clientFilter, setClientFilter] = useBlInvState('All');

  const clients = useBlInvMemo(() => ['All', ...new Set(data.invoices.map(i => i.client))], [data]);
  const statuses = ['All', 'Paid', 'Open', 'Partial', 'Overdue', 'Disputed'];

  const filtered = data.invoices.filter(i =>
    (statusFilter === 'All' || i.status === statusFilter) &&
    (clientFilter === 'All' || i.client === clientFilter)
  );

  const totalBilled = data.invoices.reduce((s, i) => s + i.amount, 0);
  const totalOutstanding = data.invoices.reduce((s, i) => s + i.balance, 0);
  const overdueTotal = data.invoices.filter(i => i.status === 'Overdue' || i.status === 'Disputed').reduce((s, i) => s + i.balance, 0);

  const statusStyle = (s) => ({
    Paid: { bg: bl.emeraldBg, color: bl.emerald },
    Open: { bg: bl.tealBg, color: bl.teal },
    Partial: { bg: bl.violetBg, color: bl.violet },
    Overdue: { bg: bl.amberBg, color: bl.amber },
    Disputed: { bg: bl.crimsonBg, color: bl.crimson },
  }[s] || { bg: Tbi.color.bg.secondary, color: Tbi.color.text.secondary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Invoices</span><span style={bl.statValue}>{data.invoices.length}</span><span style={{ ...bl.statDelta, color: Tbi.color.text.tertiary }}>last 6 months</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Total billed</span><span style={bl.statValue}>{bl.money(totalBilled)}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Outstanding</span><span style={{ ...bl.statValue, color: bl.amber }}>{bl.money(totalOutstanding)}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Overdue / disputed</span><span style={{ ...bl.statValue, color: bl.crimson }}>{bl.money(overdueTotal)}</span></div>
      </div>

      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>Invoices — {filtered.length} of {data.invoices.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tbi.color.border.light}`, borderRadius: '5px', background: Tbi.color.bg.card, color: Tbi.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <select value={clientFilter} onChange={e => setClientFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tbi.color.border.light}`, borderRadius: '5px', background: Tbi.color.bg.card, color: Tbi.color.text.secondary }}>
              {clients.map(c => <option key={c} value={c}>Client: {c === 'All' ? 'All' : c.length > 22 ? c.slice(0, 20) + '…' : c}</option>)}
            </select>
            <button style={bl.btnSecondary}>Export</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Invoice</th>
              <th style={bl.th}>Client / Matter</th>
              <th style={bl.th}>Partner</th>
              <th style={bl.th}>Issued</th>
              <th style={bl.th}>Due</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Amount</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Paid</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Balance</th>
              <th style={bl.th}>Aging</th>
              <th style={bl.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(i => {
              const ss = statusStyle(i.status);
              const aging = bl.agingColor(i.daysOutstanding);
              return (
                <tr key={i.id}>
                  <td style={{ ...bl.td, fontFamily: Tbi.font.mono, color: Tbi.color.text.primary, fontWeight: 600 }}>{i.id}</td>
                  <td style={{ ...bl.td, maxWidth: '280px' }}>
                    <div style={{ fontSize: '12px', color: Tbi.color.text.primary, fontWeight: 500 }}>{i.client}</div>
                    <div style={{ fontSize: '11px', color: Tbi.color.text.tertiary, marginTop: '2px' }}>{i.matter}</div>
                  </td>
                  <td style={{ ...bl.td, color: Tbi.color.text.secondary }}>{i.billingPartner}</td>
                  <td style={{ ...bl.td, fontFamily: Tbi.font.mono, fontSize: '11px', color: Tbi.color.text.secondary }}>{i.issued}</td>
                  <td style={{ ...bl.td, fontFamily: Tbi.font.mono, fontSize: '11px', color: Tbi.color.text.secondary }}>{i.due}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: Tbi.color.text.primary, fontWeight: 700 }}>{bl.money(i.amount)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: bl.emerald }}>{bl.money(i.paid)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbi.font.mono, color: i.balance > 0 ? bl.amber : Tbi.color.text.tertiary, fontWeight: i.balance > 0 ? 700 : 500 }}>{bl.money(i.balance)}</td>
                  <td style={bl.td}>
                    {i.daysOutstanding > 0 ? (
                      <span style={{ ...bl.tag, background: aging.bg, color: aging.color }}>{i.daysOutstanding}d · {aging.label}</span>
                    ) : <span style={{ color: Tbi.color.text.tertiary, fontSize: '10px' }}>current</span>}
                  </td>
                  <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{i.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.BillingPipeline = BillingPipeline;
window.BillingInvoices = BillingInvoices;
