// BILLING PLATFORM — Profitability + Budgets
const Tbp = window.ArbiterTokens;

function BillingProfitability({ data }) {
  const bl = window.__bl;
  const p = data.profitability;
  const flagged = p.byMatter.filter(m => m.flagged);
  const totalRev = p.byMatter.reduce((s, m) => s + m.revenue, 0);
  const totalMargin = p.byMatter.reduce((s, m) => s + m.margin, 0);
  const blendedMarginPct = (totalMargin / totalRev * 100).toFixed(1);

  const marginColor = (pct) => pct >= 35 ? bl.emerald : pct >= 25 ? bl.amber : bl.crimson;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Matters tracked</span>
          <span style={bl.statValue}>{p.byMatter.length}</span>
          <span style={{ ...bl.statDelta, color: Tbp.color.text.tertiary }}>with allocated cost model</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Blended margin</span>
          <span style={{ ...bl.statValue, color: marginColor(parseFloat(blendedMarginPct)) }}>{blendedMarginPct}%</span>
          <span style={{ ...bl.statDelta, color: Tbp.color.text.tertiary }}>across tracked matters</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Margin dollars</span>
          <span style={bl.statValue}>{bl.money(totalMargin)}</span>
        </div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Under-performing</span>
          <span style={{ ...bl.statValue, color: bl.crimson }}>{flagged.length}</span>
          <span style={{ ...bl.statDelta, color: Tbp.color.text.tertiary }}>margin &lt; 20%</span>
        </div>
      </div>

      {/* By practice */}
      <div style={bl.card}>
        <div style={bl.cardH}>Profitability by practice</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Practice</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Revenue</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Margin $</th>
              <th style={bl.th}>Margin %</th>
            </tr>
          </thead>
          <tbody>
            {p.byPractice.map(pr => (
              <tr key={pr.practice}>
                <td style={{ ...bl.td, fontWeight: 600, color: Tbp.color.text.primary }}>{pr.practice}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.primary, fontWeight: 700 }}>{bl.money(pr.revenue)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: bl.emerald }}>{bl.money(pr.margin)}</td>
                <td style={bl.td}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{ width: '160px', height: '6px', background: Tbp.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${pr.marginPct * 2}%`, height: '100%', background: marginColor(pr.marginPct) }} />
                    </div>
                    <span style={{ fontFamily: Tbp.font.mono, color: marginColor(pr.marginPct), fontWeight: 700 }}>{pr.marginPct.toFixed(1)}%</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* By matter */}
      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>Matter profitability — fully-loaded cost model</span>
          <button style={bl.btnSecondary}>Export</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Matter</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Revenue</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Direct cost</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Overhead</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Margin</th>
              <th style={bl.th}>Margin %</th>
              <th style={bl.th}>Flag</th>
            </tr>
          </thead>
          <tbody>
            {p.byMatter.map(m => (
              <tr key={m.matter} style={m.flagged ? { background: 'rgba(185,28,28,0.03)' } : undefined}>
                <td style={{ ...bl.td, fontWeight: 600, color: Tbp.color.text.primary, maxWidth: '260px' }}>{m.matter}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.primary, fontWeight: 700 }}>{bl.money(m.revenue)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.secondary }}>{bl.money(m.directCost)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.tertiary }}>{bl.money(m.overheadAlloc)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: marginColor(m.marginPct), fontWeight: 700 }}>{bl.money(m.margin)}</td>
                <td style={bl.td}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <div style={{ width: '90px', height: '4px', background: Tbp.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                      <div style={{ width: `${Math.min(100, m.marginPct * 2)}%`, height: '100%', background: marginColor(m.marginPct) }} />
                    </div>
                    <span style={{ fontFamily: Tbp.font.mono, fontSize: '11px', color: marginColor(m.marginPct), fontWeight: 700, minWidth: '42px', textAlign: 'right' }}>{m.marginPct.toFixed(1)}%</span>
                  </div>
                </td>
                <td style={bl.td}>
                  {m.flagged && <span style={{ ...bl.tag, background: bl.crimsonBg, color: bl.crimson }}>under-performing</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Partner leverage */}
      <div style={bl.card}>
        <div style={bl.cardH}>Partner leverage — originations, working revenue, team size</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Partner</th>
              <th style={bl.th}>Practice</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Originations</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Working rev.</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Team</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Leverage</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Margin</th>
            </tr>
          </thead>
          <tbody>
            {p.leverageByPartner.map(lp => (
              <tr key={lp.partner}>
                <td style={{ ...bl.td, fontWeight: 600, color: Tbp.color.text.primary }}>{lp.partner}</td>
                <td style={{ ...bl.td, color: Tbp.color.text.secondary }}>{lp.practice}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: bl.emerald, fontWeight: 700 }}>{bl.money(lp.originations)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.primary }}>{bl.money(lp.workingRevenue)}</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.secondary }}>{lp.associates}a · {lp.paralegals}p</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: lp.leverage >= 3 ? bl.emerald : bl.amber, fontWeight: 700 }}>{lp.leverage.toFixed(1)}x</td>
                <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: bl.emerald, fontWeight: 700 }}>{bl.money(lp.margin)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BillingBudgets({ data }) {
  const bl = window.__bl;

  const statusStyle = (s) => s === 'On track' ? { bg: bl.emeraldBg, color: bl.emerald }
    : s === 'Watch' ? { bg: bl.amberBg, color: bl.amber }
    : { bg: bl.crimsonBg, color: bl.crimson };

  const overBudget = data.budgets.filter(b => b.status === 'Over budget').length;
  const watch = data.budgets.filter(b => b.status === 'Watch').length;
  const onTrack = data.budgets.filter(b => b.status === 'On track').length;
  const totalBudget = data.budgets.reduce((s, b) => s + b.budget, 0);
  const totalActual = data.budgets.reduce((s, b) => s + b.actual, 0);
  const totalEAC = data.budgets.reduce((s, b) => s + b.eac, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Matters budgeted</span><span style={bl.statValue}>{data.budgets.length}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>On track</span><span style={{ ...bl.statValue, color: bl.emerald }}>{onTrack}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Watch</span><span style={{ ...bl.statValue, color: bl.amber }}>{watch}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Over budget</span><span style={{ ...bl.statValue, color: bl.crimson }}>{overBudget}</span></div>
        <div style={bl.stat}>
          <span style={bl.statLabel}>Total EAC vs budget</span>
          <span style={{ ...bl.statValue, color: totalEAC > totalBudget ? bl.crimson : bl.emerald }}>{((totalEAC - totalBudget) / totalBudget * 100).toFixed(1)}%</span>
          <span style={{ ...bl.statDelta, color: Tbp.color.text.tertiary }}>{bl.money(totalEAC)} / {bl.money(totalBudget)}</span>
        </div>
      </div>

      {/* Alerts — over budget */}
      {data.budgets.filter(b => b.status === 'Over budget').length > 0 && (
        <div style={{ ...bl.card, borderLeft: `3px solid ${bl.crimson}` }}>
          <div style={{ ...bl.cardH, color: bl.crimson }}>! Matters over budget — client notification required</div>
          <div>
            {data.budgets.filter(b => b.status === 'Over budget').map(b => (
              <div key={b.matter} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tbp.color.border.light}`, display: 'flex', alignItems: 'center', gap: '16px' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tbp.color.text.primary }}>{b.matter}</div>
                  <div style={{ fontSize: '11px', color: Tbp.color.text.tertiary, marginTop: '2px' }}>{b.client} · Phase: {b.phase}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '10px', color: Tbp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>EAC vs budget</div>
                  <div style={{ fontSize: '14px', fontWeight: 700, color: bl.crimson, fontFamily: Tbp.font.mono }}>+{b.varPct.toFixed(1)}% ({bl.money(b.eac - b.budget)})</div>
                </div>
                <button style={bl.btnSecondary}>Notify client</button>
                <button style={bl.btnPrimary}>Budget amendment</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Budget table */}
      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>Matter budgets</span>
          <button style={bl.btnSecondary}>Variance report</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Matter</th>
              <th style={bl.th}>Phase</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Budget</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Actual</th>
              <th style={bl.th}>Burn</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>ETC</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>EAC</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Variance</th>
              <th style={bl.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.budgets.map(b => {
              const ss = statusStyle(b.status);
              const burnColor = b.burnPct > 80 ? bl.crimson : b.burnPct > 60 ? bl.amber : bl.emerald;
              return (
                <tr key={b.matter}>
                  <td style={{ ...bl.td, fontWeight: 600, color: Tbp.color.text.primary, maxWidth: '240px' }}>
                    {b.matter}
                    <div style={{ fontSize: '10px', color: Tbp.color.text.tertiary, marginTop: '2px' }}>{b.client}</div>
                  </td>
                  <td style={{ ...bl.td, color: Tbp.color.text.secondary }}>{b.phase}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.primary, fontWeight: 700 }}>{bl.money(b.budget)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.secondary }}>{bl.money(b.actual)}</td>
                  <td style={bl.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '80px', height: '4px', background: Tbp.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${Math.min(100, b.burnPct)}%`, height: '100%', background: burnColor }} />
                      </div>
                      <span style={{ fontFamily: Tbp.font.mono, fontSize: '11px', color: burnColor, fontWeight: 600, minWidth: '40px', textAlign: 'right' }}>{b.burnPct.toFixed(1)}%</span>
                    </div>
                  </td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: Tbp.color.text.tertiary }}>{bl.money(b.etc)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: b.eac > b.budget ? bl.crimson : Tbp.color.text.primary, fontWeight: 700 }}>{bl.money(b.eac)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbp.font.mono, color: b.varPct >= 0 ? bl.crimson : bl.emerald, fontWeight: 700 }}>{b.varPct >= 0 ? '+' : ''}{b.varPct.toFixed(1)}%</td>
                  <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{b.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.BillingProfitability = BillingProfitability;
window.BillingBudgets = BillingBudgets;
