// BILLING PLATFORM — Collections/AR + Trust/IOLTA
const Tbc = window.ArbiterTokens;

function BillingCollections({ data }) {
  const bl = window.__bl;
  const ar = data.arAging;
  const total = ar.buckets.reduce((s, b) => s + b.amount, 0);
  const maxBucket = Math.max(...ar.buckets.map(b => b.amount));

  return (
    <div>
      {/* AR aging buckets visual */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        {ar.buckets.map(b => {
          const ac = bl.agingColor(b.range === '91+' ? 120 : b.range === '61-90' ? 75 : b.range === '31-60' ? 45 : 15);
          return (
            <div key={b.range} style={{ ...bl.stat, borderLeft: `3px solid ${ac.color}` }}>
              <span style={bl.statLabel}>AR · {b.range} days</span>
              <span style={{ ...bl.statValue, color: ac.color }}>{bl.money(b.amount)}</span>
              <span style={{ ...bl.statDelta, color: Tbc.color.text.tertiary }}>{b.count} invoices · {b.pct.toFixed(1)}%</span>
            </div>
          );
        })}
      </div>

      {/* Aging bar visualization */}
      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>AR composition — {bl.money(total)}</span>
          <div style={{ display: 'flex', gap: '10px', fontSize: '10px' }}>
            <span style={{ color: bl.emerald }}>■ 0-30</span>
            <span style={{ color: bl.amber }}>■ 31-60</span>
            <span style={{ color: bl.orange }}>■ 61-90</span>
            <span style={{ color: bl.crimson }}>■ 91+</span>
          </div>
        </div>
        <div style={{ padding: '14px 16px' }}>
          <div style={{ display: 'flex', height: '28px', borderRadius: '4px', overflow: 'hidden', marginBottom: '14px' }}>
            {ar.buckets.map(b => {
              const ac = bl.agingColor(b.range === '91+' ? 120 : b.range === '61-90' ? 75 : b.range === '31-60' ? 45 : 15);
              return (
                <div key={b.range} title={`${b.range}: ${bl.money(b.amount)}`} style={{ width: `${(b.amount / total) * 100}%`, background: ac.color, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: '10px', fontWeight: 700 }}>
                  {b.pct.toFixed(0)}%
                </div>
              );
            })}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', fontSize: '11px' }}>
            {ar.buckets.map(b => (
              <div key={b.range} style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                <span style={{ color: Tbc.color.text.tertiary, textTransform: 'uppercase', fontSize: '9px', letterSpacing: '0.06em' }}>{b.range} days</span>
                <span style={{ fontSize: '14px', fontWeight: 700, color: Tbc.color.text.primary, fontFamily: Tbc.font.mono }}>{bl.money(b.amount)}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '16px' }}>
        {/* By client */}
        <div style={bl.card}>
          <div style={bl.cardH}>
            <span>AR by client — {ar.byClient.length}</span>
            <button style={bl.btnSecondary}>Export</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Client</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Total</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>0-30</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>31-60</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>61-90</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>91+</th>
                <th style={bl.th}>Contact</th>
              </tr>
            </thead>
            <tbody>
              {ar.byClient.map(c => (
                <tr key={c.client}>
                  <td style={{ ...bl.td, fontWeight: 600, color: Tbc.color.text.primary }}>
                    {c.client}
                    {c.disputeCount > 0 && <span style={{ ...bl.tag, background: bl.crimsonBg, color: bl.crimson, marginLeft: '6px' }}>{c.disputeCount} dispute{c.disputeCount > 1 ? 's' : ''}</span>}
                  </td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: Tbc.color.text.primary, fontWeight: 700 }}>{bl.money(c.total)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: c.b030 > 0 ? bl.emerald : Tbc.color.text.tertiary }}>{c.b030 ? bl.money(c.b030) : '—'}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: c.b3160 > 0 ? bl.amber : Tbc.color.text.tertiary }}>{c.b3160 ? bl.money(c.b3160) : '—'}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: c.b6190 > 0 ? bl.orange : Tbc.color.text.tertiary }}>{c.b6190 ? bl.money(c.b6190) : '—'}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: c.b91plus > 0 ? bl.crimson : Tbc.color.text.tertiary, fontWeight: c.b91plus > 0 ? 700 : 500 }}>{c.b91plus ? bl.money(c.b91plus) : '—'}</td>
                  <td style={{ ...bl.td, color: Tbc.color.text.secondary, fontSize: '11px' }}>{c.contact}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Escalation queue */}
        <div style={bl.card}>
          <div style={{ ...bl.cardH, color: bl.crimson }}>! Escalation queue — {ar.escalation.length}</div>
          <div>
            {ar.escalation.map(e => (
              <div key={e.invoice} style={{ padding: '14px 16px', borderBottom: `1px solid ${Tbc.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', alignItems: 'baseline' }}>
                  <span style={{ fontSize: '12px', fontWeight: 600, color: Tbc.color.text.primary, fontFamily: Tbc.font.mono }}>{e.invoice}</span>
                  <span style={{ ...bl.tag, background: bl.crimsonBg, color: bl.crimson, fontFamily: Tbc.font.mono }}>{e.days}d</span>
                </div>
                <div style={{ fontSize: '11px', color: Tbc.color.text.secondary, marginBottom: '3px' }}>{e.client}</div>
                <div style={{ fontSize: '11px', color: Tbc.color.text.tertiary, marginBottom: '6px' }}>{e.matter}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '6px' }}>
                  <span style={{ fontSize: '14px', fontWeight: 700, color: bl.crimson, fontFamily: Tbc.font.mono }}>{bl.money(e.amount)}</span>
                  <span style={{ fontSize: '10px', color: Tbc.color.text.tertiary }}>Owner: {e.ownedBy}</span>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', marginBottom: '6px' }}>
                  {e.actions.map(a => <span key={a} style={{ ...bl.tag, background: Tbc.color.bg.secondary, color: Tbc.color.text.secondary }}>ok {a}</span>)}
                </div>
                <div style={{ fontSize: '11px', color: bl.crimson, fontWeight: 600 }}>→ Next: {e.nextStep}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Disputes */}
      <div style={bl.card}>
        <div style={bl.cardH}>Active disputes — {data.disputes.length}</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, textAlign: 'right' }}>Invoice amt</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Disputed</th>
              <th style={bl.th}>Reason</th>
              <th style={bl.th}>Opened</th>
              <th style={bl.th}>Status</th>
              <th style={bl.th}>Owner</th>
            </tr>
          </thead>
          <tbody>
            {data.disputes.map(d => {
              const ss = d.status === 'Escalated' ? { bg: bl.crimsonBg, color: bl.crimson }
                : d.status === 'Under negotiation' ? { bg: bl.violetBg, color: bl.violet }
                : { bg: bl.amberBg, color: bl.amber };
              return (
                <tr key={d.invoice}>
                  <td style={{ ...bl.td, fontFamily: Tbc.font.mono, fontWeight: 600 }}>{d.invoice}</td>
                  <td style={{ ...bl.td, maxWidth: '260px' }}>
                    <div style={{ fontSize: '12px', color: Tbc.color.text.primary, fontWeight: 500 }}>{d.client}</div>
                    <div style={{ fontSize: '11px', color: Tbc.color.text.tertiary }}>{d.matter}</div>
                  </td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: Tbc.color.text.primary, fontWeight: 600 }}>{bl.money(d.amount)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: bl.crimson, fontWeight: 700 }}>{bl.money(d.disputed)}</td>
                  <td style={{ ...bl.td, color: Tbc.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{d.reason}</td>
                  <td style={{ ...bl.td, fontFamily: Tbc.font.mono, fontSize: '11px', color: Tbc.color.text.tertiary }}>{d.opened}</td>
                  <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{d.status}</span></td>
                  <td style={{ ...bl.td, color: Tbc.color.text.secondary }}>{d.owner}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BillingTrust({ data }) {
  const bl = window.__bl;
  const totalTrust = data.trustAccounts.reduce((s, a) => s + a.balance, 0);
  const totalReserve = data.trustAccounts.reduce((s, a) => s + a.reserve, 0);
  const varianceFlagged = data.trustAccounts.filter(a => a.status !== 'Reconciled').length;

  return (
    <div>
      {/* Compliance banner */}
      <div style={{ ...bl.card, marginBottom: '16px', borderLeft: `3px solid ${bl.violet}`, background: bl.violetBg }}>
        <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, color: bl.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>IOLTA Compliance — State Bar Rule 1.15</div>
            <div style={{ fontSize: '12px', color: Tbc.color.text.secondary, marginTop: '4px' }}>
              Three-way reconciliation required monthly. Last audit: 2026-01-08 · Next audit: 2026-07-08 · Compliance officer: G. Ramirez
            </div>
          </div>
          <div style={{ display: 'flex', gap: '10px' }}>
            <button style={bl.btnSecondary}>Audit log</button>
            <button style={bl.btnPrimary}>Run reconciliation</button>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Trust balance total</span><span style={bl.statValue}>{bl.money(totalTrust)}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Reserved (not disbursable)</span><span style={{ ...bl.statValue, color: bl.violet }}>{bl.money(totalReserve)}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Accounts</span><span style={bl.statValue}>{data.trustAccounts.length}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Variances flagged</span><span style={{ ...bl.statValue, color: varianceFlagged > 0 ? bl.crimson : bl.emerald }}>{varianceFlagged}</span><span style={{ ...bl.statDelta, color: Tbc.color.text.tertiary }}>require attention</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: '16px' }}>
        <div style={bl.card}>
          <div style={bl.cardH}>Trust accounts — {data.trustAccounts.length}</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Account</th>
                <th style={bl.th}>Client / Matter</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Balance</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Reserved</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>30d in</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>30d out</th>
                <th style={bl.th}>Reconciled</th>
                <th style={bl.th}>Status</th>
              </tr>
            </thead>
            <tbody>
              {data.trustAccounts.map(a => {
                const ss = a.status === 'Reconciled' ? { bg: bl.emeraldBg, color: bl.emerald }
                  : a.status === 'Variance flagged' ? { bg: bl.crimsonBg, color: bl.crimson }
                  : { bg: bl.amberBg, color: bl.amber };
                return (
                  <tr key={a.id}>
                    <td style={{ ...bl.td, fontFamily: Tbc.font.mono, color: bl.violet, fontWeight: 700 }}>{a.id}</td>
                    <td style={{ ...bl.td, maxWidth: '240px' }}>
                      <div style={{ fontSize: '12px', color: Tbc.color.text.primary, fontWeight: 500 }}>{a.client}</div>
                      <div style={{ fontSize: '11px', color: Tbc.color.text.tertiary }}>{a.matter}</div>
                    </td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: Tbc.color.text.primary, fontWeight: 700 }}>{bl.money(a.balance)}</td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: bl.violet }}>{bl.money(a.reserve)}</td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: a.deposits30d > 0 ? bl.emerald : Tbc.color.text.tertiary }}>{a.deposits30d > 0 ? `+${bl.money(a.deposits30d)}` : '—'}</td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbc.font.mono, color: a.disbursements30d > 0 ? bl.amber : Tbc.color.text.tertiary }}>{a.disbursements30d > 0 ? `−${bl.money(a.disbursements30d)}` : '—'}</td>
                    <td style={{ ...bl.td, fontFamily: Tbc.font.mono, fontSize: '11px', color: Tbc.color.text.secondary }}>{a.lastReconciled}</td>
                    <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{a.status}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={bl.card}>
          <div style={bl.cardH}>Recent ledger activity</div>
          <div>
            {data.trustLedger.map((l, i) => (
              <div key={l.id} style={{ padding: '10px 16px', borderBottom: i < data.trustLedger.length - 1 ? `1px solid ${Tbc.color.border.light}` : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '3px' }}>
                  <span style={{ fontSize: '10px', fontFamily: Tbc.font.mono, color: Tbc.color.text.tertiary }}>{l.date}</span>
                  <span style={{ fontSize: '13px', fontFamily: Tbc.font.mono, fontWeight: 700, color: l.amount >= 0 ? bl.emerald : bl.amber }}>
                    {l.amount >= 0 ? '+' : '−'}{bl.money(Math.abs(l.amount))}
                  </span>
                </div>
                <div style={{ display: 'flex', gap: '6px', marginBottom: '3px' }}>
                  <span style={{ ...bl.tag, background: l.kind === 'Deposit' ? bl.emeraldBg : bl.amberBg, color: l.kind === 'Deposit' ? bl.emerald : bl.amber }}>{l.kind}</span>
                  <span style={{ fontSize: '10px', color: bl.violet, fontFamily: Tbc.font.mono }}>{l.account}</span>
                </div>
                <div style={{ fontSize: '11px', color: Tbc.color.text.secondary, lineHeight: 1.5 }}>{l.note}</div>
                <div style={{ fontSize: '10px', color: Tbc.color.text.tertiary, marginTop: '3px' }}>Approved: {l.approvedBy}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BillingCollections = BillingCollections;
window.BillingTrust = BillingTrust;
