// ESI DATA MAP — Views Part 1: Overview + Heat Matrix
const { useState: useDMV1State } = React;
const Tdm1 = window.ArbiterTokens;

// ─── Shared helpers ───────────────────────────────────────────────────────────
const statusCell = (status, esi) => ({
  'collected':   { bg: esi.emerald,  label: '●' },
  'in-progress': { bg: esi.cyan,     label: '◑' },
  'on-hold':     { bg: esi.amber,    label: '○' },
  'identified':  { bg: esi.violet,   label: '◌' },
  'gap':         { bg: esi.crimson,  label: 'x' },
}[status] || { bg: Tdm1.color.border.light, label: '' });

const riskBadge = (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: Tdm1.color.bg.secondary, color: Tdm1.color.text.tertiary });

function DataMapOverview({ data }) {
  const esi = window.__esi;
  const dm = data.dataMapExt;
  const custodians = dm.custodianProfiles;
  const sources = dm.sourceReadiness;

  const totalVol = custodians.reduce((s, c) => s + c.totalVolumeGB, 0);
  const collected = sources.filter(s => s.collected).length;
  const highRisk = sources.filter(s => s.risk === 'high').length;
  const avgRisk = Math.round(custodians.reduce((s, c) => s + c.riskScore, 0) / custodians.length);

  // Volume by type
  const byType = {};
  sources.forEach(s => { byType[s.type] = (byType[s.type] || 0) + s.volumeGB; });
  const typeRows = Object.entries(byType).sort((a, b) => b[1] - a[1]);
  const maxTypeVol = typeRows[0]?.[1] || 1;

  // Provider concentration
  const byProvider = {};
  sources.forEach(s => { byProvider[s.provider] = (byProvider[s.provider] || 0) + s.volumeGB; });
  const provRows = Object.entries(byProvider).sort((a, b) => b[1] - a[1]).slice(0, 6);
  const maxProvVol = provRows[0]?.[1] || 1;

  return (
    <div>
      {/* Compliance banner */}
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.cyan}`, background: esi.cyanBg, marginBottom: '14px' }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: esi.cyan, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ ESI Data Map — Zubulake V · FRCP Rule 26(f) · ISO 27050-2</div>
            <div style={{ fontSize: '12px', color: Tdm1.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              Complete inventory of <b style={{ color: Tdm1.color.text.primary }}>{custodians.length} custodians</b> across <b>{sources.length} data sources</b> and <b>{esi.bytes(totalVol)}</b> total scoped volume.{' '}
              <b style={{ color: esi.emerald }}>{collected} sources fully collected.</b>{' '}
              <b style={{ color: esi.crimson }}>{highRisk} high-risk sources</b> require immediate action.
            </div>
          </div>
          <div style={{ display: 'flex', gap: '6px', flexShrink: 0 }}>
            <button style={esi.btnSecondary}>Export 26(f) map</button>
            <button style={{ ...esi.btnPrimary, background: esi.cyan }}>+ Add source</button>
          </div>
        </div>
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Custodians', v: custodians.length, d: `${custodians.filter(c=>c.priority==='key').length} key`, c: null },
          { l: 'Data sources', v: sources.length, d: null, c: null },
          { l: 'Total volume', v: esi.bytes(totalVol), d: 'scoped', c: null },
          { l: 'Collected', v: collected, d: `${sources.length - collected} remaining`, c: esi.emerald },
          { l: 'High risk', v: highRisk, d: 'sources', c: esi.crimson },
          { l: 'On hold only', v: sources.filter(s=>!s.collected && s.risk !== 'high').length, d: 'not collected', c: esi.amber },
          { l: 'Providers', v: Object.keys(byProvider).length, d: null, c: null },
          { l: 'Avg risk score', v: `${avgRisk}`, d: '/100', c: avgRisk > 70 ? esi.crimson : avgRisk > 50 ? esi.amber : esi.emerald },
        ].map(s => (
          <div key={s.l} style={esi.stat}>
            <span style={esi.statLabel}>{s.l}</span>
            <span style={{ ...esi.statValue, color: s.c || Tdm1.color.text.primary }}>{s.v}</span>
            {s.d && <span style={{ ...esi.statDelta, color: Tdm1.color.text.tertiary }}>{s.d}</span>}
          </div>
        ))}
      </div>

      {/* Two-column: volume by type + provider concentration */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Volume by source type</div>
          <div style={{ padding: '14px 16px' }}>
            {typeRows.map(([type, gb]) => {
              const ss = esi.sourceStyle(type);
              return (
                <div key={type} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                    <span style={{ color: Tdm1.color.text.primary, fontWeight: 500 }}>{ss.icon} {type}</span>
                    <span style={{ fontFamily: Tdm1.font.mono, color: esi.cyan, fontWeight: 700 }}>{esi.bytes(gb)}</span>
                  </div>
                  <div style={{ height: '8px', background: Tdm1.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(gb / maxTypeVol) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>Provider concentration (top 6)</div>
          <div style={{ padding: '14px 16px' }}>
            {provRows.map(([prov, gb]) => {
              const p = dm.providers.find(p => p.name === prov);
              const rc = p ? riskBadge(p.risk, esi) : { bg: Tdm1.color.bg.secondary, color: Tdm1.color.text.tertiary };
              return (
                <div key={prov} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px', alignItems: 'center' }}>
                    <span style={{ color: Tdm1.color.text.primary, fontWeight: 500 }}>{prov}</span>
                    <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                      <span style={{ ...esi.tag, background: rc.bg, color: rc.color, fontSize: '10px' }}>{p?.risk || '—'}</span>
                      <span style={{ fontFamily: Tdm1.font.mono, color: esi.cyan, fontWeight: 700 }}>{esi.bytes(gb)}</span>
                    </div>
                  </div>
                  <div style={{ height: '8px', background: Tdm1.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(gb / maxProvVol) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cobalt}, ${esi.cyan})` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Collection status summary */}
      <div style={esi.card}>
        <div style={esi.cardH}>Collection status — all sources at a glance</div>
        <div style={{ padding: '12px 16px', display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
          {[
            { label: 'Fully collected', color: esi.emerald, count: sources.filter(s => s.collected).length },
            { label: 'In progress', color: esi.cyan, count: sources.filter(s => !s.collected && s.collectionPct > 0).length },
            { label: 'Hold only', color: esi.amber, count: sources.filter(s => s.collectionPct === 0 && s.risk !== 'high').length },
            { label: 'High risk / gap', color: esi.crimson, count: sources.filter(s => s.risk === 'high').length },
          ].map(item => (
            <div key={item.label} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <div style={{ width: '12px', height: '12px', borderRadius: '50%', background: item.color, flexShrink: 0 }} />
              <span style={{ fontSize: '12px', color: Tdm1.color.text.secondary }}>{item.label}</span>
              <span style={{ fontFamily: Tdm1.font.mono, fontSize: '13px', fontWeight: 700, color: item.color }}>{item.count}</span>
            </div>
          ))}
        </div>
        <div style={{ padding: '0 16px 12px', display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
          {sources.map(s => {
            const pct = s.collectionPct;
            const col = s.collected ? esi.emerald : pct > 0 ? esi.cyan : s.risk === 'high' ? esi.crimson : esi.amber;
            return (
              <div key={s.srcId} title={`${s.name} — ${pct}% collected · ${s.risk} risk`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '3px', width: '44px' }}>
                <div style={{ width: '100%', height: '32px', background: Tdm1.color.border.light, borderRadius: '4px', overflow: 'hidden', position: 'relative' }}>
                  <div style={{ position: 'absolute', bottom: 0, left: 0, width: '100%', height: `${pct}%`, background: col, transition: 'height 0.3s' }} />
                </div>
                <span style={{ fontSize: '9px', color: Tdm1.color.text.tertiary, textAlign: 'center', lineHeight: 1.2, fontFamily: Tdm1.font.mono }}>{pct}%</span>
              </div>
            );
          })}
        </div>
        <div style={{ padding: '4px 16px 10px', fontSize: '10px', color: Tdm1.color.text.tertiary }}>Each bar = one data source. Height = % collected. Hover for details.</div>
      </div>
    </div>
  );
}

// ─── Heat Matrix ──────────────────────────────────────────────────────────────
function DataMapHeatMatrix({ data }) {
  const esi = window.__esi;
  const dm = data.dataMapExt;
  const custodians = dm.custodianProfiles;
  const types = dm.sourceTypes;
  const [hovered, setHovered] = useDMV1State(null);

  // Build matrix: for each custodian × type find the highest-volume source
  const getCell = (cust, type) => {
    const src = cust.sources.find(s => s.type === type);
    if (!src) return null;
    return src;
  };

  const maxVol = Math.max(...custodians.flatMap(c => c.sources.map(s => s.volumeGB || 0)));

  const cellBg = (src, esi) => {
    if (!src) return 'transparent';
    const intensity = Math.min(1, (src.volumeGB || 1) / maxVol);
    const base = {
      'collected':   esi.emerald,
      'in-progress': esi.cyan,
      'on-hold':     esi.amber,
      'identified':  esi.violet,
      'gap':         esi.crimson,
    }[src.status] || esi.slate;
    // Vary opacity by volume
    const opacity = 0.2 + intensity * 0.75;
    return `${base}${Math.round(opacity * 255).toString(16).padStart(2, '0')}`;
  };

  const CELL_W = 58, CELL_H = 32, LABEL_W = 160;

  return (
    <div>
      {/* Legend */}
      <div style={{ ...esi.card, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px', display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' }}>
          <span style={{ fontSize: '11px', fontWeight: 700, color: Tdm1.color.text.secondary, marginRight: '8px' }}>Legend:</span>
          {[
            { status: 'collected',   label: 'Collected',   color: esi.emerald },
            { status: 'in-progress', label: 'In Progress', color: esi.cyan },
            { status: 'on-hold',     label: 'Hold only',   color: esi.amber },
            { status: 'identified',  label: 'Identified',  color: esi.violet },
          ].map(l => (
            <span key={l.status} style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '11px', color: Tdm1.color.text.secondary }}>
              <span style={{ width: '12px', height: '12px', borderRadius: '2px', background: l.color, display: 'inline-block' }} />
              {l.label}
            </span>
          ))}
          <span style={{ marginLeft: '12px', fontSize: '11px', color: Tdm1.color.text.tertiary }}>Cell opacity = relative data volume</span>
        </div>
      </div>

      <div style={{ overflowX: 'auto' }}>
        <div style={{ minWidth: `${LABEL_W + types.length * CELL_W + 40}px` }}>
          {/* Column headers */}
          <div style={{ display: 'flex', marginBottom: '2px', paddingLeft: `${LABEL_W}px` }}>
            {types.map(t => {
              const ss = esi.sourceStyle(t);
              return (
                <div key={t} style={{ width: `${CELL_W}px`, textAlign: 'center', padding: '4px 2px' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: Tdm1.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.04em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{ss.icon}</div>
                  <div style={{ fontSize: '9px', color: Tdm1.color.text.tertiary, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.split('/')[0]}</div>
                </div>
              );
            })}
            <div style={{ width: '40px', textAlign: 'right', padding: '4px 4px', fontSize: '9px', color: Tdm1.color.text.tertiary }}>Volume</div>
          </div>

          {/* Rows */}
          {custodians.map((c, ci) => {
            const pr = c.priority === 'key' ? esi.crimson : c.priority === 'high' ? esi.amber : esi.slate;
            return (
              <div key={c.name} style={{ display: 'flex', alignItems: 'center', marginBottom: '2px', borderRadius: '4px', background: ci % 2 === 0 ? Tdm1.color.bg.secondary : 'transparent' }}>
                {/* Custodian label */}
                <div style={{ width: `${LABEL_W}px`, padding: '4px 8px', flexShrink: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <div style={{ width: '3px', height: '20px', borderRadius: '1px', background: pr, flexShrink: 0 }} />
                    <div>
                      <div style={{ fontSize: '12px', fontWeight: 600, color: Tdm1.color.text.primary, whiteSpace: 'nowrap' }}>{c.name}</div>
                      <div style={{ fontSize: '10px', color: Tdm1.color.text.tertiary }}>{c.role}</div>
                    </div>
                  </div>
                </div>

                {/* Cells */}
                {types.map(type => {
                  const src = getCell(c, type);
                  const bg = cellBg(src, esi);
                  const sc = src ? statusCell(src.status, esi) : null;
                  const key = `${c.name}-${type}`;
                  const isHov = hovered === key;
                  return (
                    <div
                      key={type}
                      onMouseEnter={() => setHovered(key)}
                      onMouseLeave={() => setHovered(null)}
                      style={{
                        width: `${CELL_W}px`, height: `${CELL_H}px`, flexShrink: 0,
                        background: bg, borderRadius: '3px', margin: '1px',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        position: 'relative', cursor: src ? 'pointer' : 'default',
                        outline: isHov ? `2px solid ${esi.cyan}` : 'none',
                        transition: 'outline 0.1s',
                      }}
                      title={src ? `${c.name} · ${src.name} · ${esi.bytes(src.volumeGB || 0)} · ${src.status}` : `${c.name} has no ${type} source`}
                    >
                      {src && <span style={{ fontSize: '13px', color: '#fff', textShadow: '0 0 4px rgba(0,0,0,0.4)' }}>{sc.label}</span>}
                      {isHov && src && (
                        <div style={{ position: 'absolute', bottom: '110%', left: '50%', transform: 'translateX(-50%)', background: Tdm1.color.bg.sidebar, color: Tdm1.color.ivory100, padding: '6px 10px', borderRadius: '5px', fontSize: '11px', whiteSpace: 'nowrap', zIndex: 100, boxShadow: '0 4px 12px rgba(0,0,0,0.2)' }}>
                          <div style={{ fontWeight: 700 }}>{src.name}</div>
                          <div style={{ color: '#96A3BD', marginTop: '2px' }}>{esi.bytes(src.volumeGB || 0)} · {src.status}</div>
                        </div>
                      )}
                    </div>
                  );
                })}

                {/* Volume bar */}
                <div style={{ width: '40px', paddingLeft: '4px' }}>
                  <div style={{ fontSize: '10px', fontFamily: Tdm1.font.mono, fontWeight: 700, color: Tdm1.color.text.secondary }}>{esi.bytes(c.totalVolumeGB)}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.DataMapOverview = DataMapOverview;
window.DataMapHeatMatrix = DataMapHeatMatrix;
