// DOCUMENT PLATFORM — enterprise hubs (live-wired to DocStore + DocBus)
// Hubs: Dashboard · Library · Folders · Workspaces · Search · Versions · Compliance · Templates · Automation · Governance · Analytics · Trash
const { useState: useDcH, useMemo: useDcHMemo, useEffect: useDcHEff } = React;
const Tdch = window.ArbiterTokens;

const _useStore = (topics) => (window.useDocStore ? window.useDocStore(topics) : { docs: window.DOC_ITEMS, kpis: window.DOC_KPIS, starred: new Set(window.DOC_ITEMS.filter(d => d.starred).map(d => d.id)), audit: window.DOC_AUDIT_TRAIL, approvals: window.DOC_APPROVALS, checkouts: window.DOC_CHECKOUTS, holds: window.DOC_LEGAL_HOLDS, retention: window.DOC_RETENTION_POLICIES, shares: window.DOC_SHARES, dlp: window.DOC_DLP_POLICIES, accessReviews: window.DOC_ACCESS_REVIEWS, workflows: window.DOC_WORKFLOWS, ocr: window.DOC_OCR_PIPELINES, workspaces: window.DOC_WORKSPACES, templates: window.DOC_TEMPLATES, custodians: window.DOC_CUSTODIANS || [], envelopes: window.DOC_ENVELOPES || [], trash: window.DOC_TRASH || [], pinned: window.DOC_PINNED || [], recentlyViewed: window.DOC_RECENTLY_VIEWED || [], relationships: window.DOC_RELATIONSHIPS || [], aiInsights: window.DOC_AI_INSIGHTS || {}, velocity: window.DOC_VELOCITY || [], stale: window.DOC_STALE || [], duplicates: window.DOC_DUPLICATES || [], costByMatter: window.DOC_COST_BY_MATTER || [], heatmap: window.DOC_HEATMAP || [], confidTrend: window.DOC_CONFID_TREND || [], shareRisk: window.DOC_SHARE_RISK || {}, conflicts: window.DOC_CONFLICTS || [], savedSearches: window.DOC_SAVED_SEARCHES_V2 || [] });

