// ESI PLATFORM — Data Map + Preservation
const Tedm = window.ArbiterTokens;

function ESIDataMap({ data }) {
  const esi = window.__esi;
  // Build type totals across all custodians
  const typeTotals = {};
  data.dataMap.forEach(c => c.sources.forEach(src => {
    const type = src.includes('Exchange') || src.includes('Gmail') || src.includes('PST') ? 'Email'
      : src.includes('OneDrive') || src.includes('Drive') || src.includes('Box') ? 'Cloud Storage'
      : src.includes('Teams') || src.includes('Slack') || src.includes('WhatsApp') ? 'Chat'
      : src.includes('iPhone') || src.includes('Android') ? 'Mobile'
      : src.includes('Laptop') || src.includes('macOS') || src.includes('Windows') ? 'Laptop'
      : src.includes('SAP') ? 'ERP/Finance'
      : src.includes('GitHub') ? 'DevOps'
      : src.includes('Intralinks') || src.includes('Bloomberg') ? 'SaaS'
      : 'Other';
    typeTotals[type] = (typeTotals[type] || 0) + 1;
  }));

  const priorityColor = (p) => p === 'key' ? { bg: esi.crimsonBg, color: esi.crimson }
    : p === 'high' ? { bg: esi.amberBg, color: esi.amber }
    : { bg: Tedm.color.bg.secondary, color: Tedm.color.text.secondary };

  return (
    <div>
      <div style={esi.card}>
        <div style={{ padding: '12px 16px', background: esi.cyanBg, fontSize: '12px', color: Tedm.color.text.secondary, lineHeight: 1.6, borderLeft: `3px solid ${esi.cyan}` }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: esi.cyan, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ Data Map — custodian × source coverage</div>
          Visual inventory of where each custodian's discoverable ESI lives. Dark cells indicate active-hold coverage. Critical for Zubulake V preservation duty and Rule 26(f) meet-and-confer.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Custodians mapped</span><span style={esi.statValue}>{data.dataMap.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total volume</span><span style={esi.statValue}>{esi.bytes(data.dataMap.reduce((s, c) => s + c.volumeGB, 0))}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Key custodians</span><span style={{ ...esi.statValue, color: esi.crimson }}>{data.dataMap.filter(c => c.priority === 'key').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg sources/custodian</span><span style={esi.statValue}>{(data.dataMap.reduce((s, c) => s + c.sources.length, 0) / data.dataMap.length).toFixed(1)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Source types</span><span style={esi.statValue}>{Object.keys(typeTotals).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Max sources</span><span style={esi.statValue}>{Math.max(...data.dataMap.map(c => c.sources.length))}</span><span style={{ ...esi.statDelta, color: Tedm.color.text.tertiary }}>per custodian</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Custodian data map — {data.dataMap.length} custodians × sources</span>
          <button style={esi.btnSecondary}>Export map</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Custodian</th>
              <th style={esi.th}>Role</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Sources</th>
              <th style={esi.th}>Source coverage</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Volume</th>
              <th style={esi.th}>Priority</th>
            </tr>
          </thead>
          <tbody>
            {data.dataMap.map(c => {
              const pc = priorityColor(c.priority);
              return (
                <tr key={c.custodian}>
                  <td style={{ ...esi.td, fontWeight: 600, color: Tedm.color.text.primary }}>{c.custodian}</td>
                  <td style={{ ...esi.td, color: Tedm.color.text.secondary, fontSize: '11px' }}>{c.role}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tedm.font.mono, color: esi.cyan, fontWeight: 700 }}>{c.sources.length}</td>
                  <td style={esi.td}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', maxWidth: '540px' }}>
                      {c.sources.map(src => {
                        // pick icon based on simple rules
                        const type = src.includes('Exchange') || src.includes('Gmail') || src.includes('PST') ? 'Email'
                          : src.includes('OneDrive') || src.includes('Drive') || src.includes('Box') ? 'Cloud Storage'
                          : src.includes('Teams') || src.includes('Slack') || src.includes('WhatsApp') ? 'Chat'
                          : src.includes('iPhone') || src.includes('Android') || src.includes('Mobile') ? 'Mobile'
                          : src.includes('Laptop') || src.includes('macOS') || src.includes('Windows') ? 'Laptop'
                          : src.includes('SAP') ? 'ERP/Finance'
                          : src.includes('GitHub') ? 'DevOps'
                          : src.includes('Intralinks') || src.includes('Bloomberg') || src.includes('DMS') || src.includes('iManage') ? 'SaaS'
                          : 'Other';
                        const ss = esi.sourceStyle(type);
                        return <span key={src} title={src} style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{ss.icon} {src.length > 30 ? src.slice(0, 28) + '…' : src}</span>;
                      })}
                    </div>
                  </td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tedm.font.mono, color: Tedm.color.text.primary, fontWeight: 700 }}>{esi.bytes(c.volumeGB)}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: pc.bg, color: pc.color }}>{c.priority}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ESIPreservation({ data }) {
  const esi = window.__esi;
  const p = data.preservation;

  return (
    <div>
      {/* Compliance banner */}
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.violet}`, background: esi.violetBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Preservation posture — FRCP 37(e) / Zubulake V / ISO 27050-2</div>
          <div style={{ fontSize: '11px', color: Tedm.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            All {p.dataSourcesOnHold} data sources on active hold. Auto-suspended {p.suspendedRetentionPolicies} retention policies to prevent auto-deletion. Monthly snapshot cadence verified.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Active holds</span><span style={{ ...esi.statValue, color: esi.violet }}>{p.activeHolds}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Custodians covered</span><span style={esi.statValue}>{p.custodiansCoveredThisMatter}</span><span style={{ ...esi.statDelta, color: Tedm.color.text.tertiary }}>of {p.custodiansCoveredAll} firm-wide</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Sources on hold</span><span style={esi.statValue}>{p.dataSourcesOnHold}</span><span style={{ ...esi.statDelta, color: esi.emerald }}>100% coverage</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Snapshots MTD</span><span style={esi.statValue}>{p.snapshotsThisMonth}</span><span style={{ ...esi.statDelta, color: Tedm.color.text.tertiary }}>{p.snapshotsQTD} QTD · {p.snapshotsYTD} YTD</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Retention suspended</span><span style={{ ...esi.statValue, color: esi.amber }}>{p.suspendedRetentionPolicies}</span><span style={{ ...esi.statDelta, color: Tedm.color.text.tertiary }}>policies paused</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Next audit</span><span style={{ ...esi.statValue, fontSize: '16px', fontFamily: Tedm.font.mono, marginTop: '4px' }}>{p.nextAuditDate}</span><span style={{ ...esi.statDelta, color: Tedm.color.text.tertiary }}>last {p.lastAuditDate}</span></div>
      </div>

      {/* Snapshot timeline visualization */}
      <div style={esi.card}>
        <div style={esi.cardH}><span>Snapshot cadence — 12-month sparkline</span><span style={{ fontSize: '10px', color: Tedm.color.text.tertiary }}>avg interval {p.avgSnapshotInterval} days</span></div>
        <div style={{ padding: '20px 16px', display: 'flex', gap: '4px', alignItems: 'flex-end', height: '80px' }}>
          {Array.from({ length: 12 }).map((_, i) => {
            const n = 8 + Math.round(Math.sin(i / 2) * 3 + (i > 9 ? 2 : 0));
            const max = 16;
            const pct = (n / max) * 100;
            return (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '3px' }}>
                <div style={{ width: '100%', height: `${pct}%`, background: esi.violet, borderRadius: '2px 2px 0 0' }} />
                <div style={{ fontSize: '9px', color: Tedm.color.text.tertiary, fontFamily: Tedm.font.mono }}>M-{11-i}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Compliance matrix */}
      <div style={esi.card}>
        <div style={esi.cardH}>Compliance standards coverage</div>
        <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}>
          {p.complianceStandards.map(s => (
            <div key={s} style={{ padding: '10px 12px', background: esi.violetBg, borderRadius: '6px', border: `1px solid ${esi.violet}22`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: '12px', fontWeight: 600, color: esi.violet }}>{s}</span>
              <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>ok compliant</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.ESIDataMap = ESIDataMap;
window.ESIPreservation = ESIPreservation;
