// BILLING PLATFORM — Rates + Realization
const Tbr = window.ArbiterTokens;

function BillingRates({ data }) {
  const bl = window.__bl;
  const rc = data.rateCard;
  const blendedStd = Math.round(rc.standard.reduce((s, r) => s + r.avg * r.headcount, 0) / rc.standard.reduce((s, r) => s + r.headcount, 0));

  const approvalColor = (s) => s === 'Approved' ? { bg: bl.emeraldBg, color: bl.emerald }
    : s.includes('CFO') ? { bg: bl.violetBg, color: bl.violet }
    : { bg: bl.amberBg, color: bl.amber };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={bl.stat}><span style={bl.statLabel}>Blended standard rate</span><span style={bl.statValue}>${blendedStd}</span><span style={{ ...bl.statDelta, color: Tbr.color.text.tertiary }}>weighted by headcount</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Timekeepers</span><span style={bl.statValue}>{rc.standard.reduce((s, r) => s + r.headcount, 0)}</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Client rate agreements</span><span style={{ ...bl.statValue, color: bl.teal }}>{rc.clientOverrides.length}</span><span style={{ ...bl.statDelta, color: Tbr.color.text.tertiary }}>active</span></div>
        <div style={bl.stat}><span style={bl.statLabel}>Pending requests</span><span style={{ ...bl.statValue, color: bl.amber }}>{rc.pendingRequests.filter(r => r.status !== 'Approved').length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        <div style={bl.card}>
          <div style={bl.cardH}>Standard rate card</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Role</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Low</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Avg</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>High</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Headcount</th>
              </tr>
            </thead>
            <tbody>
              {rc.standard.map(r => (
                <tr key={r.role}>
                  <td style={{ ...bl.td, fontWeight: 600, color: Tbr.color.text.primary }}>{r.role}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.tertiary }}>${r.low}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.primary, fontWeight: 700 }}>${r.avg}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>${r.high}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>{r.headcount}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={bl.card}>
          <div style={bl.cardH}>Client rate agreements</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Client</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Partner</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Assoc.</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Para.</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>vs Std</th>
              </tr>
            </thead>
            <tbody>
              {rc.clientOverrides.map(c => (
                <tr key={c.client}>
                  <td style={{ ...bl.td, maxWidth: '200px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tbr.color.text.primary }}>{c.client}</div>
                    <div style={{ fontSize: '10px', color: Tbr.color.text.tertiary }}>Effective {c.effective}</div>
                  </td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.primary, fontWeight: 700 }}>${c.partnerRate}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>${c.associateRate}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>${c.paralegalRate}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, fontWeight: 700, color: c.vsStandardPct >= 0 ? bl.emerald : bl.amber }}>
                    {c.vsStandardPct >= 0 ? '+' : ''}{c.vsStandardPct.toFixed(1)}%
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pending rate requests */}
      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>Rate change requests — {rc.pendingRequests.length}</span>
          <button style={bl.btnPrimary}>+ New request</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={bl.th}>Request</th>
              <th style={bl.th}>Client</th>
              <th style={bl.th}>Requested by</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Current</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Proposed</th>
              <th style={{ ...bl.th, textAlign: 'right' }}>Δ</th>
              <th style={bl.th}>Effective</th>
              <th style={bl.th}>Reason</th>
              <th style={bl.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {rc.pendingRequests.map(r => {
              const diffPct = ((r.proposed - r.current) / r.current) * 100;
              const ss = approvalColor(r.status);
              return (
                <tr key={r.id}>
                  <td style={{ ...bl.td, fontFamily: Tbr.font.mono, fontWeight: 600, color: Tbr.color.text.primary }}>{r.id}</td>
                  <td style={{ ...bl.td, color: Tbr.color.text.primary, fontWeight: 500 }}>{r.client}</td>
                  <td style={{ ...bl.td, color: Tbr.color.text.secondary }}>{r.requestedBy}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>${r.current}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.primary, fontWeight: 700 }}>${r.proposed}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, fontWeight: 700, color: diffPct >= 0 ? bl.emerald : bl.amber }}>
                    {diffPct >= 0 ? '+' : ''}{diffPct.toFixed(1)}%
                  </td>
                  <td style={{ ...bl.td, fontFamily: Tbr.font.mono, fontSize: '11px', color: Tbr.color.text.secondary }}>{r.effective}</td>
                  <td style={{ ...bl.td, color: Tbr.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{r.reason}</td>
                  <td style={bl.td}><span style={{ ...bl.tag, background: ss.bg, color: ss.color }}>{r.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BillingRealization({ data }) {
  const bl = window.__bl;
  const r = data.realization;
  const maxTrend = Math.max(...r.monthlyTrend.map(t => t.worked));

  return (
    <div>
      {/* Funnel */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '16px', marginBottom: '16px' }}>
        <div style={bl.card}>
          <div style={bl.cardH}>Work → Bill → Collect funnel (YTD)</div>
          <div style={{ padding: '20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            {[
              { label: 'Worked', value: r.funnel.worked, color: bl.slate, pct: 100 },
              { label: 'Billed', value: r.funnel.billed, color: bl.teal, pct: (r.funnel.billed / r.funnel.worked) * 100 },
              { label: 'Collected', value: r.funnel.collected, color: bl.emerald, pct: (r.funnel.collected / r.funnel.worked) * 100 },
            ].map((s, i, arr) => (
              <React.Fragment key={s.label}>
                <div style={{ textAlign: 'center', flex: 1 }}>
                  <div style={{ fontSize: '10px', textTransform: 'uppercase', color: Tbr.color.text.tertiary, letterSpacing: '0.08em', marginBottom: '4px' }}>{s.label}</div>
                  <div style={{ fontSize: '22px', fontWeight: 700, color: s.color, fontFamily: Tbr.font.mono }}>{bl.money(s.value)}</div>
                  <div style={{ fontSize: '11px', color: Tbr.color.text.secondary, marginTop: '2px' }}>{s.pct.toFixed(1)}% of worked</div>
                </div>
                {i < arr.length - 1 && (
                  <div style={{ flex: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', color: Tbr.color.text.tertiary }}>
                    <div style={{ fontSize: '20px', color: i === 0 ? bl.teal : bl.emerald }}>→</div>
                    <div style={{ fontSize: '11px', fontWeight: 700, color: i === 0 ? bl.realColor((arr[i + 1].value / s.value) * 100) : bl.realColor((arr[i + 1].value / s.value) * 100), fontFamily: Tbr.font.mono }}>
                      {((arr[i + 1].value / s.value) * 100).toFixed(1)}%
                    </div>
                  </div>
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={bl.card}>
          <div style={bl.cardH}>Write-down breakdown</div>
          <div style={{ padding: '10px 16px' }}>
            {r.writedowns.map(w => {
              const max = Math.max(...r.writedowns.map(x => x.amount));
              return (
                <div key={w.reason} style={{ padding: '6px 0', borderBottom: `1px solid ${Tbr.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', fontSize: '12px' }}>
                    <span style={{ color: Tbr.color.text.primary, fontWeight: 500 }}>{w.reason}</span>
                    <span style={{ display: 'flex', gap: '10px' }}>
                      <span style={{ fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary, fontSize: '11px' }}>{w.count}×</span>
                      <span style={{ fontFamily: Tbr.font.mono, color: bl.amber, fontSize: '11px', fontWeight: 700, minWidth: '60px', textAlign: 'right' }}>{bl.money(w.amount)}</span>
                    </span>
                  </div>
                  <div style={{ height: '3px', background: Tbr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                    <div style={{ width: `${(w.amount / max) * 100}%`, height: '100%', background: bl.amber }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Monthly trend */}
      <div style={bl.card}>
        <div style={bl.cardH}>
          <span>Monthly trend — Worked / Billed / Collected (12 months)</span>
          <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>
            <span style={{ color: bl.slate }}>■ Worked</span>
            <span style={{ color: bl.teal }}>■ Billed</span>
            <span style={{ color: bl.emerald }}>■ Collected</span>
          </div>
        </div>
        <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '8px', alignItems: 'flex-end', height: '180px' }}>
          {r.monthlyTrend.map(t => (
            <div key={t.m} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
              <div style={{ display: 'flex', gap: '2px', alignItems: 'flex-end', height: '140px', width: '100%', justifyContent: 'center' }}>
                <div style={{ width: '28%', height: `${(t.worked / maxTrend) * 100}%`, background: bl.slate, opacity: 0.6, borderRadius: '2px 2px 0 0' }} />
                <div style={{ width: '28%', height: `${(t.billed / maxTrend) * 100}%`, background: bl.teal, borderRadius: '2px 2px 0 0' }} />
                <div style={{ width: '28%', height: `${(t.collected / maxTrend) * 100}%`, background: bl.emerald, borderRadius: '2px 2px 0 0' }} />
              </div>
              <span style={{ fontSize: '9px', color: Tbr.color.text.tertiary, fontFamily: Tbr.font.mono }}>{t.m}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* By matter */}
        <div style={bl.card}>
          <div style={bl.cardH}>Realization by matter</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={bl.th}>Matter</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Worked</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Billed</th>
                <th style={{ ...bl.th, textAlign: 'right' }}>Collected</th>
                <th style={bl.th}>Overall</th>
              </tr>
            </thead>
            <tbody>
              {r.byMatter.map(m => (
                <tr key={m.matter}>
                  <td style={{ ...bl.td, fontSize: '11px', fontWeight: 600, color: Tbr.color.text.primary, maxWidth: '180px' }}>{m.matter}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>{bl.money(m.worked)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: bl.teal }}>{bl.money(m.billed)}</td>
                  <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: bl.emerald }}>{bl.money(m.collected)}</td>
                  <td style={bl.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '50px', height: '4px', background: Tbr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${m.overallPct}%`, height: '100%', background: bl.realColor(m.overallPct) }} />
                      </div>
                      <span style={{ fontFamily: Tbr.font.mono, fontSize: '11px', color: bl.realColor(m.overallPct), fontWeight: 700, minWidth: '40px', textAlign: 'right' }}>{m.overallPct.toFixed(1)}%</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* By attorney + practice */}
        <div>
          <div style={bl.card}>
            <div style={bl.cardH}>By attorney</div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={bl.th}>Attorney</th>
                  <th style={{ ...bl.th, textAlign: 'right' }}>Hours</th>
                  <th style={{ ...bl.th, textAlign: 'right' }}>Collected</th>
                  <th style={{ ...bl.th, textAlign: 'right' }}>Overall</th>
                </tr>
              </thead>
              <tbody>
                {r.byAttorney.map(a => (
                  <tr key={a.attorney}>
                    <td style={{ ...bl.td, fontSize: '11px', fontWeight: 600, color: Tbr.color.text.primary }}>{a.attorney}<div style={{ fontSize: '10px', color: Tbr.color.text.tertiary }}>{a.role}</div></td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: Tbr.color.text.secondary }}>{a.hours.toLocaleString()}</td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: bl.emerald }}>{bl.money(a.collected)}</td>
                    <td style={{ ...bl.td, textAlign: 'right', fontFamily: Tbr.font.mono, color: bl.realColor(a.overallPct), fontWeight: 700 }}>{a.overallPct.toFixed(1)}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={bl.card}>
            <div style={bl.cardH}>By practice area</div>
            <div style={{ padding: '10px 16px' }}>
              {r.byPractice.map(p => (
                <div key={p.practice} style={{ padding: '6px 0', borderBottom: `1px solid ${Tbr.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', fontSize: '12px' }}>
                    <span style={{ color: Tbr.color.text.primary, fontWeight: 500 }}>{p.practice}</span>
                    <span style={{ fontFamily: Tbr.font.mono, color: bl.realColor(p.overallPct), fontWeight: 700 }}>{p.overallPct.toFixed(1)}%</span>
                  </div>
                  <div style={{ height: '4px', background: Tbr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                    <div style={{ width: `${p.overallPct}%`, height: '100%', background: bl.realColor(p.overallPct) }} />
                  </div>
                  <div style={{ fontSize: '10px', color: Tbr.color.text.tertiary, marginTop: '2px', fontFamily: Tbr.font.mono }}>{bl.money(p.worked)} worked → {bl.money(p.collected)} collected</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.BillingRates = BillingRates;
window.BillingRealization = BillingRealization;
