const { useState, useMemo } = React;
const T = window.ArbiterTokens;

// Evidence platform shared styles — premium ivory with teal accent
const ev = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary },
  header: {
    padding: '16px 24px', borderBottom: `1px solid ${T.color.border.light}`,
    background: T.color.bg.card, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  },
  headerTitle: { display: 'flex', alignItems: 'center', gap: '12px' },
  evIcon: {
    width: '32px', height: '32px', borderRadius: '6px',
    background: 'linear-gradient(135deg, #0D9488 0%, #0F766E 100%)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: '14px', fontWeight: 700, color: '#fff',
  },
  title: { fontSize: '18px', fontWeight: 700, color: T.color.text.primary, letterSpacing: '-0.02em' },
  subtitle: { fontSize: '12px', color: T.color.text.tertiary, marginTop: '1px' },
  tabs: {
    display: 'flex', gap: '0', borderBottom: `1px solid ${T.color.border.light}`,
    background: T.color.bg.card, padding: '0 24px',
  },
  tab: {
    padding: '10px 16px', fontSize: '12px', fontWeight: 500,
    color: T.color.text.tertiary, cursor: 'pointer', border: 'none', background: 'none',
    borderBottom: '2px solid transparent', fontFamily: T.font.family,
    transition: 'all 0.15s', marginBottom: '-1px',
  },
  tabActive: { color: '#0D9488', borderBottomColor: '#0D9488', fontWeight: 600 },
  body: { padding: '20px 24px' },
  card: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden', marginBottom: '16px' },
  cardH: { padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px', fontWeight: 600, color: T.color.text.primary, display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  stat: { display: 'flex', flexDirection: 'column', gap: '2px', padding: '12px 16px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` },
  statLabel: { fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' },
  statValue: { fontSize: '22px', fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1, color: T.color.text.primary },
  teal: '#0D9488',
  tealBg: 'rgba(13,148,136,0.06)',
  tealText: '#0D9488',
  tag: { display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 600 },
  filterBtn: { padding: '4px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '11px', fontWeight: 500, color: T.color.text.secondary, cursor: 'pointer', fontFamily: T.font.family },
  filterBtnActive: { background: '#0D9488', color: '#fff', borderColor: '#0D9488' },
  row: { padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '12px', transition: 'background 0.1s', cursor: 'pointer' },
  barTrack: { height: '6px', borderRadius: '3px', background: T.color.border.light },
  barFill: { height: '100%', borderRadius: '3px', transition: 'width 0.5s ease' },
};

window.ev = ev;

// ── VAULT TAB ──
function EvidenceVault({ data, onOpenDoc }) {
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState('All');
  const [sortBy, setSortBy] = useState('relevance');
  const [hovered, setHovered] = useState(null);
  const [expanded, setExpanded] = useState(null);

  const vault = data.vault;
  const types = ['All', ...new Set(vault.map(v => v.type))];

  const filtered = useMemo(() => {
    let items = vault;
    if (typeFilter !== 'All') items = items.filter(i => i.type === typeFilter);
    if (search) {
      const q = search.toLowerCase();
      items = items.filter(i => i.name.toLowerCase().includes(q) || i.bates.toLowerCase().includes(q) || i.aiTags.some(t => t.includes(q)));
    }
    if (sortBy === 'relevance') items = [...items].sort((a, b) => b.relevance - a.relevance);
    if (sortBy === 'date') items = [...items].sort((a, b) => b.dateCollected.localeCompare(a.dateCollected));
    if (sortBy === 'bates') items = [...items].sort((a, b) => a.bates.localeCompare(b.bates));
    return items;
  }, [search, typeFilter, sortBy, vault]);

  const hotDocs = vault.filter(v => v.hotDoc).length;
  const totalPages = vault.reduce((s, v) => s + v.pages, 0);

  const relevanceColor = (r) => r >= 85 ? T.color.status.active : r >= 65 ? T.color.status.warning : T.color.text.tertiary;
  const extColor = (ext) => ({ PDF: '#C23030', DOCX: '#2563EB', XLSX: '#1B7A4A', ZIP: '#6B21A8', MSG: '#B8860B' }[ext] || T.color.text.tertiary);

  return (
    <div>
      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={ev.stat}><span style={ev.statLabel}>Total Items</span><span style={ev.statValue}>{vault.length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Total Pages</span><span style={ev.statValue}>{totalPages.toLocaleString()}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Hot Documents</span><span style={{ ...ev.statValue, color: '#C23030' }}>{hotDocs}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Authenticated</span><span style={{ ...ev.statValue, color: T.color.status.active }}>{vault.filter(v => v.status === 'Authenticated').length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Under Review</span><span style={{ ...ev.statValue, color: T.color.status.warning }}>{vault.filter(v => v.reviewStatus === 'In Progress').length}</span></div>
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
        <input style={{ height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 12px', fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '260px' }} placeholder="Search by name, Bates, or tag..." value={search} onChange={e => setSearch(e.target.value)} />
        {types.slice(0, 8).map(t => (
          <button key={t} style={{ ...ev.filterBtn, ...(typeFilter === t ? ev.filterBtnActive : {}) }} onClick={() => setTypeFilter(t)}>{t}</button>
        ))}
        <div style={{ flex: 1 }} />
        <select style={{ ...ev.filterBtn, padding: '4px 8px' }} value={sortBy} onChange={e => setSortBy(e.target.value)}>
          <option value="relevance">Sort: Relevance</option>
          <option value="date">Sort: Date</option>
          <option value="bates">Sort: Bates #</option>
        </select>
      </div>

      {/* Table */}
      <div style={ev.card}>
        <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr 80px 80px 70px 60px 50px 70px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '8px' }}>
          <span>Bates</span><span>Document</span><span>Type</span><span>Custodian</span><span>Relevance</span><span>Status</span><span>Ext</span><span>Review</span>
        </div>
        {filtered.map((item, i) => (
          <React.Fragment key={item.id}>
            <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr 80px 80px 70px 60px 50px 70px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '8px', fontSize: '12px', background: hovered === i ? T.color.bg.hover : 'transparent', cursor: 'pointer' }}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}
              onDoubleClick={() => onOpenDoc && onOpenDoc(item.id)}
              onClick={() => setExpanded(expanded === i ? null : i)}>
              <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{item.bates.length > 14 ? item.bates.slice(0, 14) + '…' : item.bates}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                {item.hotDoc && <span style={{ fontSize: '10px', color: '#C23030' }}></span>}
                <div>
                  <div style={{ fontWeight: 500, color: T.color.text.primary }}>{item.name}</div>
                  <div style={{ display: 'flex', gap: '4px', marginTop: '2px', flexWrap: 'wrap' }}>
                    {item.aiTags.slice(0, 3).map((tag, j) => (
                      <span key={j} style={{ fontSize: '9px', padding: '1px 5px', borderRadius: '8px', background: ev.tealBg, color: ev.teal }}>{tag}</span>
                    ))}
                  </div>
                </div>
              </div>
              <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{item.type}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.custodian.split('(')[0].trim()}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                <div style={{ width: '28px', height: '4px', borderRadius: '2px', background: T.color.border.light }}>
                  <div style={{ width: `${item.relevance}%`, height: '100%', borderRadius: '2px', background: relevanceColor(item.relevance) }} />
                </div>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: relevanceColor(item.relevance) }}>{item.relevance}</span>
              </div>
              <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: item.status === 'Authenticated' ? T.color.status.activeBg : item.status === 'Under Review' ? T.color.status.warningBg : T.color.status.pendingBg, color: item.status === 'Authenticated' ? T.color.status.active : item.status === 'Under Review' ? T.color.status.warning : T.color.text.secondary }}>{item.status}</span>
              <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: `${extColor(item.ext)}10`, color: extColor(item.ext) }}>{item.ext}</span>
              <span style={{ fontSize: '9px', padding: '2px 6px', borderRadius: '8px', background: item.reviewStatus === 'Coded' ? T.color.status.activeBg : T.color.status.warningBg, color: item.reviewStatus === 'Coded' ? T.color.status.active : T.color.status.warning }}>{item.reviewStatus}</span>
            </div>
            {/* Expanded detail: Chain of custody */}
            {expanded === i && (
              <div style={{ padding: '12px 16px 12px 116px', borderBottom: `1px solid ${T.color.border.light}`, background: T.color.bg.secondary, fontSize: '11px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                  <div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '6px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Chain of Custody</div>
                    {item.chainOfCustody.map((c, j) => (
                      <div key={j} style={{ display: 'flex', gap: '8px', marginBottom: '4px' }}>
                        <span style={{ fontFamily: T.font.mono, color: T.color.text.tertiary, minWidth: '48px' }}>{c.date}</span>
                        <span style={{ color: T.color.text.secondary }}>{c.action}</span>
                        <span style={{ color: T.color.text.tertiary }}>— {c.by}</span>
                      </div>
                    ))}
                  </div>
                  <div>
                    <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '6px', fontSize: '10px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Details</div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 12px', fontSize: '11px' }}>
                      <span style={{ color: T.color.text.tertiary }}>Pages:</span><span>{item.pages}</span>
                      <span style={{ color: T.color.text.tertiary }}>Size:</span><span>{item.size}</span>
                      <span style={{ color: T.color.text.tertiary }}>Collected:</span><span>{item.dateCollected}</span>
                      <span style={{ color: T.color.text.tertiary }}>Created:</span><span>{item.dateCreated}</span>
                      <span style={{ color: T.color.text.tertiary }}>Privilege:</span><span>{item.privilege}</span>
                      <span style={{ color: T.color.text.tertiary }}>Reviewer:</span><span>{item.reviewer}</span>
                      {item.exhibitNum && <><span style={{ color: T.color.text.tertiary }}>Exhibit:</span><span style={{ fontWeight: 600, color: ev.teal }}>{item.exhibitNum}</span></>}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

window.EvidenceVault = EvidenceVault;
