// ESI PLATFORM — Cost Analytics + Activity
// (Chain of Custody extracted to its own sub-platform — see ESIChain.jsx)
const Tecost = window.ArbiterTokens;

function ESICost({ data }) {
  const esi = window.__esi;
  const c = data.cost;
  const maxMonth = Math.max(...c.monthly12.map(m => m.cost));
  const maxCat = Math.max(...c.byCategory.map(x => x.ytd));

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.emerald}`, background: esi.emeraldBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Cost efficiency — {c.savingsVsIndustry}% below industry benchmark</div>
          <div style={{ fontSize: '11px', color: Tecost.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Firm at <b style={{ color: Tecost.color.text.primary, fontFamily: Tecost.font.mono }}>${c.avgPerGB.toFixed(2)}/GB</b> vs industry avg <b style={{ fontFamily: Tecost.font.mono }}>${c.industryPerGB.toFixed(2)}/GB</b>. YTD spend <b style={{ color: Tecost.color.text.primary, fontFamily: Tecost.font.mono }}>{esi.money(c.perMatterYTD)}</b>.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>MTD cost</span><span style={esi.statValue}>{esi.money(c.perMatterMTD)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>YTD cost</span><span style={esi.statValue}>{esi.money(c.perMatterYTD)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>$/GB</span><span style={{ ...esi.statValue, color: esi.emerald }}>${c.avgPerGB.toFixed(2)}</span><span style={{ ...esi.statDelta, color: Tecost.color.text.tertiary }}>vs ${c.industryPerGB} industry</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Savings vs industry</span><span style={{ ...esi.statValue, color: esi.emerald }}>{c.savingsVsIndustry}%</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Cost trend</span><span style={{ ...esi.statValue, color: esi.amber }}>↑ 145%</span><span style={{ ...esi.statDelta, color: Tecost.color.text.tertiary }}>YoY (matter scale)</span></div>
      </div>

      {/* 12-month trend */}
      <div style={esi.card}>
        <div style={esi.cardH}><span>ESI cost trend — 12 months</span><span style={{ fontSize: '10px', color: Tecost.color.text.tertiary }}>total: {esi.money(c.monthly12.reduce((s, m) => s + m.cost, 0))}</span></div>
        <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '8px', alignItems: 'flex-end', height: '180px' }}>
          {c.monthly12.map((m, i) => {
            const isLast = i === c.monthly12.length - 1;
            return (
              <div key={m.m} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
                <span style={{ fontSize: '10px', fontFamily: Tecost.font.mono, color: isLast ? esi.cyan : Tecost.color.text.tertiary, fontWeight: isLast ? 700 : 400 }}>${(m.cost / 1000).toFixed(0)}K</span>
                <div style={{ width: '100%', height: `${(m.cost / maxMonth) * 140}px`, background: `linear-gradient(180deg, ${esi.cyanLight} 0%, ${esi.cyan} 100%)`, opacity: isLast ? 1 : 0.7, borderRadius: '3px 3px 0 0' }} />
                <span style={{ fontSize: '9px', color: Tecost.color.text.tertiary, fontFamily: Tecost.font.mono }}>{m.m}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* By category */}
      <div style={esi.card}>
        <div style={esi.cardH}>Cost breakdown by category</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Category</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>MTD</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>YTD</th>
              <th style={esi.th}>% of YTD</th>
            </tr>
          </thead>
          <tbody>
            {c.byCategory.map(x => (
              <tr key={x.category}>
                <td style={{ ...esi.td, fontWeight: 600, color: Tecost.color.text.primary }}>{x.category}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tecost.font.mono, color: Tecost.color.text.secondary }}>{esi.money(x.mtd)}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tecost.font.mono, color: Tecost.color.text.primary, fontWeight: 700 }}>{esi.money(x.ytd)}</td>
                <td style={esi.td}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{ width: '180px', height: '6px', background: Tecost.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${(x.ytd / maxCat) * 100}%`, height: '100%', background: esi.cyan }} />
                    </div>
                    <span style={{ fontFamily: Tecost.font.mono, color: esi.cyan, fontWeight: 700, minWidth: '42px', textAlign: 'right' }}>{x.pct}%</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ESIActivity({ data }) {
  const esi = window.__esi;
  const sev = (s) => s === 'error' ? { bg: esi.crimsonBg, color: esi.crimson }
    : s === 'warn' ? { bg: esi.amberBg, color: esi.amber }
    : { bg: esi.emeraldBg, color: esi.emerald };

  return (
    <div style={esi.card}>
      <div style={esi.cardH}>
        <span>Activity log — {data.activity.length} events</span>
        <button style={esi.btnSecondary}>Export CSV</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={esi.th}>Time</th>
            <th style={esi.th}>Actor</th>
            <th style={esi.th}>Action</th>
            <th style={esi.th}>Target</th>
            <th style={esi.th}>Severity</th>
          </tr>
        </thead>
        <tbody>
          {data.activity.map(ev => {
            const ss = sev(ev.severity);
            return (
              <tr key={ev.id}>
                <td style={{ ...esi.td, fontFamily: Tecost.font.mono, color: Tecost.color.text.tertiary, fontSize: '11px' }}>{ev.time}</td>
                <td style={{ ...esi.td, color: Tecost.color.text.primary, fontWeight: 500 }}>
                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: ss.color, marginRight: '8px' }} />
                  {ev.actor}
                </td>
                <td style={{ ...esi.td, color: Tecost.color.text.secondary }}>{ev.action}</td>
                <td style={{ ...esi.td, color: Tecost.color.text.primary, fontWeight: 500, maxWidth: '440px' }}>{ev.target}</td>
                <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{ev.severity}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.ESICost = ESICost;
window.ESIActivity = ESIActivity;
