const { useState, useEffect, useCallback, useRef } = React;
const T = window.ArbiterTokens;

// ── DOCUMENT VIEWER — Split pane with metadata + coding ──
function DocumentViewer({ data, initialDocId, onClose }) {
  const vault = data.vault;
  const [activeDocIdx, setActiveDocIdx] = useState(() => {
    const idx = vault.findIndex(v => v.id === initialDocId);
    return idx >= 0 ? idx : 0;
  });
  const [activePanel, setActivePanel] = useState('metadata'); // metadata | coding | annotations
  const [annotations, setAnnotations] = useState([]);
  const [newAnnotation, setNewAnnotation] = useState('');
  const [codingValues, setCodingValues] = useState({});
  const [highlights, setHighlights] = useState([]);
  const listRef = useRef(null);

  const doc = vault[activeDocIdx];

  // Initialize coding from doc
  useEffect(() => {
    if (doc) {
      setCodingValues({
        responsiveness: doc.reviewStatus === 'Coded' ? 'responsive' : '',
        privilege: doc.privilege === 'None' ? 'none' : 'ac',
        confidentiality: 'confidential',
        hotDoc: doc.hotDoc,
        issues: doc.aiTags.slice(0, 4),
      });
      setAnnotations([
        ...(doc.hotDoc ? [{ id: 1, author: doc.reviewer, time: 'Apr 16', text: 'Flagged as hot document — key evidence for case theory.', type: 'flag' }] : []),
        ...(doc.relevance >= 85 ? [{ id: 2, author: 'AI', time: 'Auto', text: `High relevance score (${doc.relevance}%). AI identified ${doc.aiTags.length} relevant tags.`, type: 'ai' }] : []),
      ]);
    }
  }, [activeDocIdx]);

  // Keyboard nav
  useEffect(() => {
    const handler = (e) => {
      if (e.key === 'ArrowDown' || e.key === 'j') { e.preventDefault(); setActiveDocIdx(i => Math.min(i + 1, vault.length - 1)); }
      if (e.key === 'ArrowUp' || e.key === 'k') { e.preventDefault(); setActiveDocIdx(i => Math.max(i - 1, 0)); }
      if (e.key === 'Escape') onClose();
      // Coding shortcuts
      if (e.key === 'r' && !e.metaKey && !e.ctrlKey && activePanel === 'coding') setCodingValues(v => ({...v, responsiveness: 'responsive'}));
      if (e.key === 'n' && !e.metaKey && !e.ctrlKey && activePanel === 'coding') setCodingValues(v => ({...v, responsiveness: 'non-responsive'}));
      if (e.key === 'h' && !e.metaKey && !e.ctrlKey && activePanel === 'coding') setCodingValues(v => ({...v, hotDoc: !v.hotDoc}));
      if (e.key === 'p' && !e.metaKey && !e.ctrlKey && activePanel === 'coding') setCodingValues(v => ({...v, privilege: v.privilege === 'none' ? 'ac' : 'none'}));
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [activePanel, vault.length, onClose]);

  const addAnnotation = () => {
    if (!newAnnotation.trim()) return;
    setAnnotations(prev => [...prev, { id: Date.now(), author: 'M. Kirkland', time: 'Now', text: newAnnotation, type: 'note' }]);
    setNewAnnotation('');
  };

  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);

  if (!doc) return null;

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9998, background: T.color.bg.primary, display: 'flex', flexDirection: 'column' }}>
      {/* Top bar */}
      <div style={{ height: '44px', minHeight: '44px', background: T.color.bg.card, borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', padding: '0 16px', gap: '12px' }}>
        <button onClick={onClose} style={{ padding: '4px 10px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '13px', color: T.color.text.secondary, cursor: 'pointer', fontFamily: T.font.family }}>← Back to Vault</button>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '8px' }}>
          {doc.hotDoc && <span style={{ fontSize: '12px' }}></span>}
          <span style={{ fontWeight: 600, fontSize: '13px', color: T.color.text.primary }}>{doc.name}</span>
          <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{doc.bates}</span>
          <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: `${extColor(doc.ext)}10`, color: extColor(doc.ext) }}>{doc.ext}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '11px', color: T.color.text.tertiary }}>
          <span>{activeDocIdx + 1} of {vault.length}</span>
          <button onClick={() => setActiveDocIdx(i => Math.max(i-1, 0))} style={{ padding: '2px 8px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', background: T.color.bg.card, cursor: 'pointer', fontSize: '12px', color: T.color.text.secondary }}>↑</button>
          <button onClick={() => setActiveDocIdx(i => Math.min(i+1, vault.length-1))} style={{ padding: '2px 8px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', background: T.color.bg.card, cursor: 'pointer', fontSize: '12px', color: T.color.text.secondary }}>↓</button>
        </div>
      </div>

      {/* Main split */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Doc list sidebar */}
        <div ref={listRef} style={{ width: '240px', minWidth: '240px', borderRight: `1px solid ${T.color.border.light}`, overflow: 'auto', background: T.color.bg.secondary }}>
          {vault.map((v, i) => (
            <div key={v.id} onClick={() => setActiveDocIdx(i)} style={{
              padding: '8px 12px', borderBottom: `1px solid ${T.color.border.light}`, cursor: 'pointer',
              background: i === activeDocIdx ? T.color.bg.card : 'transparent',
              borderLeft: i === activeDocIdx ? `3px solid ${ev.teal}` : '3px solid transparent',
              transition: 'background 0.1s',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                {v.hotDoc && <span style={{ fontSize: '9px' }}></span>}
                <span style={{ fontSize: '11px', fontWeight: i === activeDocIdx ? 600 : 400, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v.name}</span>
              </div>
              <div style={{ fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary, marginTop: '2px' }}>{v.bates.length > 18 ? v.bates.slice(0,18)+'…' : v.bates}</div>
            </div>
          ))}
        </div>

        {/* Document preview area */}
        <div style={{ flex: 1, background: '#E8E4DF', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
          {/* Simulated document */}
          <div style={{ width: '600px', minHeight: '780px', background: '#fff', borderRadius: '2px', boxShadow: '0 2px 16px rgba(0,0,0,0.12)', padding: '48px 56px', position: 'relative' }}>
            <div style={{ fontSize: '9px', fontFamily: T.font.mono, color: '#999', position: 'absolute', top: '16px', right: '20px' }}>{doc.bates}</div>
            <div style={{ fontSize: '16px', fontWeight: 700, color: '#1a1a1a', marginBottom: '8px', lineHeight: 1.3 }}>{doc.name}</div>
            <div style={{ fontSize: '10px', color: '#888', marginBottom: '20px' }}>{doc.type} · {doc.category} · {doc.pages} pages · {doc.size}</div>
            <div style={{ height: '1px', background: '#ddd', marginBottom: '20px' }} />
            {/* Simulated content lines */}
            {Array.from({ length: 18 }).map((_, i) => (
              <div key={i} style={{ height: '8px', background: i === 4 || i === 11 ? 'rgba(13,148,136,0.15)' : '#f0f0f0', borderRadius: '2px', marginBottom: '8px', width: i === 0 ? '45%' : i === 8 ? '30%' : i === 17 ? '60%' : `${70 + Math.sin(i) * 20}%` }} />
            ))}
            {doc.hotDoc && (
              <div style={{ position: 'absolute', top: '16px', left: '20px', fontSize: '9px', fontWeight: 700, padding: '2px 8px', borderRadius: '8px', background: 'rgba(194,48,48,0.1)', color: '#C23030', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Hot Document</div>
            )}
            {/* Highlight indicators */}
            <div style={{ position: 'absolute', left: '40px', top: '188px', width: '4px', height: '12px', borderRadius: '2px', background: ev.teal, opacity: 0.6 }} />
            <div style={{ position: 'absolute', left: '40px', top: '300px', width: '4px', height: '12px', borderRadius: '2px', background: '#F59E0B', opacity: 0.6 }} />
          </div>
          {/* Zoom controls */}
          <div style={{ position: 'absolute', bottom: '16px', right: '16px', display: 'flex', gap: '4px' }}>
            <button style={{ width: '28px', height: '28px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '14px', cursor: 'pointer', color: T.color.text.secondary }}>−</button>
            <span style={{ padding: '4px 8px', fontSize: '11px', color: T.color.text.tertiary, background: T.color.bg.card, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>100%</span>
            <button style={{ width: '28px', height: '28px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '14px', cursor: 'pointer', color: T.color.text.secondary }}>+</button>
          </div>
        </div>

        {/* Right panel — metadata / coding / annotations */}
        <div style={{ width: '320px', minWidth: '320px', borderLeft: `1px solid ${T.color.border.light}`, display: 'flex', flexDirection: 'column', background: T.color.bg.card }}>
          {/* Panel tabs */}
          <div style={{ display: 'flex', borderBottom: `1px solid ${T.color.border.light}` }}>
            {[{id:'metadata',label:'Metadata'},{id:'coding',label:'Coding'},{id:'annotations',label:'Notes'}].map(p => (
              <button key={p.id} onClick={() => setActivePanel(p.id)} style={{
                flex: 1, padding: '8px', fontSize: '11px', fontWeight: 500, border: 'none', background: 'none',
                color: activePanel === p.id ? ev.teal : T.color.text.tertiary,
                borderBottom: activePanel === p.id ? `2px solid ${ev.teal}` : '2px solid transparent',
                cursor: 'pointer', fontFamily: T.font.family, marginBottom: '-1px',
              }}>{p.label}</button>
            ))}
          </div>

          <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
            {/* METADATA PANEL */}
            {activePanel === 'metadata' && (
              <div>
                {/* Relevance */}
                <div style={{ padding: '8px 0', borderBottom: `1px solid ${T.color.border.light}`, marginBottom: '8px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                    <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>AI Relevance</span>
                    <span style={{ fontSize: '16px', fontWeight: 700, fontFamily: T.font.mono, color: relevanceColor(doc.relevance) }}>{doc.relevance}%</span>
                  </div>
                  <div style={{ height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                    <div style={{ width: `${doc.relevance}%`, height: '100%', borderRadius: '3px', background: relevanceColor(doc.relevance) }} />
                  </div>
                </div>
                {/* Tags */}
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>AI Tags</div>
                  <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                    {doc.aiTags.map((tag, i) => (
                      <span key={i} style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '10px', background: ev.tealBg, color: ev.teal, fontWeight: 500 }}>{tag}</span>
                    ))}
                  </div>
                </div>
                {/* Fields */}
                <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: '4px 8px', fontSize: '11px' }}>
                  {[
                    ['Bates #', doc.bates],
                    ['Type', doc.type],
                    ['Category', doc.category],
                    ['Custodian', doc.custodian],
                    ['Created', doc.dateCreated],
                    ['Collected', doc.dateCollected],
                    ['Pages', doc.pages],
                    ['Size', doc.size],
                    ['Status', doc.status],
                    ['Privilege', doc.privilege],
                    ['Reviewer', doc.reviewer],
                    ['Exhibit', doc.exhibitNum || '—'],
                  ].map(([label, val], i) => (
                    <React.Fragment key={i}>
                      <span style={{ color: T.color.text.tertiary, fontWeight: 500 }}>{label}</span>
                      <span style={{ color: T.color.text.primary, wordBreak: 'break-all' }}>{val}</span>
                    </React.Fragment>
                  ))}
                </div>
                {/* Chain of custody */}
                <div style={{ marginTop: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Chain of Custody</div>
                  {doc.chainOfCustody.map((c, i) => (
                    <div key={i} style={{ display: 'flex', gap: '6px', marginBottom: '4px', fontSize: '10px' }}>
                      <span style={{ fontFamily: T.font.mono, color: T.color.text.tertiary, minWidth: '40px' }}>{c.date}</span>
                      <span style={{ color: T.color.text.secondary }}>{c.action} — <span style={{ fontWeight: 500 }}>{c.by}</span></span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* CODING PANEL */}
            {activePanel === 'coding' && (
              <div>
                <div style={{ fontSize: '9px', color: T.color.text.tertiary, marginBottom: '12px', padding: '6px 8px', background: T.color.bg.secondary, borderRadius: '4px' }}>
                  Shortcuts: <span style={{ fontFamily: T.font.mono }}>R</span>=Responsive <span style={{ fontFamily: T.font.mono }}>N</span>=Non-Resp <span style={{ fontFamily: T.font.mono }}>H</span>=Hot Doc <span style={{ fontFamily: T.font.mono }}>P</span>=Privilege <span style={{ fontFamily: T.font.mono }}>↑↓</span>=Navigate
                </div>

                {/* Responsiveness */}
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Responsiveness</div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    {['responsive', 'non-responsive', 'further-review'].map(v => {
                      const labels = { responsive: 'Responsive', 'non-responsive': 'Non-Responsive', 'further-review': 'Further Review' };
                      const colors = { responsive: T.color.status.active, 'non-responsive': T.color.text.tertiary, 'further-review': T.color.status.warning };
                      const isActive = codingValues.responsiveness === v;
                      return (
                        <button key={v} onClick={() => setCodingValues(cv => ({...cv, responsiveness: v}))} style={{
                          flex: 1, padding: '6px 4px', borderRadius: '6px', fontSize: '10px', fontWeight: 600, cursor: 'pointer', fontFamily: T.font.family, border: `1px solid ${isActive ? colors[v] : T.color.border.light}`,
                          background: isActive ? `${colors[v]}10` : T.color.bg.card, color: isActive ? colors[v] : T.color.text.secondary,
                        }}>{labels[v]}</button>
                      );
                    })}
                  </div>
                </div>

                {/* Privilege */}
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Privilege</div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    {['none', 'ac', 'wp', 'joint'].map(v => {
                      const labels = { none: 'None', ac: 'Atty-Client', wp: 'Work Product', joint: 'Joint Defense' };
                      const isActive = codingValues.privilege === v;
                      return (
                        <button key={v} onClick={() => setCodingValues(cv => ({...cv, privilege: v}))} style={{
                          flex: 1, padding: '6px 4px', borderRadius: '6px', fontSize: '10px', fontWeight: 600, cursor: 'pointer', fontFamily: T.font.family, border: `1px solid ${isActive ? '#A855F7' : T.color.border.light}`,
                          background: isActive ? 'rgba(168,85,247,0.08)' : T.color.bg.card, color: isActive ? '#A855F7' : T.color.text.secondary,
                        }}>{labels[v]}</button>
                      );
                    })}
                  </div>
                </div>

                {/* Confidentiality */}
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Confidentiality</div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    {['public', 'confidential', 'highly-confidential', 'aeo'].map(v => {
                      const labels = { public: 'Public', confidential: 'Conf.', 'highly-confidential': 'Highly Conf.', aeo: 'AEO' };
                      const isActive = codingValues.confidentiality === v;
                      return (
                        <button key={v} onClick={() => setCodingValues(cv => ({...cv, confidentiality: v}))} style={{
                          flex: 1, padding: '6px 2px', borderRadius: '6px', fontSize: '9px', fontWeight: 600, cursor: 'pointer', fontFamily: T.font.family, border: `1px solid ${isActive ? T.color.status.warning : T.color.border.light}`,
                          background: isActive ? 'rgba(184,134,11,0.08)' : T.color.bg.card, color: isActive ? T.color.status.warning : T.color.text.secondary,
                        }}>{labels[v]}</button>
                      );
                    })}
                  </div>
                </div>

                {/* Hot doc toggle */}
                <div style={{ marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <button onClick={() => setCodingValues(cv => ({...cv, hotDoc: !cv.hotDoc}))} style={{
                    padding: '6px 14px', borderRadius: '6px', fontSize: '11px', fontWeight: 600, cursor: 'pointer', fontFamily: T.font.family,
                    border: `1px solid ${codingValues.hotDoc ? '#C23030' : T.color.border.light}`,
                    background: codingValues.hotDoc ? 'rgba(194,48,48,0.08)' : T.color.bg.card,
                    color: codingValues.hotDoc ? '#C23030' : T.color.text.secondary,
                  }}> Hot Document</button>
                </div>

                {/* Issue tags */}
                <div style={{ marginBottom: '12px' }}>
                  <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Issue Tags</div>
                  <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                    {['breach', 'fraud', 'fiduciary', 'damages', 'scienter', 'reliance', 'MSA', 'Apex'].map(tag => {
                      const isActive = codingValues.issues?.includes(tag);
                      return (
                        <button key={tag} onClick={() => setCodingValues(cv => ({...cv, issues: isActive ? cv.issues.filter(t=>t!==tag) : [...(cv.issues||[]), tag]}))} style={{
                          padding: '3px 10px', borderRadius: '12px', fontSize: '10px', fontWeight: 500, cursor: 'pointer', fontFamily: T.font.family,
                          border: `1px solid ${isActive ? ev.teal : T.color.border.light}`,
                          background: isActive ? ev.tealBg : T.color.bg.card, color: isActive ? ev.teal : T.color.text.secondary,
                        }}>{tag}</button>
                      );
                    })}
                  </div>
                </div>

                {/* Save */}
                <button style={{ width: '100%', padding: '8px', borderRadius: '6px', background: ev.teal, border: 'none', color: '#fff', fontSize: '12px', fontWeight: 700, cursor: 'pointer', fontFamily: T.font.family }}>Save Coding Decisions</button>
              </div>
            )}

            {/* ANNOTATIONS PANEL */}
            {activePanel === 'annotations' && (
              <div>
                <div style={{ marginBottom: '12px' }}>
                  <textarea value={newAnnotation} onChange={e => setNewAnnotation(e.target.value)} placeholder="Add a note about this document..." style={{ width: '100%', minHeight: '56px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '8px 10px', fontSize: '11px', fontFamily: T.font.family, color: T.color.text.primary, background: T.color.bg.primary, outline: 'none', resize: 'vertical' }} />
                  <button onClick={addAnnotation} style={{ marginTop: '4px', padding: '5px 12px', borderRadius: '6px', background: ev.teal, border: 'none', color: '#fff', fontSize: '11px', fontWeight: 600, cursor: 'pointer', fontFamily: T.font.family }}>Add Note</button>
                </div>
                {annotations.map(a => {
                  const typeColors = { flag: '#C23030', ai: '#3B82F6', note: ev.teal };
                  return (
                    <div key={a.id} style={{ padding: '8px 0', borderBottom: `1px solid ${T.color.border.light}`, marginBottom: '4px' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                        <span style={{ fontSize: '10px', fontWeight: 600, color: typeColors[a.type] || T.color.text.primary }}>{a.author}</span>
                        <span style={{ fontSize: '9px', color: T.color.text.tertiary }}>{a.time}</span>
                      </div>
                      <div style={{ fontSize: '11px', color: T.color.text.secondary, lineHeight: 1.4 }}>{a.text}</div>
                    </div>
                  );
                })}
                {annotations.length === 0 && <div style={{ fontSize: '11px', color: T.color.text.tertiary, textAlign: 'center', padding: '20px' }}>No annotations yet.</div>}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.DocumentViewer = DocumentViewer;
