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

// Local helpers — avoid window.statusColor / window.extColor collision with later-loaded scripts
const docStatusColor = (s) => ({ Draft: T.color.status.warning, Final: T.color.status.active, Filed: T.color.accent.blue, Review: '#6B21A8' }[s] || T.color.status.pending);
const docExtColor = (ext) => ({ PDF: '#C23030', DOCX: '#2563EB', XLSX: '#1B7A4A', MSG: '#B8860B' }[ext] || T.color.text.tertiary);

// ── FOLDER TREE VIEW ──
function DocFolderTree({ folders, activeFolder, onSelect }) {
  const getChildren = (parentId) => folders.filter(f => f.parent === parentId);
  const [expanded, setExpanded] = useState({ 'F-ROOT': true, 'F-001': true });

  const toggle = (id) => setExpanded(prev => ({ ...prev, [id]: !prev[id] }));

  const renderNode = (folder, depth = 0) => {
    const children = getChildren(folder.id);
    const isOpen = expanded[folder.id];
    const isActive = activeFolder === folder.id;
    return (
      <React.Fragment key={folder.id}>
        <div onClick={() => { onSelect(folder.id); if (children.length > 0) toggle(folder.id); }}
          style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '5px 8px', paddingLeft: `${8 + depth * 16}px`, borderRadius: T.radius.sm, cursor: 'pointer', background: isActive ? T.color.bg.hover : 'transparent', fontSize: T.font.size.sm, color: isActive ? T.color.text.primary : T.color.text.secondary, fontWeight: isActive ? T.font.weight.medium : T.font.weight.normal, transition: 'background 0.1s' }}>
          {children.length > 0 ? <span style={{ fontSize: '9px', color: T.color.text.tertiary, width: '10px' }}>{isOpen ? '▾' : '▸'}</span> : <span style={{ width: '10px' }} />}
          <span style={{ fontSize: '12px' }}>{folder.icon}</span>
          <span style={{ flex: 1 }}>{folder.name}</span>
          <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, fontFamily: T.font.mono }}>{folder.count}</span>
        </div>
        {isOpen && children.map(c => renderNode(c, depth + 1))}
      </React.Fragment>
    );
  };

  const roots = folders.filter(f => f.parent === null);
  return <div style={{ padding: '4px 0' }}>{roots.map(r => renderNode(r))}</div>;
}

// ── DOCUMENT TABLE (reusable, with optional selection + query highlighting) ──
function highlightMatch(text, query) {
  if (!query) return text;
  const q = query.trim();
  if (!q || q.length < 2) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx < 0) return text;
  return (
    <>
      {text.slice(0, idx)}
      <mark style={{ background: 'rgba(212,160,23,0.35)', color: 'inherit', padding: '0 2px', borderRadius: '2px' }}>{text.slice(idx, idx + q.length)}</mark>
      {text.slice(idx + q.length)}
    </>
  );
}

