const { useState } = React;
const T = window.ArbiterTokens;

const MONTHLY_SPEND = [
  { month: 'Nov', value: 680000 }, { month: 'Dec', value: 520000 },
  { month: 'Jan', value: 740000 }, { month: 'Feb', value: 810000 },
  { month: 'Mar', value: 920000 }, { month: 'Apr', value: 680000 },
];

const MATTER_SPEND = [
  { name: 'Pacific Shipping Antitrust', billed: 2100000, budget: 3500000 },
  { name: 'Greenfield Environmental', billed: 1340000, budget: 4000000 },
  { name: 'Chen v. Atlas Financial', billed: 1450000, budget: 1600000 },
  { name: 'Sterling Pharma FCPA', billed: 890000, budget: 2000000 },
  { name: 'Redstone v. Meridian', billed: 842000, budget: 1200000 },
  { name: 'Blackwell IP', billed: 567000, budget: 900000 },
];

const ATTORNEY_HOURS = [
  { name: 'M. Kirkland', role: 'Senior Partner', hours: 412, rate: 950, billed: 391400 },
  { name: 'S. Chen', role: 'Partner', hours: 387, rate: 850, billed: 328950 },
  { name: 'L. Torres', role: 'Senior Associate', hours: 624, rate: 550, billed: 343200 },
  { name: 'R. Vasquez', role: 'Partner', hours: 298, rate: 800, billed: 238400 },
  { name: 'A. Petrov', role: 'Associate', hours: 510, rate: 450, billed: 229500 },
  { name: 'J. Park', role: 'Associate', hours: 486, rate: 420, billed: 204120 },
];

const bStyles = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary, padding: '20px' },
  header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' },
  title: { fontSize: T.font.size.xl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight },
  statsRow: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '20px' },
  grid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' },
  section: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' },
  sectionHeader: { padding: '12px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary },
  chartArea: { padding: '16px' },
  barRow: { display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm },
  barLabel: { width: '180px', fontWeight: T.font.weight.medium, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  barTrack: { flex: 1, height: '8px', borderRadius: '4px', background: T.color.border.light, position: 'relative' },
  barFill: { height: '100%', borderRadius: '4px', transition: 'width 0.5s ease' },
  barValue: { minWidth: '64px', textAlign: 'right', fontSize: T.font.size.xs, fontFamily: T.font.mono, color: T.color.text.secondary },
};

function fmt(val) {
  if (val >= 1000000) return '$' + (val / 1000000).toFixed(1) + 'M';
  if (val >= 1000) return '$' + (val / 1000).toFixed(0) + 'K';
  return '$' + val;
}

// Simple inline bar chart
function SpendChart({ data }) {
  const max = Math.max(...data.map(d => d.value));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', height: '120px', padding: '0 4px' }}>
      {data.map((d, i) => (
        <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
          <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{fmt(d.value)}</span>
          <div style={{
            width: '100%', borderRadius: '3px 3px 0 0',
            height: `${(d.value / max) * 80}px`,
            background: i === data.length - 1 ? T.color.navy600 : T.color.navy200,
            transition: 'height 0.4s ease',
          }} />
          <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{d.month}</span>
        </div>
      ))}
    </div>
  );
}

function BillingView() {
  const [hoveredRow, setHoveredRow] = useState(null);

  const totalBilled = MATTER_SPEND.reduce((s, m) => s + m.billed, 0);
  const totalBudget = MATTER_SPEND.reduce((s, m) => s + m.budget, 0);
  const totalHours = ATTORNEY_HOURS.reduce((s, a) => s + a.hours, 0);

  return (
    <div style={bStyles.container}>
      <div style={bStyles.header}>
        <div style={bStyles.title}>Billing & Analytics</div>
        <button style={window.sharedStyles.btn}>Export Report</button>
      </div>

      <div style={bStyles.statsRow}>
        <StatCard label="Total Billed YTD" value={fmt(totalBilled)} delta="12% vs prior year" deltaType="up" />
        <StatCard label="Total Budget" value={fmt(totalBudget)} delta={`${Math.round(totalBilled/totalBudget*100)}% utilized`} deltaType="" />
        <StatCard label="Billable Hours" value={totalHours.toLocaleString()} delta="Avg 8.2h/day" deltaType="" />
        <StatCard label="Realization Rate" value="91%" delta="2.4% improvement" deltaType="up" />
      </div>

      <div style={bStyles.grid}>
        {/* Monthly spend chart */}
        <div style={bStyles.section}>
          <div style={bStyles.sectionHeader}>Monthly Spend Trend</div>
          <div style={bStyles.chartArea}>
            <SpendChart data={MONTHLY_SPEND} />
          </div>
        </div>

        {/* Attorney hours */}
        <div style={bStyles.section}>
          <div style={bStyles.sectionHeader}>Attorney Utilization</div>
          {ATTORNEY_HOURS.map((a, i) => (
            <div key={i} style={{...bStyles.barRow, background: hoveredRow === `a${i}` ? T.color.bg.hover : 'transparent'}}
              onMouseEnter={() => setHoveredRow(`a${i}`)} onMouseLeave={() => setHoveredRow(null)}>
              <div style={{ width: '120px' }}>
                <div style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{a.name}</div>
                <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{a.role}</div>
              </div>
              <div style={bStyles.barTrack}>
                <div style={{...bStyles.barFill, width: `${(a.hours / 700) * 100}%`, background: T.color.navy500 }} />
              </div>
              <div style={{ minWidth: '80px', textAlign: 'right' }}>
                <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, fontFamily: T.font.mono }}>{a.hours}h</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>{fmt(a.billed)}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Matter budget utilization */}
      <div style={bStyles.section}>
        <div style={bStyles.sectionHeader}>Matter Budget Utilization</div>
        {MATTER_SPEND.map((m, i) => {
          const pct = Math.round(m.billed / m.budget * 100);
          const overBudget = pct > 85;
          return (
            <div key={i} style={{...bStyles.barRow, background: hoveredRow === `m${i}` ? T.color.bg.hover : 'transparent'}}
              onMouseEnter={() => setHoveredRow(`m${i}`)} onMouseLeave={() => setHoveredRow(null)}>
              <div style={bStyles.barLabel}>{m.name}</div>
              <div style={bStyles.barTrack}>
                <div style={{...bStyles.barFill, width: `${pct}%`, background: overBudget ? T.color.status.warning : T.color.navy500}} />
              </div>
              <span style={{...bStyles.barValue, color: overBudget ? T.color.status.warning : T.color.text.secondary}}>
                {fmt(m.billed)} / {fmt(m.budget)} ({pct}%)
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.BillingView = BillingView;
