// ESI PLATFORM — Dashboard + Data Sources
const { useState: useESIDashState, useMemo: useESIDashMemo } = React;
const Tesd = window.ArbiterTokens;

function ESIDashboard({ data }) {
  const esi = window.__esi;
  const k = data.kpis;
  const proc = data.processing.stages;
  const maxVol = proc[0].volumeGB;

  // 6 stages for EDRM-style pipeline
  const stages = [
    { name: 'Identify', count: data.sources.length, color: 'slate' },
    { name: 'Preserve', count: data.preservation.dataSourcesOnHold, color: 'violet' },
    { name: 'Collect',  count: data.collections.filter(c => c.status !== 'Complete ok').length, color: 'cyan' },
    { name: 'Forensic', count: data.forensicImages.filter(f => f.status === 'Imaged').length, color: 'teal' },
    { name: 'Process',  count: data.processing.activeJobs.length, color: 'cobalt' },
    { name: 'Host',     count: data.hosting.length, color: 'emerald' },
  ];

  return (
    <div>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Data sources</span><span style={esi.statValue}>{k.dataSources}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>{k.custodians} custodians</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total volume</span><span style={esi.statValue}>{esi.bytes(k.totalVolumeGB)}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>preserved</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Review-ready</span><span style={{ ...esi.statValue, color: esi.emerald }}>{esi.bytes(k.reviewableGB)}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>−{k.reductionPct}% from raw</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Active jobs</span><span style={{ ...esi.statValue, color: esi.cyan }}>{k.activeCollectionJobs + k.activeProcessingJobs}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>{k.activeCollectionJobs} collect · {k.activeProcessingJobs} process</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Monthly cost</span><span style={esi.statValue}>{esi.money(k.monthlyCost)}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>${k.costPerGB}/GB</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Chain events</span><span style={esi.statValue}>{k.chainEvents}</span><span style={{ ...esi.statDelta, color: esi.emerald }}>100% verified</span></div>
      </div>

      {/* EDRM pipeline */}
      <div style={esi.card}>
        <div style={esi.cardH}>ESI lifecycle — active at each stage</div>
        <div style={{ padding: '14px 16px', display: 'flex', gap: '8px' }}>
          {stages.map((s, i) => {
            const colorMap = { slate: esi.slate, violet: esi.violet, cyan: esi.cyan, teal: esi.teal, cobalt: esi.cobalt, emerald: esi.emerald };
            const bg = { slate: esi.slateBg, violet: esi.violetBg, cyan: esi.cyanBg, teal: esi.tealBg, cobalt: esi.cobaltBg, emerald: esi.emeraldBg };
            const c = colorMap[s.color];
            return (
              <div key={s.name} style={{ flex: 1, position: 'relative' }}>
                <div style={{ padding: '10px 8px', background: bg[s.color], border: `1px solid ${c}22`, borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: c, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>{s.name}</div>
                  <div style={{ fontSize: '22px', fontWeight: 700, color: c, fontFamily: Tesd.font.mono }}>{s.count}</div>
                </div>
                {i < stages.length - 1 && (
                  <div style={{ position: 'absolute', right: '-4px', top: '50%', transform: 'translateY(-50%)', color: Tesd.color.text.tertiary, fontSize: '10px' }}>›</div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px', marginBottom: '16px' }}>
        {/* Corpus reduction funnel */}
        <div style={esi.card}>
          <div style={esi.cardH}>
            <span>Corpus reduction — {(proc[0].volumeGB / 1024).toFixed(2)} TB → {esi.bytes(proc[proc.length-1].volumeGB)}</span>
            <span style={{ fontSize: '10px', color: esi.emerald, fontWeight: 700, fontFamily: Tesd.font.mono }}>{proc[proc.length-1].reductionPct}% reduction</span>
          </div>
          <div style={{ padding: '14px 16px' }}>
            {proc.map((s, i) => {
              const pct = (s.volumeGB / maxVol) * 100;
              const colorMap = { slate: esi.slate, cyan: esi.cyan, cobalt: esi.cobalt, violet: esi.violet, amber: esi.amber, orange: esi.orange, emerald: esi.emerald };
              const c = colorMap[s.color] || esi.cyan;
              return (
                <div key={s.stage} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                    <span style={{ color: Tesd.color.text.primary, fontWeight: 600 }}>{i + 1}. {s.stage}</span>
                    <span style={{ display: 'flex', gap: '10px', fontFamily: Tesd.font.mono }}>
                      <span style={{ color: Tesd.color.text.secondary, fontSize: '11px' }}>{esi.bytes(s.volumeGB)}</span>
                      <span style={{ color: c, fontWeight: 700, fontSize: '11px', minWidth: '48px', textAlign: 'right' }}>{s.reductionPct > 0 ? `−${s.reductionPct}%` : '100%'}</span>
                    </span>
                  </div>
                  <div style={{ height: '16px', background: Tesd.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: `linear-gradient(90deg, ${c} 0%, ${c}CC 100%)` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Alerts + compliance */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
          <div style={{ ...esi.card, marginBottom: 0, borderLeft: `3px solid ${esi.cyan}` }}>
            <div style={{ ...esi.cardH, color: esi.cyan }}>Operations</div>
            <div style={{ padding: '10px 16px' }}>
              {[
                { label: 'Active collection jobs', value: k.activeCollectionJobs, color: esi.cyan },
                { label: 'Active processing jobs', value: k.activeProcessingJobs, color: esi.cyan },
                { label: 'Forensic images on file', value: k.forensicImages, color: esi.teal },
                { label: 'Hosting platforms', value: data.hosting.length, color: esi.emerald },
                { label: 'Vendors engaged', value: k.vendorCount, color: esi.violet },
              ].map(a => (
                <div key={a.label} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                  <span style={{ color: Tesd.color.text.secondary }}>{a.label}</span>
                  <span style={{ color: a.color, fontWeight: 700, fontFamily: Tesd.font.mono }}>{a.value}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{ ...esi.card, marginBottom: 0, borderLeft: `3px solid ${esi.violet}` }}>
            <div style={{ ...esi.cardH, color: esi.violet }}>Preservation &amp; compliance</div>
            <div style={{ padding: '10px 16px' }}>
              <div style={{ fontSize: '10px', color: Tesd.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Standards</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '10px' }}>
                {data.preservation.complianceStandards.map(s => <span key={s} style={{ ...esi.tag, background: esi.violetBg, color: esi.violet }}>{s}</span>)}
              </div>
              <div style={{ fontSize: '11px', color: Tesd.color.text.secondary, lineHeight: 1.55 }}>
                Last audit <b style={{ color: Tesd.color.text.primary, fontFamily: Tesd.font.mono }}>{data.preservation.lastAuditDate}</b> · next <b style={{ color: esi.violet, fontFamily: Tesd.font.mono }}>{data.preservation.nextAuditDate}</b>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Active processing jobs */}
      <div style={esi.card}>
        <div style={esi.cardH}>Active processing jobs — {data.processing.activeJobs.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Job</th>
              <th style={esi.th}>Source</th>
              <th style={esi.th}>Stage</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>In flight</th>
              <th style={esi.th}>Started</th>
              <th style={esi.th}>ETA</th>
            </tr>
          </thead>
          <tbody>
            {data.processing.activeJobs.map(j => (
              <tr key={j.id}>
                <td style={{ ...esi.td, fontFamily: Tesd.font.mono, fontWeight: 700, color: esi.cyan }}>{j.id}</td>
                <td style={{ ...esi.td, fontWeight: 500, color: Tesd.color.text.primary }}>{j.source}</td>
                <td style={esi.td}><span style={{ ...esi.tag, background: esi.cyanBg, color: esi.cyan }}>{j.stage}</span></td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tesd.font.mono, fontWeight: 700, color: Tesd.color.text.primary }}>{j.inflight.toLocaleString()}</td>
                <td style={{ ...esi.td, fontFamily: Tesd.font.mono, fontSize: '11px', color: Tesd.color.text.tertiary }}>{j.started}</td>
                <td style={{ ...esi.td, fontFamily: Tesd.font.mono, fontSize: '11px', color: esi.amber }}>{j.eta}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ESIDataSources({ data }) {
  const esi = window.__esi;
  const [typeFilter, setTypeFilter] = useESIDashState('All');
  const [providerFilter, setProviderFilter] = useESIDashState('All');

  const types = useESIDashMemo(() => ['All', ...new Set(data.sources.map(s => s.type))], [data]);
  const providers = useESIDashMemo(() => ['All', ...new Set(data.sources.map(s => s.provider))], [data]);

  const filtered = data.sources.filter(s =>
    (typeFilter === 'All' || s.type === typeFilter) &&
    (providerFilter === 'All' || s.provider === providerFilter)
  );

  const totalVol = data.sources.reduce((sum, s) => sum + s.volumeGB, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total sources</span><span style={esi.statValue}>{data.sources.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Preserved</span><span style={{ ...esi.statValue, color: esi.emerald }}>{data.sources.filter(s => s.preserved).length}</span><span style={{ ...esi.statDelta, color: Tesd.color.text.tertiary }}>100% coverage</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Providers</span><span style={esi.statValue}>{new Set(data.sources.map(s => s.provider)).size}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Types</span><span style={esi.statValue}>{new Set(data.sources.map(s => s.type)).size}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total volume</span><span style={esi.statValue}>{esi.bytes(totalVol)}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Data source inventory — {filtered.length} of {data.sources.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tesd.color.border.light}`, borderRadius: '5px', background: Tesd.color.bg.card, color: Tesd.color.text.secondary }}>
              {types.map(t => <option key={t} value={t}>Type: {t}</option>)}
            </select>
            <select value={providerFilter} onChange={e => setProviderFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tesd.color.border.light}`, borderRadius: '5px', background: Tesd.color.bg.card, color: Tesd.color.text.secondary }}>
              {providers.map(p => <option key={p} value={p}>Provider: {p}</option>)}
            </select>
            <button style={esi.btnSecondary}>Export CSV</button>
            <button style={esi.btnPrimary}>+ Add source</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>ID</th>
              <th style={esi.th}>Source</th>
              <th style={esi.th}>Type</th>
              <th style={esi.th}>Provider</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Volume</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Custodians</th>
              <th style={esi.th}>Hold</th>
              <th style={esi.th}>Last collected</th>
              <th style={esi.th}>Notes</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(s => {
              const ss = esi.sourceStyle(s.type);
              return (
                <tr key={s.id}>
                  <td style={{ ...esi.td, fontFamily: Tesd.font.mono, color: esi.cyan, fontWeight: 700 }}>{s.id}</td>
                  <td style={{ ...esi.td, fontWeight: 600, color: Tesd.color.text.primary, maxWidth: '260px' }}>{s.name}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{ss.icon} {s.type}</span></td>
                  <td style={{ ...esi.td, color: Tesd.color.text.secondary, fontSize: '11px' }}>{s.provider}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tesd.font.mono, color: Tesd.color.text.primary, fontWeight: 700 }}>{esi.bytes(s.volumeGB)}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tesd.font.mono, color: Tesd.color.text.secondary }}>{s.custodians ?? '—'}</td>
                  <td style={esi.td}>{s.preserved ? <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>ok hold</span> : <span style={{ ...esi.tag, background: esi.crimsonBg, color: esi.crimson }}>none</span>}</td>
                  <td style={{ ...esi.td, fontFamily: Tesd.font.mono, fontSize: '11px', color: Tesd.color.text.tertiary }}>{s.lastCollected}</td>
                  <td style={{ ...esi.td, color: Tesd.color.text.secondary, fontSize: '11px', maxWidth: '320px', lineHeight: 1.5 }}>{s.notes}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.ESIDashboard = ESIDashboard;
window.ESIDataSources = ESIDataSources;