function DocTable({ docs, starred, onToggleStar, onSelect, hoveredRow, setHoveredRow, sortBy, sortAsc, onSort, selectable, selected, onToggleSelect, highlightQuery }) {
  const sortArrow = (col) => sortBy === col ? (sortAsc ? ' ↑' : ' ↓') : '';
  const cols = selectable ? '20px 24px 1fr 100px 140px 90px 78px 64px 52px' : '24px 1fr 100px 140px 90px 78px 64px 52px';
  const allSelected = selectable && selected && docs.length > 0 && docs.every(d => selected.has(d.id));
  const toggleAll = (e) => {
    e.stopPropagation();
    if (allSelected) docs.forEach(d => onToggleSelect(d.id, false));
    else docs.forEach(d => onToggleSelect(d.id, true));
  };
  return (
    <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: cols, 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', alignItems: 'center' }}>
        {selectable && <input type="checkbox" checked={allSelected} onChange={toggleAll} onClick={e => e.stopPropagation()} style={{ cursor: 'pointer' }} />}
        <span></span>
        <span style={{ cursor: 'pointer' }} onClick={() => onSort('name')}>Name{sortArrow('name')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => onSort('type')}>Type{sortArrow('type')}</span>
        <span>Matter</span>
        <span style={{ cursor: 'pointer' }} onClick={() => onSort('author')}>Author{sortArrow('author')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => onSort('modified')}>Modified{sortArrow('modified')}</span>
        <span>Size</span>
        <span>Ext</span>
      </div>
      {docs.map(d => {
        const isSel = selectable && selected && selected.has(d.id);
        return (
        <div key={d.id} style={{ display: 'grid', gridTemplateColumns: cols, padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, cursor: 'pointer', transition: 'background 0.1s', gap: '8px', alignItems: 'center', background: isSel ? 'rgba(37,99,235,0.08)' : hoveredRow === d.id ? T.color.bg.hover : 'transparent' }}
          onMouseEnter={() => setHoveredRow(d.id)} onMouseLeave={() => setHoveredRow(null)} onClick={() => onSelect(d)}>
          {selectable && <input type="checkbox" checked={!!isSel} onChange={(e) => { e.stopPropagation(); onToggleSelect(d.id, e.target.checked); }} onClick={e => e.stopPropagation()} style={{ cursor: 'pointer' }} />}
          <span style={{ fontSize: '12px', cursor: 'pointer', color: starred.has(d.id) ? '#D4A017' : T.color.border.medium }} onClick={e => { e.stopPropagation(); onToggleStar(d.id); }}>{starred.has(d.id) ? '*' : '*'}</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 }}>
            {d.locked && <span style={{ fontSize: '9px', color: T.color.status.warning, fontWeight: 700 }}>LOCKED</span>}
            <span style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{highlightMatch(d.name, highlightQuery)}</span>
            {(d.comments?.length || 0) > 0 && <span style={{ fontSize: '9px', color: T.color.text.tertiary, flexShrink: 0, fontFamily: T.font.mono }}>{d.comments.length}c</span>}
            {(d.versions?.length || 0) > 1 && <span style={{ fontSize: '9px', fontFamily: T.font.mono, color: T.color.text.tertiary, flexShrink: 0 }}>v{d.versions[0]?.v}</span>}
          </div>
          <span style={{ ...window.sharedStyles.tag, background: `${docStatusColor(d.status)}14`, color: docStatusColor(d.status) }}>{d.status}</span>
          <span style={{ color: T.color.text.tertiary, fontSize: T.font.size.xs, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{highlightMatch(d.matter, highlightQuery)}</span>
          <span style={{ color: T.color.text.secondary, fontSize: T.font.size.xs }}>{highlightMatch(d.author, highlightQuery)}</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={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: `${docExtColor(d.ext)}10`, color: docExtColor(d.ext) }}>{d.ext}</span>
        </div>
      ); })}
      {docs.length === 0 && <div style={{ padding: '32px', textAlign: 'center', color: T.color.text.tertiary, fontSize: T.font.size.sm }}>No documents found</div>}
    </div>
  );
}

