// ESI PLATFORM — Processing + Search
const Tepr = window.ArbiterTokens;

function ESIProcessing({ data }) {
  const esi = window.__esi;
  const p = data.processing;
  const maxVol = p.stages[0].volumeGB;

  const colorMap = { slate: esi.slate, cyan: esi.cyan, cobalt: esi.cobalt, violet: esi.violet, amber: esi.amber, orange: esi.orange, emerald: esi.emerald };
  const maxLang = Math.max(...p.languages.map(l => l.count));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Raw ingest</span><span style={esi.statValue}>{(p.stages[0].docs / 1_000_000).toFixed(2)}M</span><span style={{ ...esi.statDelta, color: Tepr.color.text.tertiary }}>{esi.bytes(p.stages[0].volumeGB)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Review-ready</span><span style={{ ...esi.statValue, color: esi.emerald }}>{(p.stages[p.stages.length-1].docs / 1_000_000).toFixed(2)}M</span><span style={{ ...esi.statDelta, color: Tepr.color.text.tertiary }}>{esi.bytes(p.stages[p.stages.length-1].volumeGB)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total reduction</span><span style={{ ...esi.statValue, color: esi.cyan }}>{p.stages[p.stages.length-1].reductionPct}%</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>OCR confidence</span><span style={{ ...esi.statValue, color: esi.emerald }}>{p.ocrStats.confidenceAvg}%</span><span style={{ ...esi.statDelta, color: Tepr.color.text.tertiary }}>failure rate {p.ocrStats.failureRate}%</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Active jobs</span><span style={{ ...esi.statValue, color: esi.cyan }}>{p.activeJobs.length}</span></div>
      </div>

      {/* Funnel */}
      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Processing pipeline — {(p.stages[0].volumeGB / 1024).toFixed(2)} TB → {esi.bytes(p.stages[p.stages.length-1].volumeGB)}</span>
          <span style={{ fontSize: '10px', color: esi.emerald, fontWeight: 700, fontFamily: Tepr.font.mono }}>{p.stages[p.stages.length-1].reductionPct}% reduction</span>
        </div>
        <div style={{ padding: '16px' }}>
          {p.stages.map((s, i) => {
            const pct = (s.volumeGB / maxVol) * 100;
            const c = colorMap[s.color] || esi.cyan;
            return (
              <div key={s.stage} style={{ marginBottom: '14px', display: 'flex', alignItems: 'center', gap: '14px' }}>
                <div style={{ minWidth: '180px' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: c, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Stage {i + 1}</div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tepr.color.text.primary }}>{s.stage}</div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ height: '28px', background: Tepr.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: `linear-gradient(90deg, ${c} 0%, ${c}CC 100%)`, display: 'flex', alignItems: 'center', paddingLeft: '12px', color: '#fff', fontSize: '11px', fontWeight: 700, fontFamily: Tepr.font.mono }}>
                      {(s.docs / 1_000_000).toFixed(2)}M · {esi.bytes(s.volumeGB)}
                    </div>
                  </div>
                </div>
                <div style={{ minWidth: '80px', textAlign: 'right' }}>
                  <div style={{ fontSize: '10px', color: Tepr.color.text.tertiary }}>of raw</div>
                  <div style={{ fontSize: '14px', fontWeight: 700, color: c, fontFamily: Tepr.font.mono }}>{pct.toFixed(1)}%</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Languages + OCR */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Language breakdown</div>
          <div style={{ padding: '12px 16px' }}>
            {p.languages.map(l => (
              <div key={l.lang} style={{ padding: '6px 0', borderBottom: `1px solid ${Tepr.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', fontSize: '12px' }}>
                  <span style={{ color: Tepr.color.text.primary, fontWeight: 500 }}>{l.lang}</span>
                  <span style={{ display: 'flex', gap: '10px', fontFamily: Tepr.font.mono }}>
                    <span style={{ color: Tepr.color.text.secondary, fontSize: '11px' }}>{l.count.toLocaleString()}</span>
                    <span style={{ color: esi.cyan, fontWeight: 700, fontSize: '11px', minWidth: '42px', textAlign: 'right' }}>{l.pct}%</span>
                  </span>
                </div>
                <div style={{ height: '4px', background: Tepr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                  <div style={{ width: `${(l.count / maxLang) * 100}%`, height: '100%', background: esi.cyan }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>OCR + text-extraction stats</div>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '14px' }}>
              <div>
                <div style={{ fontSize: '10px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pages processed</div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: Tepr.color.text.primary, fontFamily: Tepr.font.mono }}>{(p.ocrStats.pagesProcessed / 1_000_000).toFixed(2)}M</div>
              </div>
              <div>
                <div style={{ fontSize: '10px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Avg confidence</div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: esi.emerald, fontFamily: Tepr.font.mono }}>{p.ocrStats.confidenceAvg}%</div>
              </div>
            </div>
            <div style={{ padding: '10px 12px', background: p.ocrStats.failureRate < 1 ? esi.emeraldBg : esi.amberBg, borderRadius: '6px', borderLeft: `3px solid ${p.ocrStats.failureRate < 1 ? esi.emerald : esi.amber}` }}>
              <div style={{ fontSize: '11px', color: p.ocrStats.failureRate < 1 ? esi.emerald : esi.amber, fontWeight: 600 }}>Failure rate: {p.ocrStats.failureRate}%</div>
              <div style={{ fontSize: '10px', color: Tepr.color.text.secondary, marginTop: '3px' }}>
                {p.ocrStats.failureRate < 1 ? 'Below 1% — within industry benchmark (2-3%)' : 'Above industry benchmark — review failed docs'}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ESISearch({ data }) {
  const esi = window.__esi;
  const s = data.search;
  const maxCluster = Math.max(...s.conceptClusters.map(c => c.docs));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Saved searches</span><span style={esi.statValue}>{s.savedSearches.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Concept clusters</span><span style={{ ...esi.statValue, color: esi.violet }}>{s.conceptClusters.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>TAR models</span><span style={{ ...esi.statValue, color: esi.cyan }}>{s.tarSummary.modelsActive}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>TAR recall</span><span style={{ ...esi.statValue, color: esi.emerald }}>{s.tarSummary.recall}%</span><span style={{ ...esi.statDelta, color: Tepr.color.text.tertiary }}>precision {s.tarSummary.precision}%</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Predicted relevant</span><span style={esi.statValue}>{s.tarSummary.predictedRelevant.toLocaleString()}</span></div>
      </div>

      {/* Saved searches */}
      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Saved searches — {s.savedSearches.length}</span>
          <button style={esi.btnPrimary}>+ New search</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>ID</th>
              <th style={esi.th}>Name</th>
              <th style={esi.th}>Query</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Hits</th>
              <th style={esi.th}>Run by</th>
              <th style={esi.th}>Last run</th>
            </tr>
          </thead>
          <tbody>
            {s.savedSearches.map(q => (
              <tr key={q.id}>
                <td style={{ ...esi.td, fontFamily: Tepr.font.mono, fontWeight: 700, color: esi.cyan }}>{q.id}</td>
                <td style={{ ...esi.td, fontWeight: 600, color: Tepr.color.text.primary, maxWidth: '260px' }}>{q.name}</td>
                <td style={{ ...esi.td, fontFamily: Tepr.font.mono, fontSize: '11px', color: Tepr.color.text.secondary, maxWidth: '420px' }}>{q.query}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tepr.font.mono, color: esi.cyan, fontWeight: 700 }}>{q.hits.toLocaleString()}</td>
                <td style={{ ...esi.td, color: Tepr.color.text.secondary }}>{q.runBy}</td>
                <td style={{ ...esi.td, fontFamily: Tepr.font.mono, fontSize: '11px', color: Tepr.color.text.tertiary }}>{q.dateRun}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Concept clusters + TAR summary */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Concept clusters — AI-derived</div>
          <div style={{ padding: '12px 16px' }}>
            {s.conceptClusters.map(c => (
              <div key={c.label} style={{ padding: '6px 0', borderBottom: `1px solid ${Tepr.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px', fontSize: '12px' }}>
                  <span style={{ color: Tepr.color.text.primary, fontWeight: 500 }}>{c.label}</span>
                  <span style={{ fontFamily: Tepr.font.mono, color: esi.violet, fontWeight: 700 }}>{c.docs.toLocaleString()}</span>
                </div>
                <div style={{ height: '4px', background: Tepr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                  <div style={{ width: `${(c.docs / maxCluster) * 100}%`, height: '100%', background: esi.violet }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>TAR / Predictive coding</div>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px' }}>
              <div>
                <div style={{ fontSize: '9px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Recall</div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: s.tarSummary.recall >= 85 ? esi.emerald : esi.amber, fontFamily: Tepr.font.mono }}>{s.tarSummary.recall}%</div>
              </div>
              <div>
                <div style={{ fontSize: '9px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Precision</div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: esi.cyan, fontFamily: Tepr.font.mono }}>{s.tarSummary.precision}%</div>
              </div>
              <div>
                <div style={{ fontSize: '9px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Stability</div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: s.tarSummary.stability === 'Stable' ? esi.emerald : esi.amber, marginTop: '4px' }}>{s.tarSummary.stability}</div>
              </div>
            </div>
            <div style={{ marginTop: '14px', paddingTop: '12px', borderTop: `1px solid ${Tepr.color.border.light}` }}>
              <div style={{ fontSize: '10px', color: Tepr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Predicted relevant</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: Tepr.color.text.primary, fontFamily: Tepr.font.mono }}>{s.tarSummary.predictedRelevant.toLocaleString()} docs</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ESIProcessing = ESIProcessing;
window.ESISearch = ESISearch;
