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

const ALL_DOCS = [
  { id: 1, name: 'Opposition to MSJ — Draft v3', type: 'Brief', matter: 'Redstone v. Meridian', author: 'M. Kirkland', modified: '2026-04-18', size: '2.4 MB', ext: 'DOCX', status: 'Draft', starred: true },
  { id: 2, name: 'Harrington Deposition Transcript', type: 'Transcript', matter: 'Redstone v. Meridian', author: 'Court Reporter', modified: '2026-04-15', size: '847 KB', ext: 'PDF', status: 'Final', starred: false },
  { id: 3, name: 'Economic Damages Report — Mitchell', type: 'Expert Report', matter: 'Redstone v. Meridian', author: 'S. Mitchell', modified: '2026-04-02', size: '5.1 MB', ext: 'PDF', status: 'Final', starred: true },
  { id: 4, name: 'Antitrust Complaint — Filed', type: 'Pleading', matter: 'Pacific Shipping Antitrust', author: 'S. Chen', modified: '2026-03-20', size: '1.2 MB', ext: 'PDF', status: 'Filed', starred: false },
  { id: 5, name: 'Shipping Route Analysis 2019–2024', type: 'Exhibit', matter: 'Pacific Shipping Antitrust', author: 'L. Torres', modified: '2026-04-10', size: '18.3 MB', ext: 'XLSX', status: 'Final', starred: false },
  { id: 6, name: 'Thornton Will — Original 2018', type: 'Evidence', matter: 'Thornton Estate', author: 'Estate Records', modified: '2026-02-14', size: '340 KB', ext: 'PDF', status: 'Final', starred: true },
  { id: 7, name: 'Expert Witness CV — Dr. Patel', type: 'Expert Report', matter: 'Thornton Estate', author: 'R. Vasquez', modified: '2026-04-01', size: '120 KB', ext: 'PDF', status: 'Final', starred: false },
  { id: 8, name: 'Patent Claim Chart — Blackwell v. Orion', type: 'Analysis', matter: 'Blackwell IP', author: 'J. Park', modified: '2026-04-16', size: '780 KB', ext: 'XLSX', status: 'Draft', starred: true },
  { id: 9, name: 'Settlement Offer — Atlas Financial', type: 'Correspondence', matter: 'Chen v. Atlas', author: 'Opposing Counsel', modified: '2026-04-17', size: '95 KB', ext: 'PDF', status: 'Review', starred: true },
  { id: 10, name: 'FCPA Compliance Memo — Sterling', type: 'Memo', matter: 'Sterling Pharma', author: 'S. Chen', modified: '2026-04-19', size: '3.2 MB', ext: 'DOCX', status: 'Draft', starred: false },
  { id: 11, name: 'Financial Audit Report Q3 2025', type: 'Production', matter: 'Sterling Pharma', author: 'S. Chen', modified: '2026-04-20', size: '12.8 MB', ext: 'PDF', status: 'Final', starred: false },
  { id: 12, name: 'Eminent Domain Valuation Report', type: 'Expert Report', matter: 'Harbor District', author: 'R. Vasquez', modified: '2026-04-08', size: '6.7 MB', ext: 'PDF', status: 'Final', starred: false },
  { id: 13, name: 'Merger Agreement — NovaTech/Apex', type: 'Contract', matter: 'NovaTech Merger', author: 'A. Petrov', modified: '2026-03-28', size: '4.5 MB', ext: 'PDF', status: 'Final', starred: false },
  { id: 14, name: 'Class Certification Motion', type: 'Brief', matter: 'Greenfield Environmental', author: 'M. Kirkland', modified: '2026-04-14', size: '1.9 MB', ext: 'DOCX', status: 'Filed', starred: true },
  { id: 15, name: 'Privilege Log — All Matters Q1', type: 'Log', matter: 'Firm-wide', author: 'J. Park', modified: '2026-04-12', size: '2.1 MB', ext: 'XLSX', status: 'Final', starred: false },
];

const docTypes = ['All', 'Brief', 'Transcript', 'Expert Report', 'Pleading', 'Exhibit', 'Evidence', 'Memo', 'Correspondence', 'Contract'];

