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

function EvidencePlatform({ matter, onBack }) {
  const [activeTab, setActiveTab] = useState('vault');
  const [viewerDoc, setViewerDoc] = useState(null);
  const m = matter;
  const data = useMemo(() => window.EVIDENCE_DATA[m.id] || null, [m.id]);

  const tabs = [
    { id: 'vault', label: 'Evidence Vault' },
    { id: 'review', label: 'AI Review' },
    { id: 'search', label: 'Search' },
    { id: 'tar', label: 'TAR' },
    { id: 'timeline', label: 'Timeline' },
    { id: 'exhibits', label: 'Exhibits' },
    { id: 'production', label: 'Productions' },
    { id: 'transcripts', label: 'Transcripts' },
    { id: 'graph', label: 'Relationships' },
  ];

  if (!data) return (
    <div style={ev.container}>
      <div style={ev.header}>
        <div style={ev.headerTitle}>
          <button onClick={onBack} style={{ padding: '4px 10px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '14px', color: T.color.text.secondary, cursor: 'pointer' }}>←</button>
          <div style={ev.evIcon}>{window.Icons && <window.Icons.Documents size={16} color="#fff" strokeWidth={1.75} />}</div>
          <div><div style={ev.title}>Evidence Manager</div><div style={ev.subtitle}>{m.name}</div></div>
        </div>
      </div>
      <div style={{ padding: '60px', textAlign: 'center', color: T.color.text.tertiary }}>Evidence data not yet loaded for this matter. Full evidence management available for Redstone v. Meridian.</div>
    </div>
  );

  const vault = data.vault;
  const hotDocs = vault.filter(v => v.hotDoc).length;
  const totalPages = vault.reduce((s, v) => s + v.pages, 0);
  const reviewPct = Math.round(((data.reviewPipeline.total - data.reviewPipeline.stages[0].count) / data.reviewPipeline.total) * 100);

  // Make vault items openable in viewer
  const handleOpenDoc = (docId) => setViewerDoc(docId);

  const renderTab = () => {
    switch (activeTab) {
      case 'vault': return <EvidenceVault data={data} onOpenDoc={handleOpenDoc} />;
      case 'review': return <EvidenceReview data={data} />;
      case 'search': return <EvidenceSearch data={data} />;
      case 'tar': return <EvidenceTAR data={data} />;
      case 'timeline': return <EvidenceTimeline data={data} />;
      case 'exhibits': return <EvidenceExhibits data={data} />;
      case 'production': return <EvidenceProduction data={data} />;
      case 'transcripts': return <EvidenceTranscripts data={data} />;
      case 'graph': return <EvidenceGraph data={data} />;
      default: return <EvidenceVault data={data} onOpenDoc={handleOpenDoc} />;
    }
  };

  return (
    <div style={ev.container}>
      {/* Document Viewer overlay */}
      {viewerDoc && (
        <DocumentViewer data={data} initialDocId={viewerDoc} onClose={() => setViewerDoc(null)} />
      )}

      {/* Header */}
      <div style={ev.header}>
        <div style={ev.headerTitle}>
          <button onClick={onBack} style={{ padding: '4px 10px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: '14px', color: T.color.text.secondary, cursor: 'pointer' }}>←</button>
          <div style={ev.evIcon}>{window.Icons && <window.Icons.Documents size={16} color="#fff" strokeWidth={1.75} />}</div>
          <div>
            <div style={ev.title}>Evidence Manager</div>
            <div style={ev.subtitle}>{m.name} · {m.id}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Items</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, fontFamily: T.font.mono }}>{vault.length}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pages</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: T.color.text.primary, fontFamily: T.font.mono }}>{totalPages.toLocaleString()}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: 'rgba(194,48,48,0.04)', border: '1px solid rgba(194,48,48,0.15)' }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: '#C23030', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Hot Docs</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: '#C23030', fontFamily: T.font.mono }}>{hotDocs}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: ev.tealBg, border: `1px solid ${ev.teal}20` }}>
            <span style={{ fontSize: '10px', fontWeight: 600, color: ev.teal, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Review</span>
            <span style={{ fontSize: '14px', fontWeight: 700, color: ev.teal, fontFamily: T.font.mono }}>{reviewPct}%</span>
          </div>
          <button style={{ padding: '6px 14px', borderRadius: '6px', background: ev.teal, border: 'none', color: '#fff', fontSize: '12px', fontWeight: 700, cursor: 'pointer', fontFamily: T.font.family }}>+ Import</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={ev.tabs}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{ ...ev.tab, ...(activeTab === t.id ? ev.tabActive : {}) }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Body */}
      <div style={ev.body}>
        {renderTab()}
      </div>
    </div>
  );
}

window.EvidencePlatform = EvidencePlatform;