// ── TEMPLATES VIEW ──
function DocTemplatesView() {
  const templates = window.DOC_TEMPLATES;
  const [hov, setHov] = useState(null);
  return (
    <div>
      <div style={{ marginBottom: '12px', fontSize: T.font.size.sm, color: T.color.text.tertiary }}>{templates.length} templates available</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
        {templates.map(t => (
          <div key={t.id} onMouseEnter={() => setHov(t.id)} onMouseLeave={() => setHov(null)}
            style={{ background: T.color.bg.card, border: `1px solid ${hov === t.id ? T.color.border.medium : T.color.border.light}`, borderRadius: T.radius.lg, padding: '16px', cursor: 'pointer', transition: 'border-color 0.15s, box-shadow 0.15s', boxShadow: hov === t.id ? T.shadow.md : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
              <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: `${docExtColor(t.ext)}10`, color: docExtColor(t.ext) }}>{t.ext}</span>
              <span style={{ ...window.sharedStyles.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>{t.type}</span>
            </div>
            <div style={{ fontSize: T.font.size.md, fontWeight: T.font.weight.semibold, color: T.color.text.primary, marginBottom: '4px' }}>{t.name}</div>
            <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{t.author} · Used {t.usageCount} times · Last: {t.lastUsed}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── ANALYTICS VIEW ──
function DocAnalyticsView() {
  const a = window.DOC_ANALYTICS;
  const maxCount = Math.max(...a.byMatter.map(m => m.count));
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '20px' }}>
        <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, padding: '14px 16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>Total Documents</div>
          <div style={{ fontSize: T.font.size.xxl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight, marginTop: '4px' }}>{a.totalDocs}</div>
        </div>
        <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, padding: '14px 16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>Total Storage</div>
          <div style={{ fontSize: T.font.size.xxl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight, marginTop: '4px' }}>{a.totalSize}</div>
        </div>
        <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, padding: '14px 16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>Avg Versions</div>
          <div style={{ fontSize: T.font.size.xxl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight, marginTop: '4px' }}>{a.avgVersion}</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '20px' }}>
        {/* By Matter */}
        <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' }}>
          <div style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary }}>Documents by Matter</div>
          {a.byMatter.map((m, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '7px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm }}>
              <span style={{ width: '120px', fontWeight: T.font.weight.medium, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.name}</span>
              <div style={{ flex: 1, height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                <div style={{ height: '100%', borderRadius: '3px', width: `${(m.count / maxCount) * 100}%`, background: T.color.navy500 }} />
              </div>
              <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: T.color.text.tertiary, minWidth: '24px', textAlign: 'right' }}>{m.count}</span>
            </div>
          ))}
        </div>
        {/* By Type */}
        <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' }}>
          <div style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary }}>Documents by Type</div>
          {a.byType.map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '7px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm }}>
              <span style={{ color: T.color.text.primary }}>{t.name}</span>
              <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: T.color.text.tertiary }}>{t.count}</span>
            </div>
          ))}
        </div>
      </div>
      {/* Recent Activity */}
      <div style={{ background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' }}>
        <div style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary }}>Recent Activity</div>
        {a.recentActivity.map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm }}>
            <span style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary, minWidth: '70px' }}>{r.action}</span>
            <span style={{ flex: 1, color: T.color.text.secondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.doc}</span>
            <span style={{ color: T.color.text.secondary, fontSize: T.font.size.xs }}>{r.user}</span>
            <span style={{ color: T.color.text.tertiary, fontFamily: T.font.mono, fontSize: T.font.size.xs }}>{r.time}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── SEARCH VIEW (improvements #8, #16) ──
function DocSearchView({ docs, onSelect, starred, onToggleStar }) {
  const [query, setQuery] = useState('');
  const [matterFilter, setMatterFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [extFilter, setExtFilter] = useState('All');
  const [authorFilter, setAuthorFilter] = useState('All');
  const [confFilter, setConfFilter] = useState('All');
  const [dateRange, setDateRange] = useState('all');
  const [hoveredRow, setHoveredRow] = useState(null);
  const [sortBy, setSortBy] = useState('modified');
  const [sortAsc, setSortAsc] = useState(false);

  const matters = ['All', ...new Set(docs.map(d => d.matter))];
  const statuses = ['All', 'Draft', 'Final', 'Filed', 'Review'];
  const exts = ['All', 'PDF', 'DOCX', 'XLSX'];
  const authors = ['All', ...new Set(docs.map(d => d.author))];
  const confs = ['All', 'Public', 'Internal', 'Confidential', 'Highly Confidential', 'Work Product', 'Highly Confidential — AEO'];
  const dateRanges = [
    { id: 'all', label: 'Any time' }, { id: '7d', label: 'Past 7 days' }, { id: '30d', label: 'Past 30 days' }, { id: '90d', label: 'Past 90 days' },
  ];

  const filtered = useMemo(() => {
    let items = docs;
    if (matterFilter !== 'All') items = items.filter(d => d.matter === matterFilter);
    if (statusFilter !== 'All') items = items.filter(d => d.status === statusFilter);
    if (extFilter !== 'All') items = items.filter(d => d.ext === extFilter);
    if (authorFilter !== 'All') items = items.filter(d => d.author === authorFilter);
    if (confFilter !== 'All') items = items.filter(d => d.confidentiality === confFilter);
    if (dateRange !== 'all') {
      const now = new Date();
      const days = dateRange === '7d' ? 7 : dateRange === '30d' ? 30 : 90;
      const cut = new Date(now.getTime() - days * 864e5);
      items = items.filter(d => new Date(d.modified) >= cut);
    }
    if (query) {
      const q = query.toLowerCase();
      items = items.filter(d => d.name.toLowerCase().includes(q) || d.tags?.some(t => t.toLowerCase().includes(q)) || d.matter.toLowerCase().includes(q) || d.author.toLowerCase().includes(q) || d.type.toLowerCase().includes(q));
    }
    const dir = sortAsc ? 1 : -1;
    items = [...items].sort((a, b) => {
      if (sortBy === 'name') return dir * a.name.localeCompare(b.name);
      if (sortBy === 'modified') return dir * (new Date(a.modified) - new Date(b.modified));
      if (sortBy === 'type') return dir * a.type.localeCompare(b.type);
      if (sortBy === 'author') return dir * a.author.localeCompare(b.author);
      return 0;
    });
    return items;
  }, [docs, query, matterFilter, statusFilter, extFilter, authorFilter, confFilter, dateRange, sortBy, sortAsc]);

  const handleSort = (col) => { if (sortBy === col) setSortAsc(!sortAsc); else { setSortBy(col); setSortAsc(true); } };
  const savedSearches = window.DOC_SAVED_SEARCHES_V2 || window.DOC_SAVED_SEARCHES;

  // Similar documents strip: when a query hits only a few, show "people also viewed"
  const similarIds = useMemo(() => {
    if (!query || filtered.length === 0 || filtered.length > 4) return [];
    const first = filtered[0];
    const insights = window.DOC_AI_INSIGHTS?.[first.id];
    return insights?.similarDocs || [];
  }, [query, filtered]);
  const similarDocs = similarIds.map(id => docs.find(d => d.id === id)).filter(Boolean);

  const activeFilters = [matterFilter, statusFilter, extFilter, authorFilter, confFilter].filter(v => v !== 'All').length + (dateRange !== 'all' ? 1 : 0);

  const clearAll = () => {
    setQuery(''); setMatterFilter('All'); setStatusFilter('All'); setExtFilter('All');
    setAuthorFilter('All'); setConfFilter('All'); setDateRange('all');
  };

  const saveCurrent = () => {
    if (!query.trim() && activeFilters === 0) return;
    const parts = [];
    if (query) parts.push(`"${query}"`);
    if (matterFilter !== 'All') parts.push(`matter:${matterFilter}`);
    if (statusFilter !== 'All') parts.push(`status:${statusFilter}`);
    if (authorFilter !== 'All') parts.push(`author:${authorFilter}`);
    window.DocStore?.saveSearch(parts[0] || 'Custom search', parts.join(' '));
  };

  const chipStyle = (active) => ({ padding: '4px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`, background: active ? T.color.navy800 : T.color.bg.card, color: active ? T.color.ivory100 : T.color.text.secondary, fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, cursor: 'pointer', fontFamily: T.font.family });

  return (
    <div>
      {/* Search bar */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', alignItems: 'center' }}>
        <input value={query} onChange={e => setQuery(e.target.value)} placeholder='Search by name, tag, matter, author — try "matter:Redstone status:Draft"' style={{ flex: 1, height: '36px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 14px', fontSize: T.font.size.md, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none' }} />
        <button onClick={saveCurrent} style={{ padding: '0 12px', height: '36px', fontSize: '11px', fontWeight: 600, border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, color: T.color.text.secondary, borderRadius: T.radius.md, cursor: 'pointer' }}>+ Save search</button>
        {(query || activeFilters > 0) && <button onClick={clearAll} style={{ padding: '0 12px', height: '36px', fontSize: '11px', fontWeight: 600, border: 'none', background: T.color.bg.secondary, color: T.color.text.tertiary, borderRadius: T.radius.md, cursor: 'pointer' }}>Clear</button>}
      </div>
      {/* Faceted filters */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
        <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ height: '28px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 8px', fontSize: T.font.size.xs, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.secondary, cursor: 'pointer' }}>
          {matters.map(m => <option key={m} value={m}>{m === 'All' ? 'All Matters' : m}</option>)}
        </select>
        <select value={authorFilter} onChange={e => setAuthorFilter(e.target.value)} style={{ height: '28px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 8px', fontSize: T.font.size.xs, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.secondary, cursor: 'pointer' }}>
          {authors.map(a => <option key={a} value={a}>{a === 'All' ? 'All Authors' : a}</option>)}
        </select>
        <select value={confFilter} onChange={e => setConfFilter(e.target.value)} style={{ height: '28px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 8px', fontSize: T.font.size.xs, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.secondary, cursor: 'pointer' }}>
          {confs.map(c => <option key={c} value={c}>{c === 'All' ? 'All Confidentiality' : c}</option>)}
        </select>
        {statuses.map(s => <button key={s} onClick={() => setStatusFilter(s)} style={chipStyle(statusFilter === s)}>{s}</button>)}
        {exts.map(e => <button key={e} onClick={() => setExtFilter(e)} style={chipStyle(extFilter === e)}>{e}</button>)}
        <span style={{ marginLeft: 'auto', fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{filtered.length} results</span>
      </div>
      {/* Date range chips */}
      <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap', alignItems: 'center' }}>
        <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Modified:</span>
        {dateRanges.map(r => <button key={r.id} onClick={() => setDateRange(r.id)} style={{ ...chipStyle(dateRange === r.id), padding: '3px 8px' }}>{r.label}</button>)}
      </div>
      {/* Saved searches */}
      {!query && activeFilters === 0 && (
        <div style={{ marginBottom: '16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '6px' }}>Saved Searches</div>
          <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
            {savedSearches.map(ss => (
              <button key={ss.id} onClick={() => setQuery(ss.name)} style={{ padding: '4px 12px', borderRadius: '14px', border: `1px solid ${T.color.border.light}`, background: T.color.bg.card, fontSize: T.font.size.xs, color: T.color.text.secondary, cursor: 'pointer', fontFamily: T.font.family, display: 'inline-flex', alignItems: 'center', gap: '6px' }}>
                {ss.icon && <span style={{ fontSize: '11px' }}>{ss.icon}</span>}
                {ss.name} <span style={{ fontFamily: T.font.mono, color: T.color.text.tertiary }}>{ss.resultCount}</span>
              </button>
            ))}
          </div>
        </div>
      )}
      <DocTable docs={filtered} starred={starred} onToggleStar={onToggleStar} onSelect={onSelect} hoveredRow={hoveredRow} setHoveredRow={setHoveredRow} sortBy={sortBy} sortAsc={sortAsc} onSort={handleSort} highlightQuery={query} />
      {similarDocs.length > 0 && (
        <div style={{ marginTop: '16px', padding: '12px 14px', background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '8px' }}>Similar documents</div>
          <div style={{ display: 'flex', gap: '8px', overflowX: 'auto' }}>
            {similarDocs.map(d => (
              <div key={d.id} onClick={() => onSelect(d)} style={{ minWidth: '200px', padding: '10px', background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: '6px', cursor: 'pointer' }}>
                <div style={{ fontSize: '11px', fontWeight: 700, color: T.color.text.primary, marginBottom: '3px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.name}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{d.matter} · {d.type}</div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { DocFolderTree, DocTable, DocTemplatesView, DocAnalyticsView, DocSearchView });