const dStyles = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary, padding: '20px' },
  header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' },
  title: { fontSize: T.font.size.xl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight },
  statsBar: { display: 'flex', gap: '24px', marginBottom: '16px', fontSize: T.font.size.sm, color: T.color.text.tertiary },
  statNum: { fontWeight: T.font.weight.bold, color: T.color.text.primary, fontSize: T.font.size.md, marginRight: '4px' },
  toolbar: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', flexWrap: 'wrap' },
  searchInput: {
    height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md,
    padding: '0 12px', fontSize: T.font.size.base, fontFamily: T.font.family,
    background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '240px',
  },
  grid: { display: 'grid', gridTemplateColumns: '1fr', gap: '0' },
  row: {
    display: 'grid', gridTemplateColumns: '24px 1fr 120px 160px 100px 80px 70px 60px',
    alignItems: 'center', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`,
    fontSize: T.font.size.sm, cursor: 'pointer', transition: 'background 0.1s', gap: '8px',
  },
  headerRow: {
    display: 'grid', gridTemplateColumns: '24px 1fr 120px 160px 100px 80px 70px 60px',
    padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`,
    fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary,
    textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, gap: '8px',
  },
  star: { fontSize: '12px', cursor: 'pointer', color: T.color.border.medium, transition: 'color 0.1s' },
  starActive: { color: '#D4A017' },
  extBadge: {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: '9px', fontWeight: T.font.weight.bold, letterSpacing: '0.04em',
    padding: '2px 6px', borderRadius: '3px', background: T.color.bg.secondary, color: T.color.text.tertiary,
  },
};

function DocumentsHub() {
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState('All');
  const [starred, setStarred] = useState(new Set(ALL_DOCS.filter(d => d.starred).map(d => d.id)));
  const [hoveredRow, setHoveredRow] = useState(null);

  const filtered = useMemo(() => {
    let docs = ALL_DOCS;
    if (typeFilter !== 'All') docs = docs.filter(d => d.type === typeFilter);
    if (search) {
      const q = search.toLowerCase();
      docs = docs.filter(d => d.name.toLowerCase().includes(q) || d.matter.toLowerCase().includes(q) || d.author.toLowerCase().includes(q));
    }
    return docs;
  }, [search, typeFilter]);

  const toggleStar = (id, e) => { e.stopPropagation(); setStarred(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; }); };

  const extColor = (ext) => {
    const m = { PDF: '#C23030', DOCX: '#2563EB', XLSX: '#1B7A4A' };
    return m[ext] || T.color.text.tertiary;
  };

  return (
    <div style={dStyles.container}>
      <div style={dStyles.header}>
        <div style={dStyles.title}>Documents</div>
        <button style={{...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary}}>+ Upload</button>
      </div>
      <div style={dStyles.statsBar}>
        <span><span style={dStyles.statNum}>{ALL_DOCS.length}</span>documents</span>
        <span><span style={dStyles.statNum}>{starred.size}</span>starred</span>
        <span><span style={dStyles.statNum}>{ALL_DOCS.filter(d=>d.status==='Draft').length}</span>drafts</span>
        <span><span style={dStyles.statNum}>{ALL_DOCS.filter(d=>d.status==='Review').length}</span>in review</span>
      </div>
      <div style={dStyles.toolbar}>
        <input style={dStyles.searchInput} placeholder="Filter documents..." value={search} onChange={e => setSearch(e.target.value)} />
        {docTypes.slice(0,7).map(t => (
          <button key={t} onClick={() => setTypeFilter(t)} style={{
            padding: '4px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`,
            background: typeFilter === t ? T.color.navy800 : T.color.bg.card,
            color: typeFilter === t ? T.color.ivory100 : T.color.text.secondary,
            fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, cursor: 'pointer', fontFamily: T.font.family,
          }}>{t}</button>
        ))}
      </div>
      <div style={window.sharedStyles.tableContainer}>
        <div style={dStyles.headerRow}>
          <span></span><span>Name</span><span>Type</span><span>Matter</span><span>Author</span><span>Modified</span><span>Size</span><span>Ext</span>
        </div>
        {filtered.map(d => (
          <div key={d.id} style={{...dStyles.row, background: hoveredRow===d.id ? T.color.bg.hover : 'transparent'}}
            onMouseEnter={()=>setHoveredRow(d.id)} onMouseLeave={()=>setHoveredRow(null)}>
            <span style={{...dStyles.star, ...(starred.has(d.id)?dStyles.starActive:{})}} onClick={e=>toggleStar(d.id,e)}>{starred.has(d.id)?'*':'*'}</span>
            <div>
              <div style={{fontWeight: T.font.weight.medium, color: T.color.text.primary}}>{d.name}</div>
            </div>
            <span style={{color: T.color.text.secondary}}>{d.type}</span>
            <span style={{color: T.color.text.tertiary, fontSize: T.font.size.xs}}>{d.matter}</span>
            <span style={{color: T.color.text.secondary}}>{d.author}</span>
            <span style={{color: T.color.text.tertiary, fontFamily: T.font.mono, fontSize: T.font.size.xs}}>
              {new Date(d.modified).toLocaleDateString('en-US',{month:'short',day:'numeric'})}
            </span>
            <span style={{color: T.color.text.tertiary, fontSize: T.font.size.xs}}>{d.size}</span>
            <span style={{...dStyles.extBadge, color: extColor(d.ext), background: `${extColor(d.ext)}10`}}>{d.ext}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.ALL_DOCS_REF = ALL_DOCS;
window.DocumentsHub = DocumentsHub;
