// ESI DATA MAP — Views Part 2: Custodians · Source Readiness · Providers · Platform Entry
const { useState: useDMV2State } = React;
const Tdm2 = window.ArbiterTokens;

const riskBadge2 = (r, esi) => ({
  'high':   { bg: esi.crimsonBg, color: esi.crimson },
  'medium': { bg: esi.amberBg,  color: esi.amber },
  'low':    { bg: esi.cyanBg,   color: esi.cyan },
  'none':   { bg: esi.emeraldBg,color: esi.emerald },
}[r] || { bg: Tdm2.color.bg.secondary, color: Tdm2.color.text.tertiary });

function DataMapCustodians({ data }) {
  const esi = window.__esi;
  const dm = data.dataMapExt;
  const [selected, setSelected] = useDMV2State(null);
  const custodians = dm.custodianProfiles;
  const priorityColor = p => p === 'key' ? esi.crimson : p === 'high' ? esi.amber : esi.slate;

  const statusColor = (s, esi) => ({
    'collected':   { bg: esi.emeraldBg, color: esi.emerald, label: 'ok Collected' },
    'in-progress': { bg: esi.cyanBg,   color: esi.cyan,    label: '◑ In Progress' },
    'on-hold':     { bg: esi.amberBg,  color: esi.amber,   label: '○ Hold only' },
    'identified':  { bg: esi.violetBg, color: esi.violet,  label: '◌ Identified' },
    'gap':         { bg: esi.crimsonBg,color: esi.crimson, label: 'x Gap' },
  }[s] || { bg: Tdm2.color.bg.secondary, color: Tdm2.color.text.tertiary, label: s });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total custodians</span><span style={esi.statValue}>{custodians.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Key custodians</span><span style={{ ...esi.statValue, color: esi.crimson }}>{custodians.filter(c=>c.priority==='key').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Fully collected</span><span style={{ ...esi.statValue, color: esi.emerald }}>{custodians.filter(c=>c.sources.every(s=>s.status==='collected')).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg risk score</span><span style={{ ...esi.statValue, color: esi.amber }}>{Math.round(custodians.reduce((s,c)=>s+c.riskScore,0)/custodians.length)}</span><span style={{ ...esi.statDelta, color: Tdm2.color.text.tertiary }}>/100</span></div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
        {custodians.map(c => {
          const isSel = selected === c.name;
          const pc = priorityColor(c.priority);
          const collectedCount = c.sources.filter(s=>s.status==='collected').length;
          const pct = Math.round((collectedCount / c.sources.length) * 100);
          return (
            <div key={c.name} style={{ ...esi.card, marginBottom: 0, borderLeft: `3px solid ${pc}` }}>
              <div
                onClick={() => setSelected(isSel ? null : c.name)}
                style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: '220px 1fr 120px 120px 80px 100px', gap: '16px', alignItems: 'center', cursor: 'pointer' }}
              >
                <div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tdm2.color.text.primary }}>{c.name}</div>
                  <div style={{ fontSize: '11px', color: Tdm2.color.text.tertiary }}>{c.role} · {c.org}</div>
                </div>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tdm2.color.text.tertiary, marginBottom: '3px' }}>
                    <span>{collectedCount}/{c.sources.length} sources collected</span>
                    <span style={{ fontFamily: Tdm2.font.mono, color: pct === 100 ? esi.emerald : esi.cyan, fontWeight: 700 }}>{pct}%</span>
                  </div>
                  <div style={{ height: '8px', background: Tdm2.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: pct===100 ? esi.emerald : `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` }} />
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: Tdm2.font.mono, fontWeight: 700, color: Tdm2.color.text.primary }}>{esi.bytes(c.totalVolumeGB)}</div>
                  <div style={{ fontSize: '10px', color: Tdm2.color.text.tertiary }}>total volume</div>
                </div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <div style={{ fontSize: '11px', fontWeight: 700, color: c.riskScore > 80 ? esi.crimson : c.riskScore > 60 ? esi.amber : esi.emerald }}>{c.riskScore}</div>
                    <div style={{ flex: 1, height: '6px', background: Tdm2.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${c.riskScore}%`, height: '100%', background: c.riskScore > 80 ? esi.crimson : c.riskScore > 60 ? esi.amber : esi.emerald }} />
                    </div>
                  </div>
                  <div style={{ fontSize: '10px', color: Tdm2.color.text.tertiary, marginTop: '2px' }}>risk score</div>
                </div>
                <div><span style={{ ...esi.tag, background: `${pc}14`, color: pc }}>{c.priority}</span></div>
                <div style={{ textAlign: 'right', fontSize: '11px', color: esi.cyan, fontWeight: 600 }}>{isSel ? '− collapse' : '+ sources'}</div>
              </div>
              {isSel && (
                <div style={{ borderTop: `1px solid ${Tdm2.color.border.light}`, padding: '12px 16px' }}>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    {c.sources.map(src => {
                      const sc = statusColor(src.status, esi);
                      const rk = riskBadge2(src.risk, esi);
                      return (
                        <div key={src.srcId} style={{ padding: '10px 12px', borderRadius: '6px', background: Tdm2.color.bg.secondary, border: `1px solid ${Tdm2.color.border.light}`, minWidth: '180px' }}>
                          <div style={{ fontSize: '12px', fontWeight: 600, color: Tdm2.color.text.primary, marginBottom: '4px' }}>{src.name}</div>
                          <div style={{ fontSize: '10px', color: Tdm2.color.text.tertiary, marginBottom: '6px' }}>{src.type}</div>
                          <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                            <span style={{ ...esi.tag, background: sc.bg, color: sc.color, fontSize: '10px' }}>{sc.label}</span>
                            <span style={{ ...esi.tag, background: rk.bg, color: rk.color, fontSize: '10px' }}>Risk: {src.risk}</span>
                          </div>
                          <div style={{ marginTop: '6px', fontFamily: Tdm2.font.mono, fontSize: '11px', fontWeight: 700, color: Tdm2.color.text.primary }}>{src.volumeGB != null ? esi.bytes(src.volumeGB) : 'pending'}</div>
                          {src.collectedOn && <div style={{ fontSize: '10px', color: Tdm2.color.text.tertiary, marginTop: '2px' }}>Collected {src.collectedOn}</div>}
                        </div>
                      );
                    })}
                  </div>
                  <div style={{ marginTop: '10px', fontSize: '11px', color: Tdm2.color.text.tertiary }}>
                    Hold active since: <b style={{ fontFamily: Tdm2.font.mono, color: Tdm2.color.text.primary }}>{c.holdDate}</b>
                    {c.exitDate && <span> · Departed: <b style={{ fontFamily: Tdm2.font.mono, color: esi.amber }}>{c.exitDate}</b></span>}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DataMapSourceReadiness({ data }) {
  const esi = window.__esi;
  const dm = data.dataMapExt;
  const [riskFilter, setRiskFilter] = useDMV2State('All');
  const sources = dm.sourceReadiness;
  const risks = ['All', 'high', 'medium', 'low', 'none'];
  const rows = sources.filter(s => riskFilter === 'All' || s.risk === riskFilter);
  const totalVol = rows.reduce((s, r) => s + r.volumeGB, 0);

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.amber}`, background: esi.amberBg, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.amber, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ FRCP Rule 26(f) Source Readiness — {sources.filter(s=>s.risk==='high').length} high-risk sources require attention</div>
          <div style={{ fontSize: '11px', color: Tdm2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Status of all {sources.length} identified data sources against preservation, collection, and meet-and-confer obligations.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Sources shown</span><span style={esi.statValue}>{rows.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Volume</span><span style={{ ...esi.statValue, color: esi.cyan }}>{esi.bytes(totalVol)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Collected</span><span style={{ ...esi.statValue, color: esi.emerald }}>{rows.filter(r=>r.collected).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>High risk</span><span style={{ ...esi.statValue, color: esi.crimson }}>{rows.filter(r=>r.risk==='high').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg collected</span><span style={{ ...esi.statValue, color: esi.cyan }}>{Math.round(rows.reduce((s,r)=>s+r.collectionPct,0)/rows.length)}%</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Source readiness registry — {rows.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={riskFilter} onChange={e => setRiskFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tdm2.color.border.light}`, borderRadius: '5px', background: Tdm2.color.bg.card, color: Tdm2.color.text.secondary }}>
              {risks.map(r => <option key={r} value={r}>Risk: {r}</option>)}
            </select>
            <button style={esi.btnSecondary}>Export 26(f) schedule</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <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}>Custodians</th>
            <th style={esi.th}>Collection %</th><th style={esi.th}>Method</th>
            <th style={esi.th}>Risk</th><th style={esi.th}>Notes</th>
          </tr></thead>
          <tbody>
            {rows.map(s => {
              const rk = riskBadge2(s.risk, esi);
              const ss = esi.sourceStyle(s.type);
              return (
                <tr key={s.srcId}>
                  <td style={{ ...esi.td, fontWeight: 600, color: Tdm2.color.text.primary }}>{ss.icon} {s.name}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{s.type}</span></td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tdm2.color.text.secondary }}>{s.provider}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tdm2.font.mono, fontWeight: 700 }}>{esi.bytes(s.volumeGB)}</td>
                  <td style={{ ...esi.td, fontFamily: Tdm2.font.mono, color: Tdm2.color.text.secondary }}>{s.custodianCount ?? 'scope'}</td>
                  <td style={{ ...esi.td, minWidth: '100px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ flex: 1, height: '6px', background: Tdm2.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${s.collectionPct}%`, height: '100%', background: s.collected ? esi.emerald : esi.cyan }} />
                      </div>
                      <span style={{ fontFamily: Tdm2.font.mono, fontSize: '10px', color: Tdm2.color.text.secondary, minWidth: '32px' }}>{s.collectionPct}%</span>
                    </div>
                  </td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tdm2.color.text.secondary }}>{s.method}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: rk.bg, color: rk.color }}>{s.risk}</span></td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tdm2.color.text.secondary, maxWidth: '280px' }}>{s.notes}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DataMapProviders({ data }) {
  const esi = window.__esi;
  const providers = data.dataMapExt.providers;
  const maxVol = Math.max(...providers.map(p => p.volumeGB));
  const totalVol = providers.reduce((s, p) => s + p.volumeGB, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Providers</span><span style={esi.statValue}>{providers.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total volume</span><span style={esi.statValue}>{esi.bytes(totalVol)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>High-risk providers</span><span style={{ ...esi.statValue, color: esi.crimson }}>{providers.filter(p=>p.risk==='high').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Top concentration</span><span style={{ ...esi.statValue, color: esi.amber }}>{((providers[0]?.volumeGB||0)/totalVol*100).toFixed(0)}%</span><span style={{ ...esi.statDelta, color: Tdm2.color.text.tertiary }}>{providers[0]?.name}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>Provider volume concentration — sorted by exposure</div>
        <div style={{ padding: '16px' }}>
          {[...providers].sort((a, b) => b.volumeGB - a.volumeGB).map(p => {
            const rk = riskBadge2(p.risk, esi);
            const pct = (p.volumeGB / totalVol * 100).toFixed(1);
            return (
              <div key={p.name} style={{ marginBottom: '14px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '5px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <span style={{ fontSize: '13px', fontWeight: 700, color: Tdm2.color.text.primary, minWidth: '120px' }}>{p.name}</span>
                    <span style={{ ...esi.tag, background: rk.bg, color: rk.color }}>{p.risk} risk</span>
                    <span style={{ fontSize: '11px', color: Tdm2.color.text.tertiary }}>{p.sources} source{p.sources !== 1 ? 's' : ''}{p.custodians ? ` · ${p.custodians} custodians` : ''}</span>
                  </div>
                  <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                    <span style={{ fontFamily: Tdm2.font.mono, fontSize: '11px', color: Tdm2.color.text.tertiary }}>{pct}% of total</span>
                    <span style={{ fontFamily: Tdm2.font.mono, fontSize: '13px', fontWeight: 700, color: Tdm2.color.text.primary }}>{esi.bytes(p.volumeGB)}</span>
                  </div>
                </div>
                <div style={{ height: '12px', background: Tdm2.color.border.light, borderRadius: '4px', overflow: 'hidden', marginBottom: '4px' }}>
                  <div style={{ width: `${(p.volumeGB / maxVol) * 100}%`, height: '100%', background: p.risk === 'high' ? `linear-gradient(90deg, ${esi.crimson}, ${esi.amber})` : `linear-gradient(90deg, ${esi.cobalt}, ${esi.cyan})`, borderRadius: '4px' }} />
                </div>
                <div style={{ fontSize: '11px', color: Tdm2.color.text.tertiary, paddingLeft: '2px' }}>{p.notes}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── MAIN PLATFORM ENTRY ──────────────────────────────────────────────────────
function ESIDataMapPlatform({ data }) {
  const esi = window.__esi;
  const [activeView, setActiveView] = useDMV2State('overview');
  const views = [
    { id: 'overview',    label: 'Overview' },
    { id: 'heatmatrix',  label: 'Heat Matrix' },
    { id: 'custodians',  label: 'Custodians' },
    { id: 'readiness',   label: '26(f) Readiness' },
    { id: 'providers',   label: 'Provider Exposure' },
  ];
  const renderView = () => {
    switch (activeView) {
      case 'overview':   return <DataMapOverview data={data} />;
      case 'heatmatrix': return <DataMapHeatMatrix data={data} />;
      case 'custodians': return <DataMapCustodians data={data} />;
      case 'readiness':  return <DataMapSourceReadiness data={data} />;
      case 'providers':  return <DataMapProviders data={data} />;
      default:           return <DataMapOverview data={data} />;
    }
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: '4px', padding: '6px', background: Tdm2.color.bg.secondary, border: `1px solid ${Tdm2.color.border.light}`, borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
        {views.map(v => (
          <button key={v.id} onClick={() => setActiveView(v.id)} style={{
            padding: '6px 12px', fontSize: '11px', fontWeight: activeView === v.id ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: activeView === v.id ? esi.cobalt : 'transparent',
            color: activeView === v.id ? '#fff' : Tdm2.color.text.secondary,
            fontFamily: Tdm2.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {renderView()}
    </div>
  );
}

window.DataMapCustodians = DataMapCustodians;
window.DataMapSourceReadiness = DataMapSourceReadiness;
window.DataMapProviders = DataMapProviders;
window.ESIDataMapPlatform = ESIDataMapPlatform;
