/* ── DiagnosticArchiveModal.jsx — Rangement d'un envoi de diagnostics ──────────
   Une notification « diagnostic » regroupe TOUTES les PJ d'un email de
   diagnostiqueur (metadata.diagnostic_attachments). Cette modale permet de :
   - choisir/confirmer le PROGRAMME concerné,
   - choisir/confirmer/créer le dossier « Diag » OneDrive du programme,
   - cocher/décocher les fichiers à ranger (par défaut tous cochés),
   puis d'archiver le tout en une fois via /archive-compromis (endpoint générique
   multi-PJ) et de marquer la notification traitée.
   Pas de build, pas d'import/export — tout est global (React CDN). */
function DiagnosticArchiveModal({ C, notif, projects, fiches, onClose, onDone }) {
  // Pièces jointes : liste multi-PJ (cas normal) ou repli sur la PJ principale
  // unique (cas d'une notif diagnostic promue par le classifieur V2 mono-PDF).
  const atts = React.useMemo(() => {
    const m = notif.metadata || {};
    if (Array.isArray(m.diagnostic_attachments) && m.diagnostic_attachments.length) return m.diagnostic_attachments;
    try {
      const ref = notif.attachment_ref ? JSON.parse(notif.attachment_ref) : null;
      if (ref && ref.attachmentId) return [ref];
    } catch (_) {}
    return [];
  }, [notif]);

  const params = (notif.proposed_action && notif.proposed_action.params) || {};

  // Dossier « Diag » suggéré au niveau PROGRAMME (miroir de buildOneDrivePath).
  const buildDiagFolder = (p, f) => {
    const seg = s => (s || '').replace(/[/\\:*?"<>|]/g, '_').trim() || 'inconnu';
    const ville = seg((p && p.ville) || '');
    const nom = seg((f && f.nomProgramme) || (p && p.nom) || 'Programme');
    const progSeg = ville ? `${ville} - ${nom}` : nom;
    return `\\Blue\\Programmes\\Programmes validés\\${progSeg}\\Diagnostics\\`;
  };

  const [selProjId, setSelProjId] = React.useState(params.programmeId || '');
  const proj = (projects || []).find(x => x && x.id === selProjId) || null;
  const fiche = (fiches && fiches[selProjId]) || {};
  const [folder, setFolder] = React.useState(params.suggestedFolder || (proj ? buildDiagFolder(proj, fiche) : '\\Blue\\Programmes\\Programmes validés\\'));

  // PJ cochées : toutes par défaut.
  const [checked, setChecked] = React.useState(() => new Set(atts.map(a => a.attachmentId)));

  // Navigateur OneDrive
  const [folders, setFolders] = React.useState([]);
  const [currentPath, setCurrentPath] = React.useState('');
  const [browsing, setBrowsing] = React.useState(false);
  const [showBrowser, setShowBrowser] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [okMsg, setOkMsg] = React.useState('');

  const inp = { background: '#f8fafc', border: '1px solid #cbd5e1', borderRadius: 8, color: '#1e293b', padding: '6px 10px', fontSize: 12, width: '100%', boxSizing: 'border-box' };
  const btn = (bg, sm) => ({ background: bg || '#2563eb', color: '#fff', border: 'none', borderRadius: 7, padding: sm ? '5px 12px' : '8px 18px', cursor: 'pointer', fontSize: sm ? 12 : 13, fontWeight: 600, whiteSpace: 'nowrap' });
  const fmtKo = b => (b == null ? '?' : Math.round(b / 1024) + ' Ko');

  const toggle = id => setChecked(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const onProgChange = (pid) => {
    setSelProjId(pid);
    const np = (projects || []).find(x => x && x.id === pid) || null;
    const nf = (fiches && fiches[pid]) || {};
    if (np) setFolder(buildDiagFolder(np, nf));
  };

  const browseTo = async (path) => {
    setBrowsing(true); setErr('');
    try {
      const r = await fetch('/api/agent/onedrive/browse?path=' + encodeURIComponent(path), { credentials: 'same-origin' });
      const d = await r.json();
      setCurrentPath(path); setFolders(d.folders || []);
    } catch (e) { setErr('Navigation impossible : ' + e.message); }
    finally { setBrowsing(false); }
  };
  const openBrowser = () => {
    setShowBrowser(true);
    const start = folder.replace(/\\+$/, '');
    const parent = '\\' + start.split('\\').filter(Boolean).slice(0, -1).join('\\');
    browseTo(parent || '\\Blue\\Programmes\\Programmes validés');
  };
  const goUp = () => {
    const segs = currentPath.replace(/\\+$/, '').split('\\').filter(Boolean);
    if (segs.length <= 1) return;
    browseTo('\\' + segs.slice(0, -1).join('\\'));
  };
  const createFolder = async () => {
    if (!newName.trim()) return;
    setBusy(true); setErr('');
    try {
      const full = currentPath.replace(/\\+$/, '') + '\\' + newName.trim();
      const r = await window.apiFetch('/api/agent/onedrive/mkdir', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: full }) });
      const d = await r.json();
      if (!d.ok) throw new Error(d.error || 'Erreur création dossier');
      setNewName(''); setFolder(full + '\\'); await browseTo(full);
    } catch (e) { setErr('Création impossible : ' + e.message); }
    finally { setBusy(false); }
  };

  const run = async () => {
    const ids = atts.filter(a => checked.has(a.attachmentId)).map(a => a.attachmentId);
    if (!ids.length) { setErr('Cochez au moins un fichier à ranger.'); return; }
    if (!folder.trim()) { setErr('Indiquez un dossier de destination.'); return; }
    setBusy(true); setErr(''); setOkMsg('');
    try {
      const r = await window.apiFetch(`/api/agent/notifications/${notif.id}/archive-compromis`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ folderPath: folder, attachmentIds: ids }),
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Archivage échoué');
      await window.apiFetch(`/api/agent/notifications/${notif.id}`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'mark_done' }),
      }).catch(() => {});
      setOkMsg(`${d.archived ? d.archived.length : ids.length} document(s) rangé(s) dans le dossier Diag.`);
      setTimeout(() => { if (onDone) onDone(); }, 900);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} onClick={onClose}>
      <div style={{ background: '#fff', borderRadius: 16, padding: 24, width: 640, maxWidth: '96vw', maxHeight: '92vh', overflowY: 'auto', boxShadow: '0 8px 40px #0003', border: '1px solid #e2e8f0' }} onClick={e => e.stopPropagation()}>
        <div style={{ fontWeight: 800, fontSize: 16, marginBottom: 4 }}>🔬 Diagnostics reçus — ranger dans le dossier Diag</div>
        <div style={{ fontSize: 12, color: C.muted, marginBottom: 14 }}>{notif.from_name || ''} {'<' + (notif.from_email || '') + '>'}{notif.received_at ? ' · reçu le ' + String(notif.received_at).slice(0, 10) : ''}</div>

        {okMsg && <div style={{ background: '#dcfce7', color: '#15803d', borderRadius: 8, padding: '8px 12px', fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{okMsg}</div>}
        {err && <div style={{ background: '#fee2e2', color: '#dc2626', borderRadius: 8, padding: '8px 12px', fontSize: 13, fontWeight: 600, marginBottom: 12 }}>{err}</div>}

        {/* Programme */}
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: C.muted, marginBottom: 4 }}>PROGRAMME</div>
          <select value={selProjId} onChange={e => onProgChange(e.target.value)} style={inp}>
            <option value="">— Choisir un programme —</option>
            <GroupedProgrammeOptions projects={projects} fiches={fiches} />
          </select>
        </div>

        {/* Dossier OneDrive */}
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: C.muted, marginBottom: 4 }}>DOSSIER DIAG (créé automatiquement s'il n'existe pas)</div>
          <div style={{ display: 'flex', gap: 6 }}>
            <input value={folder} onChange={e => setFolder(e.target.value)} style={{ ...inp, fontFamily: 'monospace', fontSize: 11 }} />
            <button onClick={() => showBrowser ? setShowBrowser(false) : openBrowser()} style={btn('#64748b', true)}>📁 Parcourir</button>
          </div>
          {showBrowser && (
            <div style={{ marginTop: 8, background: '#f0f9ff', border: '1px solid #bae6fd', borderRadius: 8, padding: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <button onClick={goUp} disabled={browsing} style={btn('#64748b', true)}>⬆ Remonter</button>
                <span style={{ fontSize: 11, color: C.muted, fontFamily: 'monospace', wordBreak: 'break-all' }}>{currentPath || '…'}</span>
              </div>
              <div style={{ maxHeight: 160, overflowY: 'auto', background: '#fff', border: '1px solid #e2e8f0', borderRadius: 6 }}>
                {browsing && <div style={{ padding: 8, fontSize: 12, color: C.muted }}>Chargement…</div>}
                {!browsing && folders.length === 0 && <div style={{ padding: 8, fontSize: 12, color: C.muted }}>Aucun sous-dossier.</div>}
                {!browsing && folders.map((f, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 8px', borderBottom: '1px solid #f1f5f9', fontSize: 12 }}>
                    <span style={{ flex: 1, cursor: 'pointer' }} onClick={() => browseTo((currentPath.replace(/\\+$/, '')) + '\\' + f.name)}>📁 {f.name}</span>
                    <button onClick={() => setFolder((currentPath.replace(/\\+$/, '')) + '\\' + f.name + '\\')} style={btn('#2563eb', true)}>Choisir</button>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                <input value={newName} onChange={e => setNewName(e.target.value)} placeholder="Nouveau dossier (ex. Diagnostics)" style={{ ...inp, fontSize: 12 }} />
                <button onClick={createFolder} disabled={busy || !newName.trim()} style={btn('#059669', true)}>+ Créer ici</button>
              </div>
            </div>
          )}
        </div>

        {/* Fichiers */}
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: C.muted, marginBottom: 4 }}>FICHIERS À RANGER ({checked.size}/{atts.length})</div>
          <div style={{ border: '1px solid #e2e8f0', borderRadius: 8 }}>
            {atts.length === 0 && <div style={{ padding: 8, fontSize: 12, color: C.muted }}>Aucune pièce jointe.</div>}
            {atts.map((a, i) => (
              <label key={a.attachmentId || i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px', borderBottom: i < atts.length - 1 ? '1px solid #f1f5f9' : 'none', fontSize: 12, cursor: 'pointer' }}>
                <input type="checkbox" checked={checked.has(a.attachmentId)} onChange={() => toggle(a.attachmentId)} />
                <span style={{ flex: 1 }}>📎 {a.filename || 'document.pdf'}</span>
                <span style={{ color: C.muted }}>{fmtKo(a.size)}</span>
              </label>
            ))}
          </div>
          <div style={{ fontSize: 11, color: C.muted, marginTop: 4 }}>Décochez ce qui ne doit pas aller dans le dossier Diag (ex. une facture du diagnostiqueur).</div>
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button onClick={onClose} style={{ ...btn('#e2e8f0'), color: '#475569' }}>Annuler</button>
          <button onClick={run} disabled={busy || !checked.size || !folder.trim()} style={btn('#059669')}>{busy ? 'Rangement…' : 'Ranger dans le dossier Diag'}</button>
        </div>
      </div>
    </div>
  );
}
