// DocumentsScreen.jsx — AegisComply Document Management (Supabase Storage)

const DOC_CATEGORIES = [
  { id: 'policy',    label: 'Policy',           color: '#0D9488', bg: '#F0FDFA' },
  { id: 'procedure', label: 'Procedure / SOP',  color: '#2563EB', bg: '#EFF6FF' },
  { id: 'cert',      label: 'Certificate',      color: '#16A34A', bg: '#F0FDF4' },
  { id: 'audit',     label: 'Audit Report',     color: '#9333EA', bg: '#FAF5FF' },
  { id: 'manual',    label: 'Manual',           color: '#0EA5E9', bg: '#F0F9FF' },
  { id: 'sds',       label: 'SDS / MSDS',       color: '#DC2626', bg: '#FFF5F5' },
  { id: 'training',  label: 'Training',         color: '#D97706', bg: '#FFFBEB' },
  { id: 'other',     label: 'Other',            color: '#64748B', bg: '#F1F5F9' },
];

const MAX_FILE_MB = 25;

const docStyles = {
  page: { padding: 24 },
  toolbar: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20, flexWrap: 'wrap' },
  searchWrap: { position: 'relative', flex: 1, maxWidth: 320 },
  searchInput: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 12px 0 36px', fontFamily: "'DM Sans', sans-serif", fontSize: 13, color: '#334155', outline: 'none', background: 'white' },
  searchIcon: { position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: '#94A3B8', pointerEvents: 'none' },
  select: { height: 36, padding: '0 28px 0 12px', border: '1px solid #CBD5E1', borderRadius: 6, background: 'white', fontSize: 13, fontWeight: 500, color: '#475569', cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", outline: 'none', appearance: 'none', backgroundImage: 'url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%2364748B\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3e%3cpolyline points=\'6 9 12 15 18 9\'%3e%3c/polyline%3e%3c/svg%3e")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center' },
  uploadBtn: { height: 36, padding: '0 16px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 600, color: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'DM Sans', sans-serif", marginLeft: 'auto' },
  uploadBtnDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
  grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 14 },
  card: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: 16, boxShadow: '0 1px 3px rgba(0,0,0,0.06)', cursor: 'pointer', transition: 'all 150ms', position: 'relative' },
  cardHover: { boxShadow: '0 4px 12px rgba(0,0,0,0.08)', transform: 'translateY(-1px)' },
  fileIcon: { width: 44, height: 44, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 },
  fileName: { fontSize: 13, fontWeight: 600, color: '#0F172A', marginBottom: 4, lineHeight: 1.35, wordBreak: 'break-word' },
  fileMeta: { fontSize: 11, color: '#94A3B8' },
  catBadge: { display: 'inline-flex', padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 10 },
  cardActions: { display: 'flex', gap: 6, marginTop: 12, paddingTop: 10, borderTop: '1px solid #F1F5F9' },
  actionBtn: { flex: 1, height: 28, padding: '0 8px', borderRadius: 5, border: '1px solid #CBD5E1', background: 'white', fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", color: '#334155' },
  actionDanger: { borderColor: '#FECACA', color: '#DC2626', flex: 0, padding: '0 10px' },
  tagsRow: { display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 6 },
  tag: { fontSize: 9, padding: '1px 6px', borderRadius: 3, background: '#F1F5F9', color: '#475569', fontWeight: 500 },
  empty: { padding: 60, textAlign: 'center', border: '2px dashed #E2E8F0', borderRadius: 12, background: 'white' },
  emptyIcon: { width: 60, height: 60, borderRadius: 12, background: '#F1F5F9', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 },
  emptyTitle: { fontSize: 16, fontWeight: 700, color: '#334155', marginBottom: 6 },
  emptySub: { fontSize: 13, color: '#94A3B8', marginBottom: 18 },
  // Modal
  overlay: { position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 },
  modal: { background: 'white', borderRadius: 12, width: '100%', maxWidth: 520, maxHeight: '90vh', display: 'flex', flexDirection: 'column', boxShadow: '0 16px 48px rgba(0,0,0,0.18)' },
  modalHeader: { padding: '18px 24px', borderBottom: '1px solid #E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  modalTitle: { fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 16, fontWeight: 700, color: '#0F172A' },
  modalClose: { width: 30, height: 30, borderRadius: 6, border: 'none', background: '#F1F5F9', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#64748B' },
  modalBody: { padding: '20px 24px', overflowY: 'auto', flex: 1 },
  modalFooter: { padding: '14px 24px', borderTop: '1px solid #E2E8F0', display: 'flex', gap: 10, justifyContent: 'flex-end', background: '#F8FAFC' },
  field: { marginBottom: 14 },
  fieldRow: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  label: { fontSize: 12, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 5 },
  required: { color: '#DC2626', marginLeft: 2 },
  input: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', boxSizing: 'border-box' },
  textarea: { width: '100%', minHeight: 60, border: '1px solid #CBD5E1', borderRadius: 6, padding: '8px 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', resize: 'vertical', boxSizing: 'border-box' },
  selectInput: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 28px 0 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', appearance: 'none', backgroundImage: 'url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%2364748B\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3e%3cpolyline points=\'6 9 12 15 18 9\'%3e%3c/polyline%3e%3c/svg%3e")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center', boxSizing: 'border-box' },
  fileDrop: { border: '2px dashed #CBD5E1', borderRadius: 8, padding: '28px 16px', textAlign: 'center', cursor: 'pointer', transition: 'all 150ms' },
  fileDropActive: { borderColor: '#0D9488', background: '#F0FDFA' },
  btnPrimary: { height: 38, padding: '0 18px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  btnPrimaryDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
  btnSecondary: { height: 38, padding: '0 18px', border: '1px solid #CBD5E1', borderRadius: 6, background: 'white', fontSize: 13, fontWeight: 600, color: '#64748B', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  btnDanger: { height: 38, padding: '0 18px', border: 'none', borderRadius: 6, background: '#DC2626', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  errorBox: { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 },
  progress: { height: 6, background: '#F1F5F9', borderRadius: 3, overflow: 'hidden', marginTop: 8 },
  progressFill: { height: '100%', background: '#0D9488', transition: 'width 200ms' },
};

function formatBytes(bytes) {
  if (!bytes) return '—';
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

function getCategoryStyle(catId) {
  return DOC_CATEGORIES.find(c => c.id === catId) || DOC_CATEGORIES[DOC_CATEGORIES.length - 1];
}

function iconForMime(mime) {
  const m = (mime || '').toLowerCase();
  if (m.includes('pdf'))   return { bg: '#FFF5F5', color: '#DC2626', label: 'PDF' };
  if (m.includes('word') || m.includes('docx') || m.includes('msword'))    return { bg: '#EFF6FF', color: '#2563EB', label: 'DOC' };
  if (m.includes('sheet') || m.includes('excel') || m.includes('xlsx'))    return { bg: '#F0FDF4', color: '#16A34A', label: 'XLS' };
  if (m.includes('image'))  return { bg: '#FAF5FF', color: '#9333EA', label: 'IMG' };
  if (m.includes('zip') || m.includes('compress'))    return { bg: '#FFFBEB', color: '#D97706', label: 'ZIP' };
  return { bg: '#F1F5F9', color: '#475569', label: 'FILE' };
}

function fmtDocDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return d; }
}

// ── Upload / Edit Modal ─────────────────────────────────────────────────────
function DocumentFormModal({ initial, user, onClose, onSaved }) {
  const isEdit = !!initial?.id;
  const [form, setForm] = React.useState({
    name:        initial?.name || '',
    category:    initial?.category || 'other',
    description: initial?.description || '',
    tags:        (initial?.tags || []).join(', '),
  });
  const [file, setFile]       = React.useState(null);
  const [dragOver, setDragOver] = React.useState(false);
  const [saving, setSaving]   = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [error, setError]     = React.useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleFile = (f) => {
    if (!f) return;
    if (f.size > MAX_FILE_MB * 1024 * 1024) {
      setError(`File too large (max ${MAX_FILE_MB} MB).`);
      return;
    }
    setFile(f);
    setError('');
    // Auto-fill name if empty
    if (!form.name) set('name', f.name.replace(/\.[^/.]+$/, ''));
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    handleFile(e.dataTransfer.files?.[0]);
  };

  const valid = (isEdit || file) && form.name.trim() && form.category;

  const handleSubmit = async () => {
    setError('');
    if (!valid) { setError('File and name are required.'); return; }
    setSaving(true);
    setProgress(0);
    try {
      const sb = window.supabaseClient;
      const tags = form.tags.split(',').map(t => t.trim()).filter(Boolean);

      if (isEdit) {
        // Edit metadata only (no file change)
        const { error: upErr } = await sb.from('documents').update({
          name:        form.name.trim(),
          category:    form.category,
          description: form.description || null,
          tags:        tags.length ? tags : null,
        }).eq('id', initial.id);
        if (upErr) throw upErr;
        setSaving(false);
        onSaved();
        return;
      }

      // New upload
      const ext = file.name.split('.').pop() || 'bin';
      const path = `${user.id}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;

      setProgress(20);
      const { error: upErr } = await sb.storage.from('documents').upload(path, file, {
        cacheControl: '3600',
        upsert: false,
        contentType: file.type || 'application/octet-stream',
      });
      if (upErr) throw upErr;
      setProgress(70);

      const { error: insErr } = await sb.from('documents').insert({
        user_id:     user.id,
        name:        form.name.trim(),
        category:    form.category,
        description: form.description || null,
        file_path:   path,
        file_size:   file.size,
        mime_type:   file.type || 'application/octet-stream',
        tags:        tags.length ? tags : null,
      });
      if (insErr) {
        // Rollback storage upload if DB insert failed
        await sb.storage.from('documents').remove([path]);
        throw insErr;
      }
      setProgress(100);
      setTimeout(() => onSaved(), 300);
    } catch (err) {
      console.error('[Documents] save error:', err);
      setError(err.message || 'Upload failed.');
      setSaving(false);
    }
  };

  return (
    <div style={docStyles.overlay} onClick={saving ? undefined : onClose}>
      <div style={docStyles.modal} onClick={e => e.stopPropagation()}>
        <div style={docStyles.modalHeader}>
          <div style={docStyles.modalTitle}>{isEdit ? 'Edit Document' : 'Upload Document'}</div>
          <button style={docStyles.modalClose} onClick={onClose} disabled={saving}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div style={docStyles.modalBody}>
          {error && <div style={docStyles.errorBox}>{error}</div>}

          {!isEdit && (
            <div style={docStyles.field}>
              <label style={docStyles.label}>File<span style={docStyles.required}>*</span></label>
              <label
                style={{ ...docStyles.fileDrop, ...(dragOver ? docStyles.fileDropActive : {}) }}
                onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                onDragLeave={() => setDragOver(false)}
                onDrop={handleDrop}
              >
                <input type="file" style={{ display: 'none' }} onChange={e => handleFile(e.target.files?.[0])}/>
                {file ? (
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A', marginBottom: 4 }}>{file.name}</div>
                    <div style={{ fontSize: 11, color: '#94A3B8' }}>{formatBytes(file.size)} · click to change</div>
                  </div>
                ) : (
                  <div>
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#94A3B8" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: 8 }}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                    <div style={{ fontSize: 13, color: '#475569', fontWeight: 500 }}>Click or drag a file here</div>
                    <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 4 }}>PDF, Word, Excel, image — max {MAX_FILE_MB} MB</div>
                  </div>
                )}
              </label>
            </div>
          )}

          <div style={docStyles.field}>
            <label style={docStyles.label}>Document Name<span style={docStyles.required}>*</span></label>
            <input style={docStyles.input} placeholder="e.g. PPE Issuance Policy 2026" value={form.name} onChange={e => set('name', e.target.value)}/>
          </div>

          <div style={docStyles.field}>
            <label style={docStyles.label}>Category</label>
            <select style={docStyles.selectInput} value={form.category} onChange={e => set('category', e.target.value)}>
              {DOC_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </select>
          </div>

          <div style={docStyles.field}>
            <label style={docStyles.label}>Description</label>
            <textarea style={docStyles.textarea} placeholder="What is this document for? Who needs it?" value={form.description} onChange={e => set('description', e.target.value)}/>
          </div>

          <div style={docStyles.field}>
            <label style={docStyles.label}>Tags <span style={{ fontWeight: 400, color: '#94A3B8' }}>(comma-separated)</span></label>
            <input style={docStyles.input} placeholder="e.g. iso, audit-2026, hse" value={form.tags} onChange={e => set('tags', e.target.value)}/>
          </div>

          {saving && progress > 0 && (
            <div style={docStyles.progress}>
              <div style={{ ...docStyles.progressFill, width: `${progress}%` }}/>
            </div>
          )}
        </div>
        <div style={docStyles.modalFooter}>
          <button style={docStyles.btnSecondary} onClick={onClose} disabled={saving}>Cancel</button>
          <button
            style={{ ...docStyles.btnPrimary, ...((!valid || saving) ? docStyles.btnPrimaryDisabled : {}) }}
            onClick={handleSubmit}
            disabled={!valid || saving}
          >
            {saving ? (isEdit ? 'Saving…' : 'Uploading…') : (isEdit ? 'Save Changes' : 'Upload Document')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Delete Confirm Modal ────────────────────────────────────────────────────
function DocDeleteModal({ doc, onConfirm, onCancel, busy }) {
  return (
    <div style={docStyles.overlay} onClick={!busy ? onCancel : undefined}>
      <div style={{ ...docStyles.modal, maxWidth: 420 }} onClick={e => e.stopPropagation()}>
        <div style={docStyles.modalHeader}>
          <div style={docStyles.modalTitle}>Delete Document?</div>
        </div>
        <div style={docStyles.modalBody}>
          <div style={{ fontSize: 13, color: '#475569', lineHeight: 1.6 }}>
            Are you sure you want to delete <strong>{doc.name}</strong>?
            <br/><br/>
            The file will be permanently removed from storage. This cannot be undone.
          </div>
        </div>
        <div style={docStyles.modalFooter}>
          <button style={docStyles.btnSecondary} onClick={onCancel} disabled={busy}>Cancel</button>
          <button style={docStyles.btnDanger} onClick={onConfirm} disabled={busy}>
            {busy ? 'Deleting…' : 'Delete'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Main Documents Screen ───────────────────────────────────────────────────
function DocumentsScreen({ user, isFrozen }) {
  const [docs, setDocs]           = React.useState([]);
  const [loading, setLoading]     = React.useState(false);
  const [error, setError]         = React.useState('');
  const [search, setSearch]       = React.useState('');
  const [categoryFilter, setCategoryFilter] = React.useState('all');
  const [hovered, setHovered]     = React.useState(null);
  const [editing, setEditing]     = React.useState(null); // null | 'new' | doc
  const [deleting, setDeleting]   = React.useState(null);
  const [deleteBusy, setDeleteBusy] = React.useState(false);

  const fetchDocs = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const sb = window.supabaseClient;
      let q = sb.from('documents').select('*').order('created_at', { ascending: false });
      if (categoryFilter !== 'all') q = q.eq('category', categoryFilter);
      if (search.trim()) {
        const t = search.trim();
        q = q.or(`name.ilike.%${t}%,description.ilike.%${t}%`);
      }
      const { data, error: qErr } = await q;
      if (qErr) throw qErr;
      setDocs(data || []);
    } catch (err) {
      console.error('[Documents] fetch error:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [search, categoryFilter]);

  React.useEffect(() => { fetchDocs(); }, [fetchDocs]);

  // Realtime
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`docs-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'documents', filter: `user_id=eq.${user.id}` }, () => fetchDocs())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchDocs]);

  const handleDownload = async (doc) => {
    try {
      const sb = window.supabaseClient;
      const { data, error: urlErr } = await sb.storage.from('documents').createSignedUrl(doc.file_path, 60);
      if (urlErr) throw urlErr;
      window.open(data.signedUrl, '_blank');
    } catch (err) {
      alert('Download failed: ' + err.message);
    }
  };

  const handleDelete = async () => {
    if (!deleting) return;
    setDeleteBusy(true);
    try {
      const sb = window.supabaseClient;
      // Try delete the file first; ignore failure (file might be gone already)
      try { await sb.storage.from('documents').remove([deleting.file_path]); } catch (e) {}
      const { error: delErr } = await sb.from('documents').delete().eq('id', deleting.id);
      if (delErr) throw delErr;
      setDeleting(null);
    } catch (err) {
      alert('Delete failed: ' + err.message);
    } finally {
      setDeleteBusy(false);
    }
  };

  return (
    <div style={docStyles.page}>
      <div style={docStyles.toolbar}>
        <div style={docStyles.searchWrap}>
          <svg style={docStyles.searchIcon} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input
            style={docStyles.searchInput}
            placeholder="Search by name or description…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
        <select style={docStyles.select} value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)}>
          <option value="all">All Categories</option>
          {DOC_CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
        </select>
        <button
          style={{ ...docStyles.uploadBtn, ...(isFrozen ? docStyles.uploadBtnDisabled : {}) }}
          onClick={() => !isFrozen && setEditing('new')}
          disabled={isFrozen}
        >
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
          Upload Document
        </button>
      </div>

      {error && <div style={docStyles.errorBox}>{error}</div>}

      {loading && docs.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8' }}>Loading documents…</div>
      ) : docs.length === 0 ? (
        <div style={docStyles.empty}>
          <div style={docStyles.emptyIcon}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#94A3B8" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
          </div>
          <div style={docStyles.emptyTitle}>
            {search || categoryFilter !== 'all' ? 'No documents match your filters' : 'No documents yet'}
          </div>
          <div style={docStyles.emptySub}>
            {search || categoryFilter !== 'all' ? 'Try clearing the filters above.' : 'Upload policies, procedures, certificates, SDS sheets, audit reports, manuals — all in one place.'}
          </div>
          {!search && categoryFilter === 'all' && !isFrozen && (
            <button style={docStyles.uploadBtn} onClick={() => setEditing('new')}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
              Upload your first document
            </button>
          )}
        </div>
      ) : (
        <div style={docStyles.grid}>
          {docs.map((d, i) => {
            const cat   = getCategoryStyle(d.category);
            const fIcon = iconForMime(d.mime_type);
            return (
              <div
                key={d.id}
                style={{ ...docStyles.card, ...(hovered === i ? docStyles.cardHover : {}) }}
                onMouseEnter={() => setHovered(i)}
                onMouseLeave={() => setHovered(null)}
                onClick={() => handleDownload(d)}
              >
                <div style={{ ...docStyles.fileIcon, background: fIcon.bg, color: fIcon.color }}>
                  <span style={{ fontWeight: 700, fontSize: 13, letterSpacing: '0.04em' }}>{fIcon.label}</span>
                </div>
                <span style={{ ...docStyles.catBadge, background: cat.bg, color: cat.color }}>{cat.label}</span>
                <div style={docStyles.fileName}>{d.name}</div>
                <div style={docStyles.fileMeta}>
                  {formatBytes(d.file_size)} · {fmtDocDate(d.created_at)}
                </div>
                {d.description && (
                  <div style={{ fontSize: 11, color: '#64748B', marginTop: 6, lineHeight: 1.5, maxHeight: 32, overflow: 'hidden' }}>
                    {d.description}
                  </div>
                )}
                {d.tags && d.tags.length > 0 && (
                  <div style={docStyles.tagsRow}>
                    {d.tags.map((t, j) => <span key={j} style={docStyles.tag}>{t}</span>)}
                  </div>
                )}
                <div style={docStyles.cardActions} onClick={e => e.stopPropagation()}>
                  <button style={docStyles.actionBtn} onClick={() => handleDownload(d)}>Download</button>
                  <button style={docStyles.actionBtn} onClick={() => !isFrozen && setEditing(d)} disabled={isFrozen}>Edit</button>
                  <button style={{ ...docStyles.actionBtn, ...docStyles.actionDanger }} onClick={() => !isFrozen && setDeleting(d)} disabled={isFrozen} title="Delete">
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L5 6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {editing && (
        <DocumentFormModal
          initial={editing === 'new' ? null : editing}
          user={user}
          onClose={() => setEditing(null)}
          onSaved={() => { setEditing(null); fetchDocs(); }}
        />
      )}
      {deleting && (
        <DocDeleteModal
          doc={deleting}
          busy={deleteBusy}
          onCancel={() => !deleteBusy && setDeleting(null)}
          onConfirm={handleDelete}
        />
      )}
    </div>
  );
}

Object.assign(window, { DocumentsScreen });
