// ═══════════════════════════════════════════════════════════════
// MODULE DOCUMENTS — Partage hiérarchique de PDFs
// ═══════════════════════════════════════════════════════════════

const Documents = ({ user, etablissement }) => {
  const etabId = etablissement?.id || 'etab-1';
  const [allDocs, setAllDocs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [currentFolder, setCurrentFolder] = React.useState(null); // id du dossier courant, null = racine
  const [search, setSearch] = React.useState('');
  const [uploading, setUploading] = React.useState(false);
  const [showNewFolder, setShowNewFolder] = React.useState(false);
  const [newFolderName, setNewFolderName] = React.useState('');
  const [renaming, setRenaming] = React.useState(null); // { id, currentName, newName }
  const fileInputRef = React.useRef(null);

  const perms = DEMO_DATA.permissions[user.role] || {};
  const canWrite = perms.documents !== false && ['consultant', 'patron', 'resp_cuisine'].includes(user.role);
  const canRead = perms.documents !== false;

  // ═══ Load + Realtime ═══
  React.useEffect(() => {
    if (!window.SB) { setLoading(false); return; }
    let unsub = null, mounted = true;

    (async () => {
      try {
        const docs = await window.SB.db.listDocuments(etabId);
        if (mounted) setAllDocs(docs);
      } catch (err) { console.error('[Documents load]', err); }
      finally { if (mounted) setLoading(false); }
    })();

    unsub = window.SB.realtime.subscribe('documents', async () => {
      try { const docs = await window.SB.db.listDocuments(etabId); if (mounted) setAllDocs(docs); } catch(e) {}
    });

    return () => { mounted = false; unsub && unsub(); };
  }, [etabId]);

  // Filtrer les documents du dossier courant
  const docsInFolder = allDocs.filter(d =>
    (d.parentId || null) === currentFolder &&
    (search === '' || d.nom.toLowerCase().includes(search.toLowerCase()))
  );
  const folders = docsInFolder.filter(d => d.type === 'folder');
  const files = docsInFolder.filter(d => d.type === 'file');

  // Breadcrumb : remonter jusqu'à la racine
  const breadcrumb = React.useMemo(() => {
    const path = [];
    let id = currentFolder;
    const safety = 20;
    let n = 0;
    while (id && n < safety) {
      const f = allDocs.find(d => d.id === id);
      if (!f) break;
      path.unshift(f);
      id = f.parentId;
      n++;
    }
    return path;
  }, [currentFolder, allDocs]);

  // ═══ Actions ═══
  const createFolder = async () => {
    if (!newFolderName.trim()) return;
    if (!window.SB) { alert('Supabase non configuré.'); return; }
    try {
      await window.SB.db.createFolder({
        etablissementId: etabId,
        parentId: currentFolder,
        nom: newFolderName.trim(),
        userId: user.id,
      });
      setNewFolderName('');
      setShowNewFolder(false);
    } catch (err) {
      alert('Erreur création dossier : ' + err.message);
    }
  };

  const handleFileUpload = async (e) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;
    if (!window.SB) { alert('Supabase non configuré.'); return; }

    setUploading(true);
    let success = 0, failed = 0;
    for (const file of files) {
      if (!file.type.includes('pdf') && !file.name.toLowerCase().endsWith('.pdf')) {
        alert(`"${file.name}" n'est pas un PDF et sera ignoré.`);
        failed++;
        continue;
      }
      if (file.size > 50 * 1024 * 1024) {
        alert(`"${file.name}" dépasse 50 Mo. Ignoré.`);
        failed++;
        continue;
      }
      try {
        await window.SB.db.uploadFile({
          etablissementId: etabId,
          parentId: currentFolder,
          file,
          userId: user.id,
        });
        success++;
      } catch (err) {
        console.error('[upload]', err);
        alert(`Erreur upload "${file.name}" : ${err.message}`);
        failed++;
      }
    }
    setUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = '';
    if (success > 0 && failed === 0) {
      // silencieux
    } else if (success > 0 && failed > 0) {
      alert(`${success} fichier(s) uploadé(s), ${failed} échec(s).`);
    }
  };

  const openFile = async (doc) => {
    if (!window.SB) return;
    try {
      const url = await window.SB.db.getFileURL(doc.storagePath);
      window.open(url, '_blank');
    } catch (err) {
      alert('Erreur ouverture fichier : ' + err.message);
    }
  };

  const downloadFile = async (doc) => {
    if (!window.SB) return;
    try {
      const url = await window.SB.db.getFileURL(doc.storagePath);
      const a = document.createElement('a');
      a.href = url;
      a.download = doc.nom;
      a.click();
    } catch (err) {
      alert('Erreur téléchargement : ' + err.message);
    }
  };

  const deleteDoc = async (doc) => {
    const msg = doc.type === 'folder'
      ? `Supprimer le dossier "${doc.nom}" et TOUT son contenu ?\n\nCette action est irréversible.`
      : `Supprimer le fichier "${doc.nom}" ?`;
    if (!window.confirm(msg)) return;
    try {
      await window.SB.db.deleteDocument(doc);
    } catch (err) {
      alert('Erreur suppression : ' + err.message);
    }
  };

  const startRename = (doc) => setRenaming({ id: doc.id, currentName: doc.nom, newName: doc.nom });
  const confirmRename = async () => {
    if (!renaming || !renaming.newName.trim() || renaming.newName === renaming.currentName) {
      setRenaming(null);
      return;
    }
    try {
      await window.SB.db.renameDocument(renaming.id, renaming.newName.trim());
      setRenaming(null);
    } catch (err) {
      alert('Erreur renommage : ' + err.message);
    }
  };

  const formatSize = (bytes) => {
    if (!bytes) return '';
    if (bytes < 1024) return bytes + ' o';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + ' Ko';
    return (bytes / 1024 / 1024).toFixed(1) + ' Mo';
  };

  const formatDate = (ts) => {
    if (!ts) return '';
    return new Date(ts).toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', year: 'numeric' });
  };

  if (!canRead) {
    return (
      <div style={{ padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 40 }}>🔐</div>
        <div style={{ fontSize: 16, fontWeight: 700, marginTop: 10 }}>Accès restreint</div>
      </div>
    );
  }

  return (
    <div style={ds.root}>
      {/* Header */}
      <div style={ds.header}>
        <div style={ds.breadcrumb}>
          <button style={ds.crumbBtn} onClick={() => setCurrentFolder(null)}>📁 Documents</button>
          {breadcrumb.map((f, i) => (
            <React.Fragment key={f.id}>
              <span style={ds.crumbSep}>/</span>
              <button style={ds.crumbBtn} onClick={() => setCurrentFolder(f.id)}>{f.nom}</button>
            </React.Fragment>
          ))}
        </div>

        <div style={ds.headerRight}>
          <input
            style={ds.search}
            placeholder="🔍 Rechercher…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          {canWrite && (
            <>
              <button style={ds.ghostBtn} onClick={() => setShowNewFolder(true)}>📁 Nouveau dossier</button>
              <label style={{ ...ds.addBtn, cursor: uploading ? 'wait' : 'pointer' }}>
                {uploading ? '⏳ Upload…' : '📤 Importer PDF'}
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="application/pdf,.pdf"
                  multiple
                  style={{ display: 'none' }}
                  onChange={handleFileUpload}
                  disabled={uploading}
                />
              </label>
            </>
          )}
        </div>
      </div>

      {/* Contenu */}
      {loading ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--text2)' }}>Chargement…</div>
      ) : docsInFolder.length === 0 ? (
        <div style={ds.empty}>
          <div style={{ fontSize: 48, opacity: 0.3 }}>📂</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginTop: 10, color: 'var(--text)' }}>
            {search ? 'Aucun résultat' : (currentFolder ? 'Ce dossier est vide' : 'Aucun document')}
          </div>
          {canWrite && !search && (
            <div style={{ fontSize: 13, color: 'var(--text2)', marginTop: 6 }}>
              Créez un dossier ou importez des PDFs pour commencer.
            </div>
          )}
        </div>
      ) : (
        <div style={ds.grid}>
          {/* Dossiers */}
          {folders.map(f => (
            <div
              key={f.id}
              style={ds.itemCard}
              onClick={() => setCurrentFolder(f.id)}
              onDoubleClick={() => setCurrentFolder(f.id)}
            >
              <div style={{ fontSize: 42, textAlign: 'center' }}>📁</div>
              {renaming?.id === f.id ? (
                <input
                  autoFocus
                  style={ds.renameInput}
                  value={renaming.newName}
                  onClick={e => e.stopPropagation()}
                  onChange={e => setRenaming({ ...renaming, newName: e.target.value })}
                  onKeyDown={e => { if (e.key === 'Enter') confirmRename(); if (e.key === 'Escape') setRenaming(null); }}
                  onBlur={confirmRename}
                />
              ) : (
                <div style={ds.itemName}>{f.nom}</div>
              )}
              <div style={ds.itemMeta}>{formatDate(f.createdAt)}</div>
              {canWrite && (
                <div style={ds.itemActions} className="no-print">
                  <button style={ds.miniBtn} onClick={(e) => { e.stopPropagation(); startRename(f); }} title="Renommer">✎</button>
                  <button style={{ ...ds.miniBtn, color: '#dc2626' }} onClick={(e) => { e.stopPropagation(); deleteDoc(f); }} title="Supprimer">🗑</button>
                </div>
              )}
            </div>
          ))}
          {/* Fichiers */}
          {files.map(f => (
            <div
              key={f.id}
              style={ds.itemCard}
              onClick={() => openFile(f)}
              onDoubleClick={() => openFile(f)}
              title="Cliquer pour ouvrir"
            >
              <div style={{ fontSize: 42, textAlign: 'center' }}>📄</div>
              {renaming?.id === f.id ? (
                <input
                  autoFocus
                  style={ds.renameInput}
                  value={renaming.newName}
                  onClick={e => e.stopPropagation()}
                  onChange={e => setRenaming({ ...renaming, newName: e.target.value })}
                  onKeyDown={e => { if (e.key === 'Enter') confirmRename(); if (e.key === 'Escape') setRenaming(null); }}
                  onBlur={confirmRename}
                />
              ) : (
                <div style={ds.itemName} title={f.nom}>{f.nom}</div>
              )}
              <div style={ds.itemMeta}>{formatSize(f.taille)} · {formatDate(f.createdAt)}</div>
              <div style={ds.itemActions} className="no-print">
                <button style={ds.miniBtn} onClick={(e) => { e.stopPropagation(); downloadFile(f); }} title="Télécharger">⬇</button>
                {canWrite && <button style={ds.miniBtn} onClick={(e) => { e.stopPropagation(); startRename(f); }} title="Renommer">✎</button>}
                {canWrite && <button style={{ ...ds.miniBtn, color: '#dc2626' }} onClick={(e) => { e.stopPropagation(); deleteDoc(f); }} title="Supprimer">🗑</button>}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal nouveau dossier */}
      {showNewFolder && (
        <div style={ds.overlay} onClick={() => setShowNewFolder(false)}>
          <div style={ds.modal} onClick={e => e.stopPropagation()}>
            <div style={ds.modalHeader}>
              <div style={{ fontWeight: 700, fontSize: 16, fontFamily: 'var(--font-serif)' }}>Nouveau dossier</div>
              <button style={ds.closeBtn} onClick={() => setShowNewFolder(false)}>✕</button>
            </div>
            <div style={{ padding: 22 }}>
              <label style={ds.fieldLabel}>Nom du dossier</label>
              <input
                autoFocus
                style={ds.fieldInput}
                value={newFolderName}
                onChange={e => setNewFolderName(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') createFolder(); }}
                placeholder="Ex: Contrats, Fiches techniques…"
              />
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
                <button style={ds.ghostBtn} onClick={() => setShowNewFolder(false)}>Annuler</button>
                <button style={ds.addBtn} onClick={createFolder}>Créer</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const ds = {
  root: { display: 'flex', flexDirection: 'column', gap: 16 },
  header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' },
  breadcrumb: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
  crumbBtn: { background: 'none', border: 'none', color: 'var(--accent)', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font)', padding: '4px 6px', borderRadius: 4 },
  crumbSep: { color: 'var(--text2)', fontSize: 14 },
  headerRight: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' },
  search: { padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 8, fontSize: 13, background: 'var(--surface)', color: 'var(--text)', fontFamily: 'var(--font)', width: 220 },
  addBtn: { padding: '8px 16px', background: 'var(--accent)', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font)' },
  ghostBtn: { padding: '8px 14px', background: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font)' },

  grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 },
  itemCard: {
    background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 10,
    padding: '16px 12px', cursor: 'pointer', position: 'relative', transition: 'box-shadow 0.15s, transform 0.15s',
  },
  itemName: { fontSize: 13, fontWeight: 600, textAlign: 'center', marginTop: 6, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  itemMeta: { fontSize: 10, color: 'var(--text2)', textAlign: 'center', marginTop: 4 },
  itemActions: { position: 'absolute', top: 6, right: 6, display: 'flex', gap: 2 },
  miniBtn: { width: 24, height: 24, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(255,255,255,0.9)', border: '1px solid var(--border)', borderRadius: 4, cursor: 'pointer', fontSize: 12, padding: 0, color: 'var(--text2)' },

  renameInput: { width: '100%', marginTop: 6, padding: '4px 6px', fontSize: 12, fontWeight: 600, textAlign: 'center', border: '1px solid var(--accent)', borderRadius: 4, fontFamily: 'var(--font)', background: 'var(--bg)', color: 'var(--text)', boxSizing: 'border-box' },

  empty: { padding: 60, textAlign: 'center', background: 'var(--surface)', border: '1px dashed var(--border)', borderRadius: 12 },

  overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 },
  modal: { background: 'var(--surface)', borderRadius: 12, width: 420, maxWidth: '90%' },
  modalHeader: { padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  closeBtn: { background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: 'var(--text2)' },
  fieldLabel: { display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--text2)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 },
  fieldInput: { width: '100%', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 8, fontSize: 14, color: 'var(--text)', background: 'var(--bg)', fontFamily: 'var(--font)', boxSizing: 'border-box' },
};

Object.assign(window, { Documents });