// ── Shared pill sub-nav ────────────────────────────────────────────────────
function DcSubNav({ views, active, onChange }) {
  const accent = (window.docAccent && window.docAccent.blue) || '#2563EB';
  return (
    <div style={{
      display: 'flex', gap: '4px', padding: '6px',
      background: Tdch.color.bg.secondary,
      border: `1px solid ${Tdch.color.border.light}`,
      borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap',
    }}>
      {views.map(v => {
        const isActive = active === v.id;
        return (
          <button key={v.id} onClick={() => onChange(v.id)} style={{
            padding: '6px 12px', fontSize: '11px',
            fontWeight: isActive ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: isActive ? accent : 'transparent',
            color: isActive ? '#fff' : Tdch.color.text.secondary,
            display: 'inline-flex', alignItems: 'center', gap: '6px',
            transition: 'all 0.12s', fontFamily: Tdch.font.family,
          }}>
            {v.label}
            {v.badge != null && (
              <span style={{
                fontSize: '10px', fontWeight: 700,
                padding: '1px 6px', borderRadius: '8px',
                background: isActive ? 'rgba(255,255,255,0.22)' : Tdch.color.bg.card,
                color: isActive ? '#fff' : Tdch.color.text.tertiary,
                fontFamily: Tdch.font.mono,
              }}>{v.badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}
window.DcSubNav = DcSubNav;

// ── Shared primitives ──────────────────────────────────────────────────────
const dcCard = {
  background: Tdch.color.bg.card,
  border: `1px solid ${Tdch.color.border.light}`,
  borderRadius: Tdch.radius.lg,
  overflow: 'hidden',
};
const dcCardH = {
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  padding: '10px 16px', borderBottom: `1px solid ${Tdch.color.border.light}`,
  fontSize: Tdch.font.size.sm, fontWeight: Tdch.font.weight.semibold,
  color: Tdch.color.text.primary,
};
const dcTh = {
  textAlign: 'left', padding: '8px 14px', fontSize: '10px',
  fontWeight: 600, color: Tdch.color.text.tertiary,
  textTransform: 'uppercase', letterSpacing: '0.06em',
  background: Tdch.color.bg.secondary,
  borderBottom: `1px solid ${Tdch.color.border.light}`,
};
const dcTd = {
  padding: '8px 14px', fontSize: '12px',
  color: Tdch.color.text.primary,
  borderBottom: `1px solid ${Tdch.color.border.light}`,
  verticalAlign: 'middle',
};
const dcTag = (bg, fg) => ({
  display: 'inline-block', padding: '2px 8px',
  fontSize: '10px', fontWeight: 600,
  borderRadius: '10px', background: bg, color: fg,
});
const dcStatCard = (label, value, color) => (
  <div style={{
    background: Tdch.color.bg.card,
    border: `1px solid ${Tdch.color.border.light}`,
    borderRadius: Tdch.radius.lg, padding: '12px 14px',
  }}>
    <div style={{
      fontSize: '10px', fontWeight: 600,
      color: Tdch.color.text.tertiary,
      textTransform: 'uppercase', letterSpacing: '0.06em',
    }}>{label}</div>
    <div style={{
      fontSize: '22px', fontWeight: 700,
      color: color || Tdch.color.text.primary,
      fontFamily: Tdch.font.mono, letterSpacing: '-0.02em',
      marginTop: '2px',
    }}>{value}</div>
  </div>
);

const statusColorMap = {
  Active: '#059669', Approved: '#059669', Current: '#059669', Final: '#059669', Filed: '#2563EB',
  Pending: '#B45309', Review: '#B45309', 'Due soon': '#B45309', Draft: '#B45309', Expiring: '#B45309',
  Overdue: '#B91C1C', Alert: '#B91C1C', Changes: '#B91C1C', Released: '#6B7280', Completed: '#059669', Awaiting: '#B45309', Declined: '#B91C1C',
  Info: '#2563EB', Warn: '#B45309',
};
const dcStatus = (s) => statusColorMap[s] || Tdch.color.text.tertiary;

const dcBtn = (variant = 'ghost') => {
  const base = { padding: '4px 10px', fontSize: '11px', fontWeight: 600, borderRadius: '6px', cursor: 'pointer', fontFamily: Tdch.font.family };
  if (variant === 'primary') return { ...base, border: 'none', background: '#2563EB', color: '#fff' };
  if (variant === 'danger')  return { ...base, border: 'none', background: '#B91C1C', color: '#fff' };
  if (variant === 'success') return { ...base, border: 'none', background: '#059669', color: '#fff' };
  if (variant === 'warn')    return { ...base, border: 'none', background: '#B45309', color: '#fff' };
  return { ...base, border: `1px solid ${Tdch.color.border.light}`, background: Tdch.color.bg.card, color: Tdch.color.text.secondary };
};

// Risk bar helper
const dcRiskBar = (score) => {
  const color = score >= 70 ? '#B91C1C' : score >= 40 ? '#B45309' : '#059669';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
      <div style={{ width: '60px', height: '6px', background: Tdch.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
        <div style={{ width: `${score}%`, height: '100%', background: color }} />
      </div>
      <span style={{ fontFamily: Tdch.font.mono, fontSize: '11px', fontWeight: 700, color, minWidth: '24px', textAlign: 'right' }}>{score}</span>
    </div>
  );
};

// ── DASHBOARD ──────────────────────────────────────────────────────────────
function DcDashboardHub() {
  const s = _useStore(['doc.uploaded','doc.deleted','doc.approvalDecided','doc.audit','doc.starred','doc.holdApplied']);
  const k = s.kpis;
  const audit = (s.audit || []).slice(0, 6);
  const approvals = s.approvals.filter(a => a.status === 'Pending').slice(0, 5);
  const contributors = (window.DOC_CONTRIBUTORS || []).slice(0, 5);
  const pct = Math.round((k.storageGB / k.storageCapGB) * 100);
  const pinned = s.pinned || [];
  const recent = s.recentlyViewed || [];

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '10px', marginBottom: '16px' }}>
        {dcStatCard('Total Documents', k.totalDocs.toLocaleString())}
        {dcStatCard('Active Legal Holds', k.activeHolds, '#B91C1C')}
        {dcStatCard('Pending Approvals', k.pendingApprovals, '#B45309')}
        {dcStatCard('Checked Out', k.checkedOut, '#2563EB')}
        {dcStatCard('DLP Incidents (30d)', k.dlpIncidents30d, '#B91C1C')}
      </div>

      {/* Pinned & Recent row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
        <div style={dcCard}>
          <div style={dcCardH}><span>Pinned firm-wide</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{pinned.length}</span></div>
          <div style={{ padding: '8px 14px' }}>
            {pinned.map(p => {
              const d = s.docs.find(x => x.id === p.docId);
              if (!d) return null;
              return (
                <div key={p.docId} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, fontSize: '12px' }}>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontWeight: 600 }}> {d.name}</div>
                    <div style={{ fontSize: '10px', color: Tdch.color.text.tertiary, marginTop: '2px' }}>{p.note} · {p.pinnedBy}</div>
                  </div>
                  <button onClick={() => window.DocStore.unpin(p.docId)} style={dcBtn()}>Unpin</button>
                </div>
              );
            })}
            {pinned.length === 0 && <div style={{ fontSize: '11px', color: Tdch.color.text.tertiary, padding: '8px 0' }}>Nothing pinned</div>}
          </div>
        </div>
        <div style={dcCard}>
          <div style={dcCardH}><span>Recently viewed</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{recent.length}</span></div>
          <div style={{ padding: '8px 14px' }}>
            {recent.slice(0, 6).map((r, i) => {
              const d = s.docs.find(x => x.id === r.docId);
              if (!d) return null;
              return (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: i < 5 ? `1px solid ${Tdch.color.border.light}` : 'none', fontSize: '12px' }}>
                  <span style={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }}>{d.name}</span>
                  <span style={{ fontSize: '10px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{r.viewedAt}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '16px', marginBottom: '16px' }}>
        <div style={dcCard}>
          <div style={dcCardH}><span>Recent Audit Trail</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary }}>{k.auditEventsToday} today</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>When</th><th style={dcTh}>User</th><th style={dcTh}>Action</th><th style={dcTh}>Document</th><th style={dcTh}>Sev</th></tr></thead>
            <tbody>
              {audit.map(a => (
                <tr key={a.id}>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{(a.when || '').slice(5)}</td>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{a.user}</td>
                  <td style={dcTd}>{a.action}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary, maxWidth: '320px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.doc}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(a.severity)}18`, dcStatus(a.severity))}>{a.severity}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div>
          <div style={{ ...dcCard, marginBottom: '12px' }}>
            <div style={dcCardH}><span>Storage</span><span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{k.storageGB} / {k.storageCapGB} GB</span></div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ height: '8px', background: Tdch.color.border.light, borderRadius: '4px', overflow: 'hidden', marginBottom: '10px' }}>
                <div style={{ width: `${pct}%`, height: '100%', background: pct > 80 ? '#B91C1C' : '#2563EB' }} />
              </div>
              <div style={{ fontSize: '11px', color: Tdch.color.text.tertiary }}>{pct}% of capacity used. Last backup: <span style={{ fontFamily: Tdch.font.mono }}>{k.lastBackup}</span></div>
            </div>
          </div>
          <div style={dcCard}>
            <div style={dcCardH}>Top Contributors</div>
            <div style={{ padding: '10px 14px' }}>
              {contributors.map(c => (
                <div key={c.user} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: `1px solid ${Tdch.color.border.light}` }}>
                  <span style={{ fontSize: '12px', fontWeight: 600 }}>{c.user}</span>
                  <span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{c.docs} docs · {c.edits} edits</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div style={dcCard}>
        <div style={dcCardH}><span>Pending Approvals — {approvals.length}</span><button style={dcBtn()}>View all</button></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Stage</th><th style={dcTh}>Requester</th><th style={dcTh}>Approver</th><th style={dcTh}>Due</th><th style={dcTh}>Actions</th></tr></thead>
          <tbody>
            {approvals.map(a => (
              <tr key={a.id}>
                <td style={{ ...dcTd, fontWeight: 600 }}>{a.doc}</td>
                <td style={dcTd}><span style={dcTag('rgba(37,99,235,0.1)', '#2563EB')}>{a.stage}</span></td>
                <td style={dcTd}>{a.requester}</td>
                <td style={dcTd}>{a.approver}</td>
                <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{a.due}</td>
                <td style={dcTd}>
                  <div style={{ display: 'flex', gap: '4px' }}>
                    <button onClick={() => window.DocStore.decideApproval(a.id, 'Approved')} style={dcBtn('success')}>Approve</button>
                    <button onClick={() => window.DocStore.decideApproval(a.id, 'Changes')} style={dcBtn('warn')}>Changes</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
window.DcDashboardHub = DcDashboardHub;

// ── BULK ACTION TOOLBAR (#3) ───────────────────────────────────────────────
function DcBulkBar({ selected, onClear }) {
  const [moveOpen, setMoveOpen] = useDcH(false);
  const [confOpen, setConfOpen] = useDcH(false);
  if (!selected || selected.size === 0) return null;
  const ids = [...selected];
  const folders = (window.DOC_FOLDERS || []).filter(f => f.id !== 'F-ROOT');
  const levels = ['Public','Internal','Confidential','Work Product','Highly Confidential','Highly Confidential — AEO'];
  const fire = (action, payload) => { window.DocStore.bulkAction(ids, action, payload); onClear(); setMoveOpen(false); setConfOpen(false); };

  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 50, marginBottom: '10px', padding: '10px 14px', background: '#0A1628', color: '#fff', borderRadius: '8px', display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap', boxShadow: '0 4px 16px rgba(10,22,40,0.25)' }}>
      <span style={{ fontSize: '12px', fontWeight: 700 }}>{selected.size} selected</span>
      <div style={{ flex: 1, display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
        <button onClick={() => fire('star')} style={{ ...dcBtn(), background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff' }}>* Star</button>
        <button onClick={() => fire('tag', prompt('Tag?') || '')} style={{ ...dcBtn(), background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff' }}> Tag</button>
        <div style={{ position: 'relative' }}>
          <button onClick={() => setMoveOpen(o => !o)} style={{ ...dcBtn(), background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff' }}>↗ Move</button>
          {moveOpen && (
            <div style={{ position: 'absolute', top: '100%', left: 0, marginTop: '4px', background: Tdch.color.bg.card, border: `1px solid ${Tdch.color.border.light}`, borderRadius: '6px', maxHeight: '220px', overflow: 'auto', minWidth: '220px', zIndex: 100, color: Tdch.color.text.primary }}>
              {folders.map(f => (
                <div key={f.id} onClick={() => fire('move', f.id)} style={{ padding: '8px 12px', fontSize: '12px', cursor: 'pointer', borderBottom: `1px solid ${Tdch.color.border.light}` }}>{f.name}</div>
              ))}
            </div>
          )}
        </div>
        <div style={{ position: 'relative' }}>
          <button onClick={() => setConfOpen(o => !o)} style={{ ...dcBtn(), background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff' }}>◈ Confidentiality</button>
          {confOpen && (
            <div style={{ position: 'absolute', top: '100%', left: 0, marginTop: '4px', background: Tdch.color.bg.card, border: `1px solid ${Tdch.color.border.light}`, borderRadius: '6px', zIndex: 100, color: Tdch.color.text.primary }}>
              {levels.map(l => (
                <div key={l} onClick={() => fire('confidentiality', l)} style={{ padding: '8px 12px', fontSize: '12px', cursor: 'pointer', borderBottom: `1px solid ${Tdch.color.border.light}`, whiteSpace: 'nowrap' }}>{l}</div>
              ))}
            </div>
          )}
        </div>
        <button onClick={() => fire('hold')} style={{ ...dcBtn(), background: 'rgba(185,28,28,0.8)', border: 'none', color: '#fff' }}> Apply Hold</button>
        <button onClick={() => { if (confirm(`Delete ${ids.length} document(s)?`)) fire('delete'); }} style={{ ...dcBtn(), background: '#B91C1C', border: 'none', color: '#fff' }}> Delete</button>
      </div>
      <button onClick={onClear} style={{ ...dcBtn(), background: 'transparent', border: '1px solid rgba(255,255,255,0.3)', color: '#fff' }}>Clear</button>
    </div>
  );
}
window.DcBulkBar = DcBulkBar;

// ── LIBRARY HUB (bulk + trash + pinned/recent/starred) ─────────────────────
function DcLibraryHub() {
  const s = _useStore(['doc.uploaded','doc.deleted','doc.restored','doc.starred','doc.pinned','doc.unpinned','doc.bulkAction','doc.viewed','doc.shareCreated']);
  const [sub, setSub] = useDcH('all');
  const [selected, setSelected] = useDcH(() => new Set());
  const [hoveredRow, setHoveredRow] = useDcH(null);
  const [sortBy, setSortBy] = useDcH('modified');
  const [sortAsc, setSortAsc] = useDcH(false);
  const [selectedDoc, setSelectedDoc] = useDcH(null);
  const docs = s.docs;
  const starred = s.starred;
  const pinnedIds = new Set((s.pinned || []).map(p => p.docId));
  const recentIds = (s.recentlyViewed || []).map(r => r.docId);
  const toggleStar = (id) => window.DocStore.toggleStar(id);
  const toggleSel  = (id) => setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const handleSort = (col) => { if (sortBy === col) setSortAsc(!sortAsc); else { setSortBy(col); setSortAsc(true); } };
  const openDoc = (d) => { window.DocStore.touch(d.id); setSelectedDoc(d); };

  const views = [
    { id: 'all',     label: 'All',       badge: docs.length },
    { id: 'matter',  label: 'By Matter' },
    { id: 'type',    label: 'By Type' },
    { id: 'recent',  label: 'Recent',    badge: recentIds.length },
    { id: 'pinned',  label: 'Pinned',    badge: pinnedIds.size },
    { id: 'starred', label: 'Starred',   badge: starred.size },
    { id: 'drafts',  label: 'Drafts',    badge: docs.filter(d => d.status === 'Draft').length },
  ];

  const table = (items) => (
    <window.DocTable
      docs={items}
      starred={starred}
      onToggleStar={toggleStar}
      onSelect={openDoc}
      hoveredRow={hoveredRow}
      setHoveredRow={setHoveredRow}
      sortBy={sortBy}
      sortAsc={sortAsc}
      onSort={handleSort}
      selectable={true}
      selected={selected}
      onToggleSelect={toggleSel}
    />
  );

  const body = () => {
    if (sub === 'matter') {
      const groups = {};
      docs.forEach(d => { (groups[d.matter] = groups[d.matter] || []).push(d); });
      return (
        <div style={{ display: 'grid', gap: '12px' }}>
          {Object.entries(groups).map(([m, items]) => (
            <div key={m} style={dcCard}>
              <div style={dcCardH}><span>{m}</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{items.length} docs</span></div>
              {table(items)}
            </div>
          ))}
        </div>
      );
    }
    if (sub === 'type') {
      const groups = {};
      docs.forEach(d => { (groups[d.type] = groups[d.type] || []).push(d); });
      return (
        <div style={{ display: 'grid', gap: '12px' }}>
          {Object.entries(groups).map(([t, items]) => (
            <div key={t} style={dcCard}>
              <div style={dcCardH}><span>{t}</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{items.length}</span></div>
              {table(items)}
            </div>
          ))}
        </div>
      );
    }
    let items = docs;
    if (sub === 'recent')  items = recentIds.map(id => docs.find(d => d.id === id)).filter(Boolean);
    if (sub === 'pinned')  items = [...pinnedIds].map(id => docs.find(d => d.id === id)).filter(Boolean);
    if (sub === 'starred') items = docs.filter(d => starred.has(d.id));
    if (sub === 'drafts')  items = docs.filter(d => d.status === 'Draft');
    if (sub !== 'recent' && sub !== 'pinned') {
      items = [...items].sort((a, b) => {
        const dir = sortAsc ? 1 : -1;
        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 table(items);
  };

  return (
    <div>
      <DcSubNav views={views} active={sub} onChange={setSub} />
      <DcBulkBar selected={selected} onClear={() => setSelected(new Set())} />
      {body()}
      {selectedDoc && <window.DocDetailPanel doc={selectedDoc} onClose={() => setSelectedDoc(null)} onNavigate={() => {}} />}
    </div>
  );
}
window.DcLibraryHub = DcLibraryHub;

// ── FOLDERS HUB ────────────────────────────────────────────────────────────
function DcFoldersHub() {
  const s = _useStore(['doc.uploaded','doc.deleted','doc.bulkAction']);
  const [activeFolder, setActiveFolder] = useDcH('F-ROOT');
  const [hoveredRow, setHoveredRow] = useDcH(null);
  const [selectedDoc, setSelectedDoc] = useDcH(null);
  const docs = s.docs;
  const folders = window.DOC_FOLDERS;

  const childIds = folders.filter(f => f.parent === activeFolder).map(f => f.id);
  const items = activeFolder === 'F-ROOT' ? docs : docs.filter(d => d.folderId === activeFolder || childIds.includes(d.folderId));

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: '12px' }}>
      <div style={{ ...dcCard, padding: '6px' }}>
        <window.DocFolderTree folders={folders} activeFolder={activeFolder} onSelect={setActiveFolder} />
      </div>
      <div>
        <window.DocTable docs={items} starred={s.starred} onToggleStar={(id) => window.DocStore.toggleStar(id)} onSelect={(d) => { window.DocStore.touch(d.id); setSelectedDoc(d); }} hoveredRow={hoveredRow} setHoveredRow={setHoveredRow} sortBy="modified" sortAsc={false} onSort={() => {}} />
        {selectedDoc && <window.DocDetailPanel doc={selectedDoc} onClose={() => setSelectedDoc(null)} onNavigate={() => {}} />}
      </div>
    </div>
  );
}
window.DcFoldersHub = DcFoldersHub;

// ── WORKSPACES HUB ─────────────────────────────────────────────────────────
function DcWorkspacesHub() {
  const [sub, setSub] = useDcH('all');
  const wss = window.DOC_WORKSPACES;
  const byKind = (kinds) => wss.filter(w => kinds.includes(w.kind));
  const filtered = sub === 'all' ? wss : sub === 'team' ? byKind(['Department','Matter']) : sub === 'personal' ? byKind(['Personal']) : sub === 'shared' ? byKind(['Shared']) : byKind(['Archive']);

  const views = [
    { id: 'all',      label: 'All Workspaces', badge: wss.length },
    { id: 'personal', label: 'My Workspace' },
    { id: 'team',     label: 'Team Drives',    badge: byKind(['Department','Matter']).length },
    { id: 'shared',   label: 'Shared With Me' },
    { id: 'archive',  label: 'Archive' },
  ];

  const kindColor = { Personal: '#7C3AED', Department: '#2563EB', Matter: '#059669', Shared: '#B45309', Archive: '#6B7280' };

  return (
    <div>
      <DcSubNav views={views} active={sub} onChange={setSub} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>
        {filtered.map(w => (
          <div key={w.id} style={{ ...dcCard, padding: '14px', cursor: 'pointer' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '8px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <div style={{ width: '32px', height: '32px', borderRadius: '6px', background: `${kindColor[w.kind]}18`, color: kindColor[w.kind], display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px', fontWeight: 700 }}>{w.icon}</div>
                <div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tdch.color.text.primary }}>{w.name}</div>
                  <div style={{ fontSize: '10px', color: Tdch.color.text.tertiary, marginTop: '1px' }}>{w.kind} · {w.members} members</div>
                </div>
              </div>
              <span style={dcTag(`${kindColor[w.kind]}18`, kindColor[w.kind])}>{w.kind}</span>
            </div>
            <div style={{ fontSize: '11px', color: Tdch.color.text.secondary, marginBottom: '10px' }}>{w.desc}</div>
            <div style={{ display: 'flex', gap: '14px', fontSize: '11px', color: Tdch.color.text.tertiary }}>
              <span><strong style={{ color: Tdch.color.text.primary, fontFamily: Tdch.font.mono }}>{w.docs}</strong> docs</span>
              <span><strong style={{ color: Tdch.color.text.primary, fontFamily: Tdch.font.mono }}>{w.size}</strong> size</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.DcWorkspacesHub = DcWorkspacesHub;

// ── SEARCH HUB ─────────────────────────────────────────────────────────────
function DcSearchHub() {
  const s = _useStore(['search.saved','search.deleted','doc.uploaded','doc.deleted']);
  const [selectedDoc, setSelectedDoc] = useDcH(null);
  return (
    <div>
      <window.DocSearchView docs={s.docs} onSelect={(d) => { window.DocStore.touch(d.id); setSelectedDoc(d); }} starred={s.starred} onToggleStar={(id) => window.DocStore.toggleStar(id)} />
      {selectedDoc && <window.DocDetailPanel doc={selectedDoc} onClose={() => setSelectedDoc(null)} onNavigate={() => {}} />}
    </div>
  );
}
window.DcSearchHub = DcSearchHub;

// ── VERSIONS / APPROVALS / CONFLICTS HUB ───────────────────────────────────
function DcVersionsHub() {
  const s = _useStore(['doc.approvalDecided','doc.approvalReassigned','doc.conflictResolved']);
  const [sub, setSub] = useDcH('checkouts');
  const [reassignFor, setReassignFor] = useDcH(null);
  const cos = s.checkouts;
  const aps = s.approvals;
  const docs = s.docs;
  const conflicts = (s.conflicts || []).filter(c => c.status === 'Unresolved');
  const pendingAps = aps.filter(a => a.status === 'Pending');

  const views = [
    { id: 'checkouts', label: 'Checked Out',    badge: cos.length },
    { id: 'approvals', label: 'Approvals',      badge: pendingAps.length },
    { id: 'history',   label: 'Version History' },
    { id: 'conflicts', label: 'Conflicts',      badge: conflicts.length },
  ];

  const body = () => {
    if (sub === 'checkouts') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Checked-out documents — {cos.length}</span><button style={dcBtn()}>Force check-in (admin)</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Locked by</th><th style={dcTh}>Since</th><th style={dcTh}>Notes</th></tr></thead>
            <tbody>
              {cos.map(c => (
                <tr key={c.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{c.docName}</td>
                  <td style={dcTd}><span style={dcTag(c.lockedBy === 'System' ? 'rgba(107,114,128,0.15)' : 'rgba(37,99,235,0.15)', c.lockedBy === 'System' ? '#6B7280' : '#2563EB')}>{c.lockedBy}</span></td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{c.since}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{c.notes}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'approvals') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Approval queue — {aps.length}</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Stage</th><th style={dcTh}>Requester</th><th style={dcTh}>Approver</th><th style={dcTh}>Due</th><th style={dcTh}>Status</th><th style={dcTh}>Actions</th></tr></thead>
            <tbody>
              {aps.map(a => (
                <tr key={a.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{a.doc}</td>
                  <td style={dcTd}>{a.stage}</td>
                  <td style={dcTd}>{a.requester}</td>
                  <td style={dcTd}>{a.approver}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{a.due}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(a.status)}18`, dcStatus(a.status))}>{a.status}</span></td>
                  <td style={dcTd}>
                    {a.status === 'Pending' ? (
                      <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                        <button onClick={() => window.DocStore.decideApproval(a.id, 'Approved')} style={dcBtn('success')}>Approve</button>
                        <button onClick={() => window.DocStore.decideApproval(a.id, 'Changes')} style={dcBtn('warn')}>Request changes</button>
                        <button onClick={() => setReassignFor(a.id)} style={dcBtn()}>Reassign</button>
                      </div>
                    ) : (
                      <span style={{ fontSize: '10px', color: Tdch.color.text.tertiary }}>{a.decidedAt || '—'}</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {reassignFor && (
            <div onClick={() => setReassignFor(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.4)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div onClick={e => e.stopPropagation()} style={{ background: Tdch.color.bg.card, borderRadius: '10px', padding: '20px', width: '360px' }}>
                <div style={{ fontSize: '14px', fontWeight: 700, marginBottom: '10px' }}>Reassign approval</div>
                <div style={{ fontSize: '11px', color: Tdch.color.text.tertiary, marginBottom: '8px' }}>New approver:</div>
                {['M. Kirkland','A. Petrov','S. Chen','R. Vasquez','L. Torres'].map(u => (
                  <button key={u} onClick={() => { window.DocStore.reassignApproval(reassignFor, u); setReassignFor(null); }} style={{ display: 'block', width: '100%', padding: '8px 10px', marginBottom: '4px', fontSize: '12px', textAlign: 'left', border: `1px solid ${Tdch.color.border.light}`, background: Tdch.color.bg.primary, borderRadius: '6px', cursor: 'pointer' }}>{u}</button>
                ))}
              </div>
            </div>
          )}
        </div>
      );
    }
    if (sub === 'history') {
      const withVersions = docs.filter(d => (d.versions || []).length > 1).slice(0, 10);
      return (
        <div style={{ display: 'grid', gap: '10px' }}>
          {withVersions.map(d => (
            <div key={d.id} style={dcCard}>
              <div style={dcCardH}><span>{d.name}</span><span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{d.versions.length} versions</span></div>
              <div style={{ padding: '8px 16px' }}>
                {d.versions.map((v, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '60px 100px 140px 80px 1fr', gap: '10px', padding: '6px 0', borderBottom: i < d.versions.length - 1 ? `1px solid ${Tdch.color.border.light}` : 'none', fontSize: '11px' }}>
                    <span style={{ fontFamily: Tdch.font.mono, fontWeight: 700, color: '#2563EB' }}>v{v.v}</span>
                    <span style={{ color: Tdch.color.text.tertiary }}>{v.date}</span>
                    <span>{v.author}</span>
                    <span style={{ fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{v.size}</span>
                    <span style={{ color: Tdch.color.text.secondary }}>{v.notes}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      );
    }
    if (conflicts.length === 0) {
      return (
        <div style={{ ...dcCard, padding: '40px', textAlign: 'center', color: Tdch.color.text.tertiary }}>
          No merge conflicts — all concurrent edits have been resolved.
        </div>
      );
    }
    const sevColor = { High: '#B91C1C', Medium: '#B45309', Low: '#6B7280' };
    return (
      <div style={{ display: 'grid', gap: '10px' }}>
        {conflicts.map(c => (
          <div key={c.id} style={dcCard}>
            <div style={dcCardH}>
              <span>{c.docName}</span>
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <span style={dcTag(`${sevColor[c.severity]}18`, sevColor[c.severity])}>{c.severity}</span>
                <span style={{ fontSize: '11px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{c.detected}</span>
              </div>
            </div>
            <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
              <div style={{ padding: '10px', background: 'rgba(37,99,235,0.06)', borderRadius: '6px', border: '1px solid rgba(37,99,235,0.2)' }}>
                <div style={{ fontSize: '11px', fontWeight: 700, color: '#2563EB', marginBottom: '4px' }}>Branch A · {c.branchA.user}</div>
                <div style={{ fontSize: '12px', color: Tdch.color.text.primary }}>{c.branchA.change}</div>
                <button onClick={() => window.DocStore.resolveConflict(c.id, 'A')} style={{ ...dcBtn('primary'), marginTop: '8px' }}>Keep A</button>
              </div>
              <div style={{ padding: '10px', background: 'rgba(124,58,237,0.06)', borderRadius: '6px', border: '1px solid rgba(124,58,237,0.2)' }}>
                <div style={{ fontSize: '11px', fontWeight: 700, color: '#7C3AED', marginBottom: '4px' }}>Branch B · {c.branchB.user}</div>
                <div style={{ fontSize: '12px', color: Tdch.color.text.primary }}>{c.branchB.change}</div>
                <button onClick={() => window.DocStore.resolveConflict(c.id, 'B')} style={{ ...dcBtn(), marginTop: '8px', background: '#7C3AED', color: '#fff', border: 'none' }}>Keep B</button>
              </div>
            </div>
            <div style={{ padding: '0 16px 12px', display: 'flex', justifyContent: 'flex-end' }}>
              <button onClick={() => window.DocStore.resolveConflict(c.id, 'merge')} style={dcBtn()}>Merge both manually</button>
            </div>
          </div>
        ))}
      </div>
    );
  };

  return (<div><DcSubNav views={views} active={sub} onChange={setSub} />{body()}</div>);
}
window.DcVersionsHub = DcVersionsHub;

// ── COMPLIANCE HUB ─────────────────────────────────────────────────────────
function DcComplianceHub() {
  const s = _useStore(['doc.holdApplied','doc.holdReleased','doc.holdReminder','doc.holdAck','access.certified','doc.retentionApplied']);
  const [sub, setSub] = useDcH('holds');
  const [drillHoldId, setDrillHoldId] = useDcH(null);
  const holds = s.holds;
  const rp = s.retention;
  const audit = s.audit;
  const docs = s.docs;
  const cus = s.custodians || [];
  const activeHolds = holds.filter(h => h.status === 'Active');

  const views = [
    { id: 'holds',      label: 'Legal Holds',      badge: activeHolds.length },
    { id: 'custodians', label: 'Custodians',       badge: cus.length },
    { id: 'retention',  label: 'Retention',        badge: rp.filter(r => r.status === 'Active').length },
    { id: 'audit',      label: 'Audit Trail',      badge: audit.length },
    { id: 'privilege',  label: 'Privilege Log' },
    { id: 'confid',     label: 'Confidentiality' },
  ];

  const body = () => {
    if (sub === 'holds') {
      return (
        <div>
          <div style={dcCard}>
            <div style={dcCardH}><span>Legal holds</span><button style={dcBtn('danger')}>+ Issue Hold</button></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><th style={dcTh}>Hold</th><th style={dcTh}>Matter</th><th style={dcTh}>Custodians</th><th style={dcTh}>Docs</th><th style={dcTh}>Issued</th><th style={dcTh}>Last Reminder</th><th style={dcTh}>Owner</th><th style={dcTh}>Status</th><th style={dcTh}>Actions</th></tr></thead>
              <tbody>
                {holds.map(h => (
                  <tr key={h.id}>
                    <td style={{ ...dcTd, fontWeight: 600 }}>{h.name}</td>
                    <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{h.matter}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{h.custodians}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{h.docs}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{h.issued}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{h.lastReminder}</td>
                    <td style={dcTd}>{h.owner}</td>
                    <td style={dcTd}><span style={dcTag(`${dcStatus(h.status)}18`, dcStatus(h.status))}>{h.status}</span></td>
                    <td style={dcTd}>
                      <div style={{ display: 'flex', gap: '4px' }}>
                        <button onClick={() => setDrillHoldId(h.id)} style={dcBtn()}>Drill</button>
                        {h.status === 'Active' ? <button onClick={() => window.DocStore.releaseHold(h.id)} style={dcBtn('warn')}>Release</button> : <button onClick={() => window.DocStore.applyHold(h.id)} style={dcBtn('success')}>Apply</button>}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {drillHoldId && (() => {
            const h = holds.find(x => x.id === drillHoldId);
            const list = cus.filter(c => c.holdId === drillHoldId);
            return (
              <div onClick={() => setDrillHoldId(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.4)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <div onClick={e => e.stopPropagation()} style={{ background: Tdch.color.bg.primary, borderRadius: '10px', width: '720px', maxHeight: '80vh', overflow: 'auto' }}>
                  <div style={{ padding: '14px 18px', borderBottom: `1px solid ${Tdch.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontSize: '14px', fontWeight: 700 }}>{h.name}</div>
                      <div style={{ fontSize: '11px', color: Tdch.color.text.tertiary, marginTop: '2px' }}>{h.matter} · {list.length} custodians</div>
                    </div>
                    <button onClick={() => setDrillHoldId(null)} style={{ background: 'none', border: 'none', fontSize: '20px', cursor: 'pointer', color: Tdch.color.text.tertiary }}>×</button>
                  </div>
                  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead><tr><th style={dcTh}>Custodian</th><th style={dcTh}>Role</th><th style={dcTh}>Ack</th><th style={dcTh}>Questionnaire</th><th style={dcTh}>Reminders</th><th style={dcTh}>Actions</th></tr></thead>
                    <tbody>
                      {list.map(c => (
                        <tr key={c.id}>
                          <td style={{ ...dcTd, fontWeight: 600 }}>{c.name}<div style={{ fontSize: '10px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{c.email}</div></td>
                          <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{c.role}</td>
                          <td style={dcTd}>{c.ack ? <span style={dcTag('#05966918','#059669')}>Ack'd {c.ackDate}</span> : <span style={dcTag('#B91C1C18','#B91C1C')}>Pending</span>}</td>
                          <td style={dcTd}><span style={dcTag(c.questionnaire === 'Complete' ? '#05966918' : c.questionnaire === 'Partial' ? '#B4530918' : '#B91C1C18', c.questionnaire === 'Complete' ? '#059669' : c.questionnaire === 'Partial' ? '#B45309' : '#B91C1C')}>{c.questionnaire}</span></td>
                          <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{c.reminders}</td>
                          <td style={dcTd}>
                            <div style={{ display: 'flex', gap: '4px' }}>
                              <button onClick={() => window.DocStore.sendHoldReminder(drillHoldId, c.id)} style={dcBtn()}>Remind</button>
                              {!c.ack && <button onClick={() => window.DocStore.ackHold(c.id)} style={dcBtn('success')}>Mark Ack'd</button>}
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            );
          })()}
        </div>
      );
    }
    if (sub === 'custodians') {
      const byHold = {};
      cus.forEach(c => { (byHold[c.holdId] = byHold[c.holdId] || []).push(c); });
      return (
        <div style={{ display: 'grid', gap: '10px' }}>
          {Object.entries(byHold).map(([hid, list]) => {
            const h = holds.find(x => x.id === hid);
            const ack = list.filter(c => c.ack).length;
            return (
              <div key={hid} style={dcCard}>
                <div style={dcCardH}>
                  <span>{h ? h.name : hid}</span>
                  <span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{ack}/{list.length} ack'd</span>
                </div>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead><tr><th style={dcTh}>Name</th><th style={dcTh}>Role</th><th style={dcTh}>Ack</th><th style={dcTh}>Questionnaire</th><th style={dcTh}>Reminders</th><th style={dcTh}>Actions</th></tr></thead>
                  <tbody>
                    {list.map(c => (
                      <tr key={c.id}>
                        <td style={{ ...dcTd, fontWeight: 600 }}>{c.name}</td>
                        <td style={dcTd}>{c.role}</td>
                        <td style={dcTd}>{c.ack ? <span style={dcTag('#05966918','#059669')}>Yes</span> : <span style={dcTag('#B91C1C18','#B91C1C')}>No</span>}</td>
                        <td style={dcTd}>{c.questionnaire}</td>
                        <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{c.reminders}</td>
                        <td style={dcTd}>
                          <button onClick={() => window.DocStore.sendHoldReminder(hid, c.id)} style={dcBtn()}>Send reminder</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            );
          })}
        </div>
      );
    }
    if (sub === 'retention') {
      // Timeline viz: years across, policies down
      const maxYrs = Math.max(10, ...rp.filter(r => r.durationYrs).map(r => r.durationYrs));
      return (
        <div>
          <div style={{ ...dcCard, marginBottom: '12px' }}>
            <div style={dcCardH}><span>Retention timeline (years to action)</span></div>
            <div style={{ padding: '14px 16px' }}>
              {rp.map(r => (
                <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '220px 1fr 120px', gap: '10px', alignItems: 'center', padding: '8px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, fontSize: '11px' }}>
                  <div>
                    <div style={{ fontWeight: 700, color: Tdch.color.text.primary }}>{r.name}</div>
                    <div style={{ fontSize: '10px', color: Tdch.color.text.tertiary }}>{r.trigger}</div>
                  </div>
                  <div style={{ position: 'relative', height: '16px', background: Tdch.color.bg.secondary, borderRadius: '8px' }}>
                    {r.durationYrs ? (
                      <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${(r.durationYrs / maxYrs) * 100}%`, background: r.action.toLowerCase().includes('delete') ? '#B91C1C' : r.action.toLowerCase().includes('archive') ? '#B45309' : '#2563EB', borderRadius: '8px', display: 'flex', alignItems: 'center', paddingLeft: '10px', color: '#fff', fontSize: '10px', fontWeight: 700, fontFamily: Tdch.font.mono }}>
                        {r.durationYrs} yr → {r.action}
                      </div>
                    ) : (
                      <div style={{ padding: '2px 10px', fontSize: '10px', color: Tdch.color.text.tertiary }}>Indefinite</div>
                    )}
                  </div>
                  <span style={dcTag(`${dcStatus(r.status)}18`, dcStatus(r.status))}>{r.status}</span>
                </div>
              ))}
            </div>
          </div>
          <div style={dcCard}>
            <div style={dcCardH}><span>Retention policies</span><button style={dcBtn()}>+ New Policy</button></div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead><tr><th style={dcTh}>Policy</th><th style={dcTh}>Trigger</th><th style={dcTh}>Action</th><th style={dcTh}>Duration</th><th style={dcTh}>Applies To</th><th style={dcTh}>Docs</th><th style={dcTh}>Status</th></tr></thead>
              <tbody>
                {rp.map(r => (
                  <tr key={r.id}>
                    <td style={{ ...dcTd, fontWeight: 600 }}>{r.name}</td>
                    <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{r.trigger}</td>
                    <td style={dcTd}>{r.action}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{r.durationYrs == null ? '—' : `${r.durationYrs} yr`}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{r.appliesTo}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{r.docs}</td>
                    <td style={dcTd}><span style={dcTag(`${dcStatus(r.status)}18`, dcStatus(r.status))}>{r.status}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      );
    }
    if (sub === 'audit') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Audit trail — {audit.length} recent events</span><button style={dcBtn()}>Export CSV</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>When</th><th style={dcTh}>User</th><th style={dcTh}>Action</th><th style={dcTh}>Document</th><th style={dcTh}>IP</th><th style={dcTh}>Severity</th></tr></thead>
            <tbody>
              {audit.slice(0, 40).map(a => (
                <tr key={a.id}>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{a.when}</td>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{a.user}</td>
                  <td style={dcTd}>{a.action}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{a.doc}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{a.ip}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(a.severity)}18`, dcStatus(a.severity))}>{a.severity}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'privilege') {
      const priv = docs.filter(d => (d.tags || []).some(t => t.toLowerCase().includes('privileg')) || d.confidentiality === 'Work Product');
      const fallback = priv.length ? priv : docs.filter(d => d.confidentiality && d.confidentiality !== 'Public').slice(0, 12);
      // Bates-numbered export
      const withBates = fallback.map((d, i) => ({ ...d, bates: `FIRM-${String(i + 1).padStart(5, '0')}` }));
      return (
        <div style={dcCard}>
          <div style={dcCardH}>
            <span>Privilege log — {withBates.length}</span>
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={dcBtn()}>Export CSV</button>
              <button style={dcBtn('primary')}>Produce (Bates)</button>
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Bates</th><th style={dcTh}>Doc</th><th style={dcTh}>Matter</th><th style={dcTh}>Author</th><th style={dcTh}>Confidentiality</th><th style={dcTh}>Date</th></tr></thead>
            <tbody>
              {withBates.map(d => (
                <tr key={d.id}>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontWeight: 700, color: '#2563EB' }}>{d.bates}</td>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{d.name}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{d.matter}</td>
                  <td style={dcTd}>{d.author}</td>
                  <td style={dcTd}><span style={dcTag('rgba(124,58,237,0.12)', '#7C3AED')}>{d.confidentiality}</span></td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{d.modified}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    // Confidentiality — trend + grouping
    const trend = s.confidTrend || [];
    const groups = {};
    docs.forEach(d => { (groups[d.confidentiality] = groups[d.confidentiality] || []).push(d); });
    const order = ['Public', 'Internal', 'Confidential', 'Work Product', 'Highly Confidential', 'Highly Confidential — AEO'];
    const ordered = order.filter(o => groups[o]).map(o => [o, groups[o]]);
    const trendMax = Math.max(1, ...trend.flatMap(t => Object.values(t).filter(v => typeof v === 'number')));
    const levelColor = { Public: '#6B7280', Internal: '#2563EB', Confidential: '#7C3AED', 'Work Product': '#B45309', 'Highly Confidential': '#B91C1C', 'Highly Confidential — AEO': '#7F1D1D' };
    return (
      <div>
        <div style={{ ...dcCard, marginBottom: '12px' }}>
          <div style={dcCardH}><span>Confidentiality trend (6 months)</span></div>
          <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: `repeat(${trend.length}, 1fr)`, gap: '10px', alignItems: 'end' }}>
            {trend.map(t => {
              const levels = order.filter(o => t[o]);
              return (
                <div key={t.month} style={{ display: 'flex', flexDirection: 'column', gap: '2px', alignItems: 'center' }}>
                  <div style={{ display: 'flex', flexDirection: 'column-reverse', width: '30px', height: '140px' }}>
                    {levels.map(l => (
                      <div key={l} title={`${l}: ${t[l]}`} style={{ height: `${(t[l] / trendMax) * 140}px`, background: levelColor[l] || '#6B7280', marginTop: '1px' }} />
                    ))}
                  </div>
                  <div style={{ fontSize: '10px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>{t.month.slice(5)}</div>
                </div>
              );
            })}
          </div>
          <div style={{ padding: '0 16px 12px', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
            {order.map(l => <span key={l} style={{ fontSize: '10px', color: Tdch.color.text.secondary, display: 'flex', alignItems: 'center', gap: '4px' }}><span style={{ width: '10px', height: '10px', background: levelColor[l], borderRadius: '2px' }} />{l}</span>)}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
          {ordered.map(([lvl, items]) => (
            <div key={lvl} style={dcCard}>
              <div style={dcCardH}><span>{lvl}</span><span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{items.length}</span></div>
              <div style={{ padding: '10px 14px' }}>
                {items.slice(0, 6).map(d => (
                  <div key={d.id} style={{ fontSize: '11px', padding: '4px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, color: Tdch.color.text.primary }}>{d.name}</div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (<div><DcSubNav views={views} active={sub} onChange={setSub} />{body()}</div>);
}
window.DcComplianceHub = DcComplianceHub;

// ── TEMPLATES HUB ──────────────────────────────────────────────────────────
function DcTemplatesHub() {
  const [sub, setSub] = useDcH('all');
  const tpls = window.DOC_TEMPLATES;
  const views = [
    { id: 'all',      label: 'All',    badge: tpls.length },
    { id: 'category', label: 'By Category' },
    { id: 'usage',    label: 'Usage' },
  ];

  if (sub === 'all') {
    return (<div><DcSubNav views={views} active={sub} onChange={setSub} /><window.DocTemplatesView /></div>);
  }
  if (sub === 'category') {
    const groups = {};
    tpls.forEach(t => { (groups[t.type] = groups[t.type] || []).push(t); });
    return (
      <div>
        <DcSubNav views={views} active={sub} onChange={setSub} />
        <div style={{ display: 'grid', gap: '10px' }}>
          {Object.entries(groups).map(([cat, items]) => (
            <div key={cat} style={dcCard}>
              <div style={dcCardH}><span>{cat}</span><span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{items.length}</span></div>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead><tr><th style={dcTh}>Name</th><th style={dcTh}>Author</th><th style={dcTh}>Last Used</th><th style={dcTh}>Usage</th></tr></thead>
                <tbody>
                  {items.map(t => (
                    <tr key={t.id}>
                      <td style={{ ...dcTd, fontWeight: 600 }}>{t.name}</td>
                      <td style={dcTd}>{t.author}</td>
                      <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{t.lastUsed}</td>
                      <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{t.usageCount}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ))}
        </div>
      </div>
    );
  }
  const sorted = [...tpls].sort((a, b) => b.usageCount - a.usageCount);
  const max = Math.max(...tpls.map(t => t.usageCount));
  return (
    <div>
      <DcSubNav views={views} active={sub} onChange={setSub} />
      <div style={dcCard}>
        <div style={dcCardH}><span>Template usage (all time)</span></div>
        <div style={{ padding: '12px 16px' }}>
          {sorted.map(t => (
            <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, fontSize: '12px' }}>
              <span style={{ width: '220px', fontWeight: 600 }}>{t.name}</span>
              <div style={{ flex: 1, height: '6px', background: Tdch.color.border.light, borderRadius: '3px' }}>
                <div style={{ height: '100%', borderRadius: '3px', width: `${(t.usageCount / max) * 100}%`, background: '#2563EB' }} />
              </div>
              <span style={{ fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary, minWidth: '36px', textAlign: 'right' }}>{t.usageCount}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.DcTemplatesHub = DcTemplatesHub;

// ── AUTOMATION HUB ─────────────────────────────────────────────────────────
function DcAutomationHub() {
  const s = _useStore(['esign.sent','esign.completed','workflow.triggered','ocr.queued']);
  const [sub, setSub] = useDcH('workflows');
  const [envOpen, setEnvOpen] = useDcH(null);
  const wfs = s.workflows;
  const ocr = s.ocr;
  const dlp = s.dlp;
  const envs = s.envelopes || [];

  const views = [
    { id: 'workflows', label: 'Workflows',     badge: wfs.length },
    { id: 'ocr',       label: 'OCR Pipelines', badge: ocr.length },
    { id: 'dlp',       label: 'DLP Rules',     badge: dlp.length },
    { id: 'esign',     label: 'eSign',         badge: envs.filter(e => e.status === 'Awaiting').length },
  ];

  const body = () => {
    if (sub === 'workflows') {
      return (
        <div style={{ display: 'grid', gap: '10px' }}>
          {wfs.map(w => (
            <div key={w.id} style={dcCard}>
              <div style={dcCardH}>
                <span>{w.name}</span>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{w.runs} runs · last {w.lastRun}</span>
                  <span style={dcTag(`${dcStatus(w.status)}18`, dcStatus(w.status))}>{w.status}</span>
                </div>
              </div>
              <div style={{ padding: '10px 16px', fontSize: '11px' }}>
                <div style={{ color: Tdch.color.text.tertiary, marginBottom: '6px' }}>Trigger: <span style={{ fontFamily: Tdch.font.mono, color: Tdch.color.text.secondary }}>{w.trigger}</span></div>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {w.steps.map((step, i) => (
                    <React.Fragment key={i}>
                      <span style={{ padding: '3px 8px', background: Tdch.color.bg.secondary, borderRadius: '4px', fontSize: '10px', fontWeight: 600 }}>{step}</span>
                      {i < w.steps.length - 1 && <span style={{ color: Tdch.color.text.tertiary }}>→</span>}
                    </React.Fragment>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      );
    }
    if (sub === 'ocr') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>OCR pipelines</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Pipeline</th><th style={dcTh}>Queue</th><th style={dcTh}>Avg Time</th><th style={dcTh}>Accuracy</th><th style={dcTh}>Last Run</th></tr></thead>
            <tbody>
              {ocr.map(o => (
                <tr key={o.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{o.name}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{o.queue}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{o.avgTimeSec}s</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right', color: o.accuracy > 95 ? '#059669' : '#B45309' }}>{o.accuracy}%</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.tertiary }}>{o.lastRun}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'dlp') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Data-loss prevention policies</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Policy</th><th style={dcTh}>Action</th><th style={dcTh}>Hits (30d)</th><th style={dcTh}>Last Hit</th><th style={dcTh}>Status</th></tr></thead>
            <tbody>
              {dlp.map(d => (
                <tr key={d.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{d.name}</td>
                  <td style={dcTd}><span style={dcTag('rgba(185,28,28,0.12)', '#B91C1C')}>{d.action}</span></td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{d.hits30d}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{d.lastHit}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(d.status)}18`, dcStatus(d.status))}>{d.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    const completed = envs.filter(e => e.status === 'Completed').length;
    const awaiting = envs.filter(e => e.status === 'Awaiting').length;
    const declined = envs.filter(e => e.status === 'Declined').length;
    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px', marginBottom: '12px' }}>
          {dcStatCard('Envelopes — awaiting', awaiting, '#B45309')}
          {dcStatCard('Completed (30d)', completed, '#059669')}
          {dcStatCard('Declined', declined, '#B91C1C')}
        </div>
        <div style={dcCard}>
          <div style={dcCardH}><span>SignDesk envelopes — {envs.length}</span><button style={dcBtn('primary')}>+ Send for signature</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Created by</th><th style={dcTh}>Sent</th><th style={dcTh}>Signers</th><th style={dcTh}>Reminders</th><th style={dcTh}>Status</th><th style={dcTh}></th></tr></thead>
            <tbody>
              {envs.map(e => (
                <React.Fragment key={e.id}>
                  <tr onClick={() => setEnvOpen(envOpen === e.id ? null : e.id)} style={{ cursor: 'pointer' }}>
                    <td style={{ ...dcTd, fontWeight: 600 }}>{e.docName}</td>
                    <td style={dcTd}>{e.createdBy}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{e.sent}</td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>
                      <span style={{ color: '#059669' }}>{e.signers.filter(sg => sg.status === 'Signed').length}</span>
                      <span style={{ color: Tdch.color.text.tertiary }}> / {e.signers.length}</span>
                    </td>
                    <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{e.reminders}</td>
                    <td style={dcTd}><span style={dcTag(`${dcStatus(e.status)}18`, dcStatus(e.status))}>{e.status}</span></td>
                    <td style={dcTd}><span style={{ color: Tdch.color.text.tertiary }}>{envOpen === e.id ? '▼' : '▶'}</span></td>
                  </tr>
                  {envOpen === e.id && (
                    <tr>
                      <td colSpan={7} style={{ ...dcTd, background: Tdch.color.bg.secondary, padding: '14px 20px' }}>
                        <div style={{ fontSize: '11px', fontWeight: 700, marginBottom: '8px', color: Tdch.color.text.primary }}>Signers</div>
                        {e.signers.map((sg, idx) => (
                          <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: idx < e.signers.length - 1 ? `1px solid ${Tdch.color.border.light}` : 'none', fontSize: '11px' }}>
                            <span style={{ fontWeight: 600 }}>{sg.name}</span>
                            <span style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                              <span style={dcTag(`${dcStatus(sg.status)}18`, dcStatus(sg.status))}>{sg.status}</span>
                              <span style={{ fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>{sg.when || '—'}</span>
                            </span>
                          </div>
                        ))}
                        {e.status === 'Awaiting' && <div style={{ marginTop: '10px', display: 'flex', gap: '6px' }}>
                          <button style={dcBtn('primary')}>Send reminder</button>
                          <button style={dcBtn('warn')}>Void envelope</button>
                        </div>}
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  return (<div><DcSubNav views={views} active={sub} onChange={setSub} />{body()}</div>);
}
window.DcAutomationHub = DcAutomationHub;

// ── GOVERNANCE HUB ─────────────────────────────────────────────────────────
function DcGovernanceHub() {
  const s = _useStore(['access.certified','doc.shareCreated','doc.shareRevoked']);
  const [sub, setSub] = useDcH('permissions');
  const ar = s.accessReviews;
  const sh = s.shares;
  const docs = s.docs;
  const dlp = s.dlp;
  const shareRisk = s.shareRisk || {};

  const views = [
    { id: 'permissions',  label: 'Permissions' },
    { id: 'reviews',      label: 'Access Reviews',  badge: ar.filter(r => r.status !== 'Current').length },
    { id: 'shares',       label: 'Active Shares',   badge: sh.length },
    { id: 'risk',         label: 'Share Risk',      badge: Object.values(shareRisk).filter(r => r.score >= 40).length },
    { id: 'dlp',          label: 'DLP Incidents',   badge: dlp.reduce((sum, d) => sum + d.hits30d, 0) },
  ];

  const body = () => {
    if (sub === 'permissions') {
      const sample = docs.filter(d => d.permissions && d.permissions.length).slice(0, 10);
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Document permissions (sample)</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Confidentiality</th><th style={dcTh}>Permitted Users</th><th style={dcTh}>Locked</th></tr></thead>
            <tbody>
              {sample.map(d => (
                <tr key={d.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{d.name}</td>
                  <td style={dcTd}><span style={dcTag('rgba(124,58,237,0.12)', '#7C3AED')}>{d.confidentiality}</span></td>
                  <td style={{ ...dcTd, fontSize: '11px', color: Tdch.color.text.secondary }}>{(d.permissions || []).join(', ')}</td>
                  <td style={dcTd}>{d.locked ? <span style={dcTag('rgba(180,83,9,0.15)', '#B45309')}>Locked</span> : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'reviews') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Access reviews</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Folder</th><th style={dcTh}>Users</th><th style={dcTh}>Last Review</th><th style={dcTh}>Next Due</th><th style={dcTh}>Status</th><th style={dcTh}>Actions</th></tr></thead>
            <tbody>
              {ar.map(r => (
                <tr key={r.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{r.folder}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'center' }}>{r.users}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{r.lastReview}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{r.nextDue}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(r.status)}18`, dcStatus(r.status))}>{r.status}</span></td>
                  <td style={dcTd}>
                    {r.status !== 'Current' ? (
                      <button onClick={() => window.DocStore.certifyAccessReview(r.id)} style={dcBtn('success')}>Certify</button>
                    ) : <span style={{ fontSize: '10px', color: Tdch.color.text.tertiary }}>Certified</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'shares') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Active external & internal shares</span><button style={dcBtn()}>Revoke expired</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Recipient</th><th style={dcTh}>Scope</th><th style={dcTh}>Expires</th><th style={dcTh}>Created By</th><th style={dcTh}>Status</th><th style={dcTh}>Actions</th></tr></thead>
            <tbody>
              {sh.map(share => (
                <tr key={share.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{share.doc}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: Tdch.color.text.secondary }}>{share.recipient}</td>
                  <td style={dcTd}><span style={dcTag('rgba(37,99,235,0.12)', '#2563EB')}>{share.scope}</span></td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{share.expires || '—'}</td>
                  <td style={dcTd}>{share.createdBy}</td>
                  <td style={dcTd}><span style={dcTag(`${dcStatus(share.status)}18`, dcStatus(share.status))}>{share.status}</span></td>
                  <td style={dcTd}>
                    {share.status === 'Active' && <button onClick={() => window.DocStore.revokeShare(share.id)} style={dcBtn('danger')}>Revoke</button>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'risk') {
      const rows = sh.map(share => ({ ...share, risk: shareRisk[share.id] || { score: 0, factors: [] } })).sort((a, b) => b.risk.score - a.risk.score);
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Share risk scoring</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary }}>Higher = more exposure</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Recipient</th><th style={dcTh}>Risk</th><th style={dcTh}>Factors</th><th style={dcTh}>Actions</th></tr></thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.id}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{r.doc}</td>
                  <td style={{ ...dcTd, fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.secondary }}>{r.recipient}</td>
                  <td style={dcTd}>{dcRiskBar(r.risk.score)}</td>
                  <td style={{ ...dcTd, fontSize: '11px', color: Tdch.color.text.secondary }}>{r.risk.factors.join(' · ')}</td>
                  <td style={dcTd}>
                    {r.risk.score >= 40 && r.status === 'Active' && <button onClick={() => window.DocStore.revokeShare(r.id)} style={dcBtn('danger')}>Revoke</button>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    return (
      <div style={dcCard}>
        <div style={dcCardH}><span>DLP incidents (30d)</span></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><th style={dcTh}>Policy</th><th style={dcTh}>Action</th><th style={dcTh}>Hits</th><th style={dcTh}>Last Hit</th></tr></thead>
          <tbody>
            {dlp.map(d => (
              <tr key={d.id}>
                <td style={{ ...dcTd, fontWeight: 600 }}>{d.name}</td>
                <td style={dcTd}>{d.action}</td>
                <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right', color: d.hits30d > 10 ? '#B91C1C' : Tdch.color.text.primary }}>{d.hits30d}</td>
                <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{d.lastHit}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  };

  return (<div><DcSubNav views={views} active={sub} onChange={setSub} />{body()}</div>);
}
window.DcGovernanceHub = DcGovernanceHub;

// ── ANALYTICS HUB — extended (#18) ─────────────────────────────────────────
function DcAnalyticsHub() {
  const s = _useStore(['doc.uploaded','doc.deleted']);
  const [sub, setSub] = useDcH('velocity');
  const a = window.DOC_ANALYTICS;
  const c = window.DOC_CONTRIBUTORS;
  const vel = s.velocity || [];
  const stale = s.stale || [];
  const cost = s.costByMatter || [];
  const heat = s.heatmap || [];

  const views = [
    { id: 'velocity',     label: 'Velocity' },
    { id: 'heatmap',      label: 'Activity Heatmap' },
    { id: 'storage',      label: 'Storage' },
    { id: 'contributors', label: 'Contributors', badge: c.length },
    { id: 'types',        label: 'By Type' },
    { id: 'stale',        label: 'Stale',        badge: stale.length },
    { id: 'cost',         label: 'Cost by Matter' },
  ];

  const body = () => {
    if (sub === 'velocity') {
      const maxU = Math.max(1, ...vel.map(d => d.uploads));
      const maxE = Math.max(1, ...vel.map(d => d.edits));
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Upload & edit velocity (30 days)</span><span style={{ fontSize: '11px', color: Tdch.color.text.tertiary }}>uploads (blue) · edits (purple)</span></div>
          <div style={{ padding: '16px', display: 'flex', alignItems: 'flex-end', gap: '3px', height: '180px' }}>
            {vel.map((d, i) => (
              <div key={i} title={`${d.date}: ${d.uploads} up · ${d.edits} edits`} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: '2px' }}>
                <div style={{ height: `${(d.edits / maxE) * 80}px`, background: '#7C3AED', borderRadius: '2px 2px 0 0' }} />
                <div style={{ height: `${(d.uploads / maxU) * 60}px`, background: '#2563EB', borderRadius: '0 0 2px 2px' }} />
              </div>
            ))}
          </div>
          <div style={{ padding: '0 16px 12px', display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tdch.color.text.tertiary, fontFamily: Tdch.font.mono }}>
            <span>{vel[0]?.date}</span><span>{vel[vel.length - 1]?.date}</span>
          </div>
        </div>
      );
    }
    if (sub === 'heatmap') {
      const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
      const maxV = Math.max(1, ...heat.flat());
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Activity heatmap — hour × day of week</span></div>
          <div style={{ padding: '14px 16px', overflowX: 'auto' }}>
            <div style={{ display: 'inline-grid', gridTemplateColumns: `40px repeat(24, 20px)`, gap: '2px' }}>
              <div />
              {Array.from({ length: 24 }, (_, h) => (
                <div key={h} style={{ fontSize: '9px', color: Tdch.color.text.tertiary, textAlign: 'center', fontFamily: Tdch.font.mono }}>{h}</div>
              ))}
              {heat.map((row, di) => (
                <React.Fragment key={di}>
                  <div style={{ fontSize: '10px', color: Tdch.color.text.tertiary, fontWeight: 600, display: 'flex', alignItems: 'center' }}>{days[di]}</div>
                  {row.map((v, h) => (
                    <div key={h} title={`${days[di]} ${h}:00 — ${v} events`} style={{ width: '20px', height: '20px', background: `rgba(37,99,235,${v / maxV})`, borderRadius: '2px', border: v === 0 ? `1px solid ${Tdch.color.border.light}` : 'none' }} />
                  ))}
                </React.Fragment>
              ))}
            </div>
          </div>
        </div>
      );
    }
    if (sub === 'storage') return <window.DocAnalyticsView />;
    if (sub === 'contributors') {
      const max = Math.max(...c.map(x => x.edits));
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Top contributors</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>User</th><th style={dcTh}>Docs</th><th style={dcTh}>Edits</th><th style={dcTh}>Activity</th><th style={dcTh}>Comments</th></tr></thead>
            <tbody>
              {c.map(r => (
                <tr key={r.user}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{r.user}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{r.docs}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{r.edits}</td>
                  <td style={dcTd}>
                    <div style={{ height: '6px', background: Tdch.color.border.light, borderRadius: '3px' }}>
                      <div style={{ height: '100%', borderRadius: '3px', width: `${(r.edits / max) * 100}%`, background: '#2563EB' }} />
                    </div>
                  </td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{r.comments}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    if (sub === 'types') {
      const max = Math.max(...a.byType.map(t => t.count));
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Distribution by type</span></div>
          <div style={{ padding: '14px 16px' }}>
            {a.byType.map(t => (
              <div key={t.name} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '6px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, fontSize: '12px' }}>
                <span style={{ width: '140px', fontWeight: 600 }}>{t.name}</span>
                <div style={{ flex: 1, height: '6px', background: Tdch.color.border.light, borderRadius: '3px' }}>
                  <div style={{ height: '100%', borderRadius: '3px', width: `${(t.count / max) * 100}%`, background: '#7C3AED' }} />
                </div>
                <span style={{ fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary, minWidth: '32px', textAlign: 'right' }}>{t.count}</span>
              </div>
            ))}
          </div>
        </div>
      );
    }
    if (sub === 'stale') {
      return (
        <div style={dcCard}>
          <div style={dcCardH}><span>Stale documents — {stale.length}</span><button style={dcBtn('warn')}>Bulk archive</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={dcTh}>Document</th><th style={dcTh}>Matter</th><th style={dcTh}>Last Opened</th><th style={dcTh}>Days Stale</th><th style={dcTh}>Size</th><th style={dcTh}>Recommendation</th></tr></thead>
            <tbody>
              {stale.map(d => (
                <tr key={d.docId}>
                  <td style={{ ...dcTd, fontWeight: 600 }}>{d.name}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{d.matter}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{d.lastOpened}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right', color: d.daysStale > 300 ? '#B91C1C' : '#B45309', fontWeight: 700 }}>{d.daysStale}</td>
                  <td style={{ ...dcTd, fontFamily: Tdch.font.mono, textAlign: 'right' }}>{d.size}</td>
                  <td style={{ ...dcTd, color: Tdch.color.text.secondary, fontSize: '11px' }}>{d.recommendation}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    const maxGb = Math.max(1, ...cost.map(r => r.gb));
    const totalCost = cost.reduce((sum, r) => sum + r.costMo, 0);
    return (
      <div style={dcCard}>
        <div style={dcCardH}><span>Storage cost by matter</span><span style={{ fontSize: '11px', fontFamily: Tdch.font.mono, color: Tdch.color.text.tertiary }}>${totalCost.toFixed(2)} / month</span></div>
        <div style={{ padding: '14px 16px' }}>
          {cost.map(r => (
            <div key={r.matter} style={{ display: 'grid', gridTemplateColumns: '200px 1fr 80px 70px', gap: '10px', alignItems: 'center', padding: '8px 0', borderBottom: `1px solid ${Tdch.color.border.light}`, fontSize: '11px' }}>
              <span style={{ fontWeight: 600, color: Tdch.color.text.primary }}>{r.matter}</span>
              <div style={{ height: '8px', background: Tdch.color.border.light, borderRadius: '4px' }}>
                <div style={{ height: '100%', borderRadius: '4px', width: `${(r.gb / maxGb) * 100}%`, background: '#059669' }} />
              </div>
              <span style={{ fontFamily: Tdch.font.mono, textAlign: 'right', color: Tdch.color.text.tertiary }}>{r.gb} GB</span>
              <span style={{ fontFamily: Tdch.font.mono, textAlign: 'right', color: Tdch.color.text.primary, fontWeight: 700 }}>${r.costMo.toFixed(2)}</span>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (<div><DcSubNav views={views} active={sub} onChange={setSub} />{body()}</div>);
}
window.DcAnalyticsHub = DcAnalyticsHub;

// ── TRASH HUB (#7) ─────────────────────────────────────────────────────────
function DcTrashHub() {
  const s = _useStore(['doc.deleted','doc.restored','doc.purged']);
  const trash = s.trash || [];

  if (trash.length === 0) {
    return <div style={{ ...dcCard, padding: '40px', textAlign: 'center', color: Tdch.color.text.tertiary }}>Trash is empty.</div>;
  }

  return (
    <div style={dcCard}>
      <div style={dcCardH}>
        <span>Trash — {trash.length} item(s) · auto-purge after 30 days</span>
        <span style={{ fontSize: '11px', color: Tdch.color.text.tertiary }}>Items under legal hold cannot be deleted</span>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead><tr><th style={dcTh}>Name</th><th style={dcTh}>Matter</th><th style={dcTh}>Deleted by</th><th style={dcTh}>Deleted at</th><th style={dcTh}>Purge at</th><th style={dcTh}>Reason</th><th style={dcTh}>Actions</th></tr></thead>
        <tbody>
          {trash.map(t => (
            <tr key={t.id}>
              <td style={{ ...dcTd, fontWeight: 600 }}>
                <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: 'rgba(107,114,128,0.15)', color: '#6B7280', marginRight: '6px' }}>{t.ext}</span>
                {t.name}
              </td>
              <td style={{ ...dcTd, color: Tdch.color.text.secondary }}>{t.matter}</td>
              <td style={dcTd}>{t.deletedBy}</td>
              <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px' }}>{t.deletedAt}</td>
              <td style={{ ...dcTd, fontFamily: Tdch.font.mono, fontSize: '11px', color: '#B45309' }}>{t.purgeAt}</td>
              <td style={{ ...dcTd, color: Tdch.color.text.tertiary, fontSize: '11px' }}>{t.reason}</td>
              <td style={dcTd}>
                <div style={{ display: 'flex', gap: '4px' }}>
                  <button onClick={() => window.DocStore.restoreFromTrash(t.id)} style={dcBtn('success')}>Restore</button>
                  <button onClick={() => { if (confirm('Permanently purge? This cannot be undone.')) window.DocStore.purgeFromTrash(t.id); }} style={dcBtn('danger')}>Purge</button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
window.DcTrashHub = DcTrashHub;
