import { useEffect, useRef, useState } from 'react';
import PasswordStrength from '../components/PasswordStrength.jsx';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { useUi }  from '../context/UiContext.jsx';
import { api } from '../api.js';

/* ── Icônes nav ─────────────────────────────────────────────── */
function IconUser() {
  return <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>;
}
function IconLock() {
  return <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>;
}

/* ── Dropdown custom style Finary ────────────────────────────── */
const LANGUES = [
  { value: 'fr', label: 'Français' },
  { value: 'en', label: 'English' },
];
const DEVISES = [
  { value: 'EUR', label: '€ - EUR' },
  { value: 'USD', label: '$ - USD' },
  { value: 'GBP', label: '£ - GBP' },
  { value: 'CHF', label: 'CHF' },
  { value: 'CAD', label: 'CA$ - CAD' },
  { value: 'SGD', label: 'SGD' },
];

function ProfileSelect({ label, options, value, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const selected = options.find(o => o.value === value);

  return (
    <div ref={ref} className="profile-field">
      <span className="profile-label">{label}</span>
      <div className={`profile-select-trigger${open ? ' open' : ''}`}
        onClick={() => setOpen(o => !o)} role="button" tabIndex={0}
        onKeyDown={e => e.key === 'Enter' && setOpen(o => !o)}>
        <span>{selected?.label}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
          style={{ transition: 'transform .15s', transform: open ? 'rotate(180deg)' : 'rotate(0deg)' }}
          aria-hidden="true">
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </div>
      {open && (
        <div className="profile-select-dropdown" role="listbox">
          {options.map(o => (
            <div key={o.value}
              className={`profile-select-option${o.value === value ? ' selected' : ''}`}
              role="option" aria-selected={o.value === value}
              onClick={() => { onChange(o.value); setOpen(false); }}>
              {o.label}
              {o.value === value && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                  aria-hidden="true">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── Bloc renvoi email de vérification ───────────────────────── */
function EmailResendBlock({ email }) {
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);

  const resend = async () => {
    setBusy(true);
    try {
      await fetch('/api/auth/resend-verification', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      setDone(true);
    } catch (_) {}
    finally { setBusy(false); }
  };

  if (done) return <p style={{ fontSize: 12, color: 'var(--success, #16a34a)', marginTop: 6 }}>✓ Email de vérification renvoyé.</p>;
  return (
    <p style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6 }}>
      Email non confirmé.{' '}
      <button type="button" onClick={() => resend()} disabled={busy}
        style={{ background: 'none', border: 'none', padding: 0, color: 'var(--primary)', fontWeight: 600, fontSize: 12, cursor: 'pointer', textDecoration: 'underline' }}>
        {busy ? 'Envoi…' : 'Renvoyer le lien'}
      </button>
    </p>
  );
}

/* ── Changement d'email ───────────────────────────────────────── */
function EmailChangeForm({ onDone }) {
  const { updateUser } = useAuth();
  const [newEmail, setNewEmail] = useState('');
  const [pwd, setPwd]           = useState('');
  const [msg, setMsg]           = useState(null);
  const [err, setErr]           = useState(null);
  const [busy, setBusy]         = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null); setMsg(null); setBusy(true);
    try {
      const r = await updateUser({ email: newEmail, currentPassword: pwd });
      if (r?.requiresVerification) {
        setMsg(`Un email de vérification a été envoyé à ${newEmail}. Validez-le pour activer cette adresse.`);
      } else {
        setMsg('Email mis à jour.'); setTimeout(onDone, 1500);
      }
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <form onSubmit={submit} style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)' }}>
        Après le changement, un email de vérification sera envoyé à la nouvelle adresse.
      </p>
      {err && <div className="error">{err}</div>}
      {msg && <div className="success-msg">{msg}</div>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <label className="profile-label">Nouvelle adresse email</label>
        <input className="profile-input" type="email" required value={newEmail} onChange={e => setNewEmail(e.target.value)} placeholder="nouvelle@email.com" />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <label className="profile-label">Mot de passe actuel (confirmation)</label>
        <input className="profile-input" type="password" required value={pwd} onChange={e => setPwd(e.target.value)} placeholder="••••••••" />
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button type="submit" className="btn btn-primary" disabled={busy} style={{ fontSize: 13 }}>
          {busy ? 'Enregistrement…' : 'Confirmer le changement'}
        </button>
        <button type="button" className="btn btn-outline" onClick={() => onDone()} style={{ fontSize: 13 }}>Annuler</button>
      </div>
    </form>
  );
}

/* ── Mon profil + Préférences ────────────────────────────────── */
function AccountForm() {
  const { user, updateUser } = useAuth();
  const { langue, setLangue, devise, setDevise } = useUi();

  /* Découpe display_name en prénom / nom */
  const parseName = (dn = '') => {
    const parts = dn.trim().split(' ');
    return parts.length >= 2
      ? { prenom: parts[0], nom: parts.slice(1).join(' ') }
      : { prenom: dn.trim(), nom: '' };
  };

  const initial = parseName(user?.display_name);
  const [prenom, setPrenom] = useState(initial.prenom);
  const [nom,    setNom]    = useState(initial.nom);
  const [infoMsg, setInfoMsg]       = useState(null);
  const [infoErr, setInfoErr]       = useState(null);
  const [loading, setLoading]       = useState(false);
  const [changingEmail, setChangingEmail] = useState(false);

  const save = async () => {
    setInfoErr(null); setInfoMsg(null); setLoading(true);
    try {
      const displayName = [prenom.trim(), nom.trim()].filter(Boolean).join(' ');
      await updateUser({ displayName });
      setInfoMsg('Profil mis à jour.');
    } catch (err) { setInfoErr(err.message); }
    finally { setLoading(false); }
  };

  /* Sauvegarde auto à la perte du focus */
  const handleBlur = () => save();

  return (
    <div className="profile-page">

      {/* ── Mon profil ──────────────────────────────────────── */}
      <section className="profile-section">
        <h2 className="profile-section-title">Mon profil</h2>

        {infoErr && <div className="error" style={{ marginBottom: 12 }}>{infoErr}</div>}
        {infoMsg && <div className="success-msg" style={{ marginBottom: 12 }}>{infoMsg}</div>}

        <div className="profile-grid-2">
          <div className="profile-field">
            <span className="profile-label">Prénom</span>
            <input className="profile-input" value={prenom}
              onChange={e => setPrenom(e.target.value)}
              onBlur={handleBlur}
              placeholder="Prénom" />
          </div>
          <div className="profile-field">
            <span className="profile-label">Nom</span>
            <input className="profile-input" value={nom}
              onChange={e => setNom(e.target.value)}
              onBlur={handleBlur}
              placeholder="NOM" />
          </div>
        </div>

        <div className="profile-field profile-field-full">
          <span className="profile-label">Mon email</span>
          <div className="profile-email-row" style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <span className="profile-email-value">{user?.email}</span>
            {user?.email_verified
              ? <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 10, background: 'var(--success-bg, #f0fdf4)', color: 'var(--success, #16a34a)', border: '1px solid #bbf7d0' }}>✓ Vérifié</span>
              : <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 10, background: 'var(--warning-bg, #fffbeb)', color: 'var(--warning-text, #92400e)', border: '1px solid #fcd34d' }}>Non vérifié</span>
            }
          </div>
          {!user?.email_verified && <EmailResendBlock email={user?.email} />}
        </div>

        <div style={{ marginTop: 20 }}>
          <button className="profile-manage-btn" type="button" onClick={() => setChangingEmail(v => !v)}>
            {changingEmail ? 'Annuler' : 'Changer mon email'}
          </button>
        </div>

        {changingEmail && <EmailChangeForm onDone={() => setChangingEmail(false)} />}
      </section>

      {/* ── Préférences ─────────────────────────────────────── */}
      <section className="profile-section">
        <h2 className="profile-section-title">Préférences</h2>
        <div className="profile-grid-2">
          <ProfileSelect label="Langue"  options={LANGUES} value={langue}  onChange={setLangue} />
          <ProfileSelect label="Devise"  options={DEVISES} value={devise}  onChange={setDevise} />
        </div>
      </section>

      {loading && <p className="text-muted" style={{ fontSize: 'var(--fs-sm)' }}>Enregistrement…</p>}
    </div>
  );
}


/* ── 2FA — Configuration double authentification ───────────────── */
function TwoFASection({ user }) {
  const [status,     setStatus]     = useState('idle'); // idle | setup | confirming | disabling
  const [setupData,  setSetupData]  = useState(null);   // { secret, qrCode, email }
  const [code,       setCode]       = useState('');
  const [disablePwd, setDisablePwd] = useState('');
  const [err,        setErr]        = useState(null);
  const [busy,       setBusy]       = useState(false);
  const [msg,        setMsg]        = useState(null);
  const [enabled,    setEnabled]    = useState(!!user?.totp_enabled);

  const startSetup = async () => {
    setErr(null); setMsg(null); setBusy(true);
    try {
      const data = await api.get('/auth/2fa/setup');
      setSetupData(data);
      setStatus('setup');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const confirmSetup = async (e) => {
    e.preventDefault(); setErr(null); setBusy(true);
    try {
      await api.post('/auth/2fa/confirm-setup', { code });
      setEnabled(true);
      setStatus('idle');
      setSetupData(null);
      setCode('');
      setMsg('Le 2FA est maintenant activé sur votre compte.');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const disable = async (e) => {
    e.preventDefault(); setErr(null); setBusy(true);
    try {
      await api.post('/auth/2fa/disable', { password: disablePwd });
      setEnabled(false);
      setStatus('idle');
      setDisablePwd('');
      setMsg('Le 2FA a été désactivé.');
      localStorage.removeItem('cl_device_token');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <div className="card" style={{ marginTop: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
        <h3 style={{ margin: 0 }}>Double authentification (2FA)</h3>
        <span style={{
          fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 12,
          background: enabled ? 'var(--success-bg,#f0fdf4)' : 'var(--surface-2,#f4f4f5)',
          color: enabled ? 'var(--success,#16a34a)' : 'var(--text-muted)',
          border: `1px solid ${enabled ? '#bbf7d0' : 'var(--border)'}`,
        }}>
          {enabled ? '✓ Activé' : 'Désactivé'}
        </span>
      </div>
      <p className="text-muted" style={{ margin: '0 0 16px', fontSize: 'var(--fs-sm)' }}>
        Protégez votre compte avec une vérification supplémentaire à chaque connexion.
      </p>

      {err && <div className="error" style={{ marginBottom: 12 }}>{err}</div>}
      {msg && <div className="success-msg" style={{ marginBottom: 12 }}>{msg}</div>}

      {/* ── État normal ── */}
      {status === 'idle' && !enabled && (
        <button className="primary" onClick={() => startSetup()} disabled={busy}>
          {busy ? 'Chargement…' : 'Activer le 2FA'}
        </button>
      )}
      {status === 'idle' && enabled && (
        <button className="btn btn-outline" style={{ color: 'var(--danger,#dc2626)', borderColor: 'var(--danger,#dc2626)' }}
          onClick={() => { setStatus('disabling'); setErr(null); setMsg(null); }}>
          Désactiver le 2FA
        </button>
      )}

      {/* ── Setup : QR code + vérification ── */}
      {status === 'setup' && setupData && (
        <div>
          <p style={{ margin: '0 0 12px', fontSize: 13, lineHeight: 1.6 }}>
            Scannez ce QR code avec votre application d'authentification (<strong>Google Authenticator</strong>, <strong>Authy</strong>, etc.), puis entrez le code à 6 chiffres pour confirmer.
          </p>
          <div style={{ display: 'flex', gap: 24, alignItems: 'flex-start', flexWrap: 'wrap', marginBottom: 20 }}>
            <div style={{ background: '#fff', padding: 12, borderRadius: 8, border: '1px solid var(--border)', display: 'inline-block' }}>
              <img src={setupData.qrCode} alt="QR code 2FA" width={160} height={160} />
            </div>
            <div style={{ flex: 1, minWidth: 200 }}>
              <p style={{ margin: '0 0 6px', fontSize: 12, color: 'var(--text-muted)' }}>
                Vous ne pouvez pas scanner ? Entrez manuellement cette clé dans votre application :
              </p>
              <code style={{
                display: 'block', background: 'var(--surface-2)', padding: '8px 10px',
                borderRadius: 6, fontSize: 13, letterSpacing: 1, wordBreak: 'break-all',
                border: '1px solid var(--border)',
              }}>
                {setupData.secret}
              </code>
              <p style={{ margin: '8px 0 0', fontSize: 11, color: 'var(--text-muted)' }}>
                Émetteur : <strong>{setupData.issuer}</strong> · Compte : <strong>{setupData.email}</strong>
              </p>
            </div>
          </div>
          <form onSubmit={confirmSetup} style={{ display: 'flex', gap: 10, alignItems: 'flex-end', maxWidth: 320 }}>
            <div style={{ flex: 1 }}>
              <label style={{ display: 'block', marginBottom: 4, fontSize: 13, fontWeight: 500 }}>Code de vérification</label>
              <input
                type="text" inputMode="numeric" maxLength={6} pattern="[0-9]{6}"
                placeholder="000000" value={code}
                onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                autoComplete="one-time-code"
                style={{ fontSize: 20, letterSpacing: 6, textAlign: 'center', fontWeight: 700 }}
              />
            </div>
            <button className="primary" type="submit" disabled={busy || code.length !== 6} style={{ flexShrink: 0 }}>
              {busy ? '…' : 'Confirmer'}
            </button>
          </form>
          <button type="button" onClick={() => { setStatus('idle'); setSetupData(null); setCode(''); setErr(null); }}
            style={{ marginTop: 12, background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 13, cursor: 'pointer', textDecoration: 'underline', padding: 0 }}>
            Annuler
          </button>
        </div>
      )}

      {/* ── Désactivation : mot de passe ── */}
      {status === 'disabling' && (
        <form onSubmit={disable} style={{ maxWidth: 360 }}>
          <p style={{ margin: '0 0 12px', fontSize: 13, color: 'var(--text-muted)' }}>
            Confirmez votre mot de passe pour désactiver le 2FA.
          </p>
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end' }}>
            <div style={{ flex: 1 }}>
              <label style={{ display: 'block', marginBottom: 4, fontSize: 13, fontWeight: 500 }}>Mot de passe actuel</label>
              <input type="password" required value={disablePwd}
                onChange={e => setDisablePwd(e.target.value)}
                autoComplete="current-password" placeholder="••••••••" />
            </div>
            <button className="btn" style={{ background: 'var(--danger,#dc2626)', color: '#fff', flexShrink: 0 }}
              type="submit" disabled={busy || !disablePwd}>
              {busy ? '…' : 'Désactiver'}
            </button>
          </div>
          <button type="button" onClick={() => { setStatus('idle'); setErr(null); setDisablePwd(''); }}
            style={{ marginTop: 10, background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 13, cursor: 'pointer', textDecoration: 'underline', padding: 0 }}>
            Annuler
          </button>
        </form>
      )}
    </div>
  );
}

/* ── Sécurité — Mot de passe ─────────────────────────────────── */
function SecurityForm() {
  const { updateUser } = useAuth();
  const [minPasswordLength, setMinPasswordLength] = useState(8);

  useEffect(() => {
    fetch('/api/app-info').then(r => r.json()).then(d => {
      if (d.minPasswordLength) setMinPasswordLength(d.minPasswordLength);
    }).catch(() => {});
  }, []);

  const [pwdForm, setPwdForm] = useState({ currentPassword: '', newPassword: '', confirm: '' });
  const [pwdMsg, setPwdMsg]   = useState(null);
  const [pwdErr, setPwdErr]   = useState(null);
  const [pwdLoading, setPwdLoading] = useState(false);

  const savePwd = async (e) => {
    e.preventDefault(); setPwdErr(null); setPwdMsg(null);
    if (pwdForm.newPassword !== pwdForm.confirm) { setPwdErr('Les mots de passe ne correspondent pas.'); return; }
    if (pwdForm.newPassword.length < 8) { setPwdErr('8 caractères minimum.'); return; }
    setPwdLoading(true);
    try {
      await updateUser({ currentPassword: pwdForm.currentPassword, newPassword: pwdForm.newPassword });
      setPwdMsg('Mot de passe modifié avec succès.');
      setPwdForm({ currentPassword: '', newPassword: '', confirm: '' });
    } catch (err) { setPwdErr(err.message); }
    finally { setPwdLoading(false); }
  };

  const handleBackfillComptes = async () => {
    setLoadingBackfill(true);
    setErrorMsg(null);
    setSuccessMsg(null);
    try {
      const { updated, total } = await api.post('/remboursements/backfill-comptes', {});
      if (updated === 0) {
        setSuccessMsg(`Aucun remboursement à corriger (${total} vérifié${total > 1 ? 's' : ''}).`);
      } else {
        setSuccessMsg(`${updated} remboursement${updated > 1 ? 's' : ''} mis à jour sur ${total} vérifié${total > 1 ? 's' : ''}.`);
      }
      setShowBackfillModal(false);
    } catch (err) {
      setErrorMsg(err.message || 'Une erreur est survenue.');
      setShowBackfillModal(false);
    } finally {
      setLoadingBackfill(false);
    }
  };

  return (
    <div className="card">
      <h3 style={{ margin: '0 0 4px' }}>Mot de passe</h3>
      <p className="text-muted" style={{ margin: '0 0 16px', fontSize: 'var(--fs-sm)' }}>
        Saisissez votre mot de passe actuel puis choisissez-en un nouveau (8 caractères minimum).
      </p>
      {pwdErr && <div className="error">{pwdErr}</div>}
      {pwdMsg && <div className="success-msg">{pwdMsg}</div>}
      <form onSubmit={savePwd}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 400 }}>
          <div>
            <label>Mot de passe actuel</label>
            <input type="password" required autoComplete="current-password"
              value={pwdForm.currentPassword}
              onChange={e => setPwdForm({ ...pwdForm, currentPassword: e.target.value })} />
          </div>
          <div>
            <label>Nouveau mot de passe</label>
            <input type="password" required autoComplete="new-password"
              value={pwdForm.newPassword}
              onChange={e => setPwdForm({ ...pwdForm, newPassword: e.target.value })} />
            <PasswordStrength password={pwdForm.newPassword} minLength={minPasswordLength} />
          </div>
          <div>
            <label>Confirmer le nouveau mot de passe</label>
            <input type="password" required autoComplete="new-password"
              value={pwdForm.confirm}
              onChange={e => setPwdForm({ ...pwdForm, confirm: e.target.value })} />
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
          <button className="primary" type="submit" disabled={pwdLoading}>
            {pwdLoading ? 'Modification…' : 'Modifier le mot de passe'}
          </button>
        </div>
      </form>
    </div>
  );
}


/* ── Appareils connectés ─────────────────────────────────────── */
function fmtRelative(isoStr) {
  if (!isoStr) return null;
  // SQLite datetime() returns UTC without Z — force UTC parsing
  const d = new Date(isoStr.endsWith('Z') ? isoStr : isoStr + 'Z');
  const diff = Date.now() - d.getTime();
  const secs  = Math.floor(diff / 1000);
  const mins  = Math.floor(secs / 60);
  const hours = Math.floor(mins / 60);
  const days  = Math.floor(hours / 24);
  if (secs < 60)   return `à l'instant`;
  if (mins < 60)   return `il y a ${mins} min`;
  if (hours < 24)  return `il y a ${hours} h`;
  if (days < 30)   return `il y a ${days} j`;
  return d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function parseBrowser(ua) {
  if (/CriOS\//i.test(ua))   return 'Chrome '  + (ua.match(/CriOS\/(\d+)/)?.[1] || '');   // Chrome sur iOS
  if (/FxiOS\//i.test(ua))   return 'Firefox ' + (ua.match(/FxiOS\/(\d+)/)?.[1] || '');   // Firefox sur iOS
  if (/EdgiOS\//i.test(ua))  return 'Edge '    + (ua.match(/EdgiOS\/(\d+)/)?.[1] || '');  // Edge sur iOS
  if (/OPR\//i.test(ua))     return 'Opera '   + (ua.match(/OPR\/(\d+)/)?.[1] || '');
  if (/Edg\//i.test(ua))     return 'Edge '    + (ua.match(/Edg\/(\d+)/)?.[1] || '');
  if (/Chrome\//i.test(ua))  return 'Chrome '  + (ua.match(/Chrome\/(\d+)/)?.[1] || '');
  if (/Firefox\//i.test(ua)) return 'Firefox ' + (ua.match(/Firefox\/(\d+)/)?.[1] || '');
  if (/Safari\//i.test(ua))  return 'Safari '  + (ua.match(/Version\/(\d+)/)?.[1] || '');
  return '';
}

function parseUA(ua) {
  if (!ua) return { device: 'Inconnu', icon: 'desktop' };
  const br = parseBrowser(ua);
  const suffix = br ? ` — ${br}` : '';

  // ── iOS ─────────────────────────────────────────────────────────────────
  if (/iPhone/i.test(ua))  return { device: `iPhone${suffix}`,  icon: 'mobile'  };
  if (/iPad/i.test(ua))    return { device: `iPad${suffix}`,    icon: 'tablet'  };

  // ── Android ─────────────────────────────────────────────────────────────
  if (/Android/i.test(ua)) {
    // Extrait "Pixel 9 Pro" / "SM-S918B" / etc. depuis "; DEVICE Build/" ou "; DEVICE)"
    const m = ua.match(/Android[\s/][\d.]+;\s*([^;)]+?)(?:\s+Build\/|\s*\))/i);
    const devName = m ? m[1].trim() : 'Android';
    const isTablet = /tablet/i.test(ua) || !/mobile/i.test(ua);
    return { device: `${devName}${suffix}`, icon: isTablet ? 'tablet' : 'mobile' };
  }

  // ── Desktop ─────────────────────────────────────────────────────────────
  let os = 'Inconnu';
  if (/Windows NT 10\.0/i.test(ua)) os = 'Windows 10/11';
  else if (/Windows/i.test(ua))      os = 'Windows';
  else if (/Macintosh/i.test(ua))    os = 'Mac';
  else if (/CrOS/i.test(ua))         os = 'ChromeOS';
  else if (/Linux/i.test(ua))        os = 'Linux';
  return { device: `${os}${suffix}`, icon: 'desktop' };
}

function DeviceIcon({ type }) {
  if (type === 'mobile') return (
    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="5" y="2" width="14" height="20" rx="2"/>
      <circle cx="12" cy="18.5" r="0.8" fill="currentColor" stroke="none"/>
    </svg>
  );
  if (type === 'tablet') return (
    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="2" width="16" height="20" rx="2"/>
      <circle cx="12" cy="18.5" r="0.8" fill="currentColor" stroke="none"/>
    </svg>
  );
  return (
    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="4" width="20" height="14" rx="2"/>
      <path d="M8 20h8M12 18v2"/>
    </svg>
  );
}

function TrustedDevicesSection() {
  const [devices,  setDevices]  = useState([]);
  const [loading,  setLoading]  = useState(true);
  const [err,      setErr]      = useState(null);
  const [busy,     setBusy]     = useState(null); // id en cours de révocation

  const currentToken = localStorage.getItem('cl_device_token');

  const load = async () => {
    try {
      setLoading(true);
      const data = await api.get('/auth/trusted-devices');
      setDevices(data);
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  };

  useEffect(() => { load(); }, []);

  const revoke = async (id, isCurrent) => {
    setBusy(id);
    try {
      await api.del(`/auth/trusted-devices/${id}`);
      if (isCurrent) localStorage.removeItem('cl_device_token');
      await load();
    } catch (e) { setErr(e.message); }
    finally { setBusy(null); }
  };

  const revokeAll = async () => {
    setBusy('all');
    try {
      await api.del('/auth/trusted-devices');
      localStorage.removeItem('cl_device_token');
      await load();
    } catch (e) { setErr(e.message); }
    finally { setBusy(null); }
  };

  if (loading) return null;

  return (
    <div className="card" style={{ marginTop: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
        <h3 style={{ margin: 0 }}>Appareils de confiance</h3>
        {devices.length > 0 && (
          <button
            onClick={() => revokeAll()}
            disabled={busy === 'all'}
            style={{
              padding: '5px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              background: 'var(--danger,#dc2626)', color: '#fff', border: 'none',
              cursor: busy === 'all' ? 'not-allowed' : 'pointer',
            }}
          >
            Tout déconnecter
          </button>
        )}
      </div>
      <p className="text-muted" style={{ margin: '0 0 16px', fontSize: 'var(--fs-sm)' }}>
        Appareils reconnus pour la double authentification (validité 30 jours).
      </p>

      {err && <div className="error" style={{ marginBottom: 12 }}>{err}</div>}

      {devices.length === 0 ? (
        <p style={{ color: 'var(--text-muted)', fontSize: 13 }}>Aucun appareil de confiance enregistré.</p>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {devices.map(dev => {
            const { device, icon } = parseUA(dev.user_agent);
            const connDate = dev.created_at
              ? new Date(dev.created_at).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' }) + ' — ' +
                new Date(dev.created_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })
              : '—';
            return (
              <div key={dev.id} style={{
                display: 'flex', alignItems: 'center', gap: 16,
                padding: '14px 16px', borderRadius: 10,
                border: `1.5px solid ${dev.isCurrent ? 'var(--primary,#1e40af)' : 'var(--border)'}`,
                background: dev.isCurrent ? 'var(--primary-bg,#eff6ff)' : 'var(--surface-2,#f9fafb)',
              }}>
                <div style={{
                  width: 52, height: 52, borderRadius: 10, flexShrink: 0,
                  background: 'var(--surface,#fff)', border: '1px solid var(--border)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--text-muted)',
                }}>
                  <DeviceIcon type={icon} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontWeight: 600, fontSize: 14, color: 'var(--text)' }}>{device}</span>
                    {dev.isCurrent && (
                      <span style={{
                        fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 10, letterSpacing: 0.5,
                        background: 'var(--primary,#1e40af)', color: '#fff',
                      }}>APPAREIL ACTUEL</span>
                    )}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 3 }}>
                    {dev.ip_address && <span>{dev.ip_address} · </span>}
                    <span>Connecté le {connDate}</span>
                    {fmtRelative(dev.last_seen_at) && (
                      <span style={{ marginLeft: 8, color: 'var(--text-muted)', opacity: 0.75 }}>
                        · Vu {fmtRelative(dev.last_seen_at)}
                      </span>
                    )}
                  </div>
                </div>
                <button
                  onClick={() => revoke(dev.id, dev.isCurrent)}
                  disabled={busy === dev.id}
                  style={{
                    flexShrink: 0, padding: '5px 12px', borderRadius: 6,
                    fontSize: 12, fontWeight: 600,
                    background: 'none',
                    color: 'var(--danger,#dc2626)',
                    border: '1px solid var(--danger,#dc2626)',
                    cursor: busy === dev.id ? 'not-allowed' : 'pointer',
                  }}
                >
                  {busy === dev.id ? '…' : 'Déconnecter'}
                </button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ── Page principale ─────────────────────────────────────────── */
export default function MonCompte() {
  const { search } = useLocation();
  const navigate   = useNavigate();
  const { user }   = useAuth();

  const section    = new URLSearchParams(search).get('section') || 'profil';
  const setSection = (s) => navigate(`/compte?section=${s}`, { replace: true });

  const SECTIONS = [
    { id: 'profil',    label: 'Mon compte',            icon: <IconUser /> },
{ id: 'securite',  label: 'Sécurité',              icon: <IconLock /> },
  ];

  return (
    <div className="account-layout">

      {/* ── Nav gauche ───────────────────────────────────────── */}
      <aside className="account-sidebar">
        <h1 className="account-title">Mon compte</h1>
        {SECTIONS.map(item => (
          <button
            key={item.id}
            className={`account-nav-item${section === item.id ? ' active' : ''}`}
            onClick={() => setSection(item.id)}
          >
            {item.icon}
            {item.label}
          </button>
        ))}
      </aside>
      {/* ── Contenu ─────────────────────────────────────── */}
      <div className="account-content">
        {section === 'profil'    && <AccountForm />}
        {section === 'securite'  && <><SecurityForm /><TwoFASection user={user} /><TrustedDevicesSection /></>}
      </div>

    </div>
  );
}
