// ============================================================
// Login.jsx — auth login (FASE 22)
// ============================================================
// POST /api/auth/login con email/password reali. Su success:
//  - cookie httpOnly settato dal server
//  - setUser({id,name,role,email,tenantId}) → store
//  - navigate dashboard
// La form fallback al ruolo demo `Marco Ferretti` per l'email pre-compilata,
// ma accetta qualsiasi persona con auth_credential attivo (password 'demo123'
// in dev, vedi scripts/seed-auth.mjs).
function Login() {
  const { setUser, navigate, pushToast } = useStore();
  const [email, setEmail] = React.useState('m.ferretti@veridanto.local');
  const [password, setPassword] = React.useState('demo123');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  // FASE 22.X (sessione 75 A1) — MFA challenge state
  const [mfaChallengeToken, setMfaChallengeToken] = React.useState(null);
  const [mfaCode, setMfaCode] = React.useState('');

  function completeLogin(u) {
    setUser({
      id: u.id,
      name: u.name,
      email: u.email,
      tenantId: u.tenantId,
      roleIds: u.roleIds || [],
      role: 'Workspace user',
    });
    pushToast({ title: 'Login effettuato', desc: `Benvenuto ${u.name}`, tone: 'ok' });
    navigate('dashboard');
  }

  async function doLogin(e) {
    if (e) e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ email: email.trim(), password }),
      });
      const json = await res.json().catch(() => ({}));
      if (res.status === 429) {
        setError(`Troppi tentativi. Riprova fra ${json.retryAfterSec || 60}s.`);
        return;
      }
      if (!res.ok) {
        setError(json.error === 'invalid_credentials' ? 'Email o password non validi' : (json.error || `HTTP ${res.status}`));
        return;
      }
      // FASE 22.X — MFA challenge: il server NON ha settato la session cookie.
      // Mostra step 2 (input codice 6-digit o backup code).
      if (json.requiresMfa) {
        setMfaChallengeToken(json.mfaChallengeToken);
        setMfaCode('');
        return;
      }
      completeLogin(json.user);
    } catch (err) {
      setError(String(err?.message || err));
    } finally {
      setSubmitting(false);
    }
  }

  async function doMfaVerify(e) {
    if (e) e.preventDefault();
    if (submitting || !mfaCode) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch('/api/auth/mfa/verify', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ code: mfaCode.trim(), mfaChallengeToken }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (json.error === 'invalid_challenge_token') {
          setError('Sessione MFA scaduta (5min). Re-inserisci email + password.');
          setMfaChallengeToken(null);
          return;
        }
        setError(json.error === 'invalid_code' ? 'Codice errato' : (json.error || `HTTP ${res.status}`));
        return;
      }
      if (json.backupCodeConsumed) {
        pushToast({ title: 'Backup code utilizzato', desc: `Restanti: ${json.remainingBackupCodes}`, tone: 'warn' });
      }
      completeLogin(json.user);
    } catch (err) {
      setError(String(err?.message || err));
    } finally {
      setSubmitting(false);
    }
  }

  function cancelMfa() {
    setMfaChallengeToken(null);
    setMfaCode('');
    setError(null);
  }

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 520px', background: 'var(--bg-0)' }}>
      <div style={{ position: 'relative', padding: '48px 56px', display: 'flex', flexDirection: 'column', borderRight: '1px solid var(--line)', background: 'linear-gradient(140deg, var(--bg-0), var(--bg-1))' }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{ width: 28, height: 28, border: '1.5px solid var(--accent)', display: 'grid', placeItems: 'center', color: 'var(--accent)', fontFamily: 'var(--font-display)', fontWeight: 700 }}>V</div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.02em' }}>Veridanto · CAPEX AI</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.14em' }}>Industrial Investment Governance · by Leaven Consulting</div>
          </div>
        </div>
        <div style={{ marginTop: 'auto' }}>
          <div className="eyebrow">Industrial investment governance</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 48, lineHeight: 1.05, letterSpacing: '-0.02em', fontWeight: 500, margin: '12px 0 10px', maxWidth: 560 }}>
            Orchestrazione CAPEX<br/><em style={{ color: 'var(--accent)', fontStyle: 'normal' }}>assistita da agenti AI.</em>
          </h1>
          <p style={{ fontSize: 14, color: 'var(--text-2)', lineHeight: 1.55, maxWidth: 560 }}>
            Un solo workspace per 20 progetti, 8 siti e 10 anni di archivio. L'agente estrae, confronta e genera bozze; le persone decidono.
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 40, maxWidth: 560 }}>
            <div><div className="eyebrow">Ore salvate</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600 }}>1.820h</div></div>
            <div><div className="eyebrow">Early warning</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600 }}>8 attivi</div></div>
            <div><div className="eyebrow">ROI 12m</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600 }}>3,4×</div></div>
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', placeItems: 'center', padding: 48 }}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <div className="eyebrow">{mfaChallengeToken ? 'Verifica MFA' : 'Accedi'}</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, margin: '8px 0 24px' }}>
            {mfaChallengeToken ? 'Secondo fattore' : 'Workspace CAPEX AI'}
          </h2>
          {!mfaChallengeToken && (
            <form onSubmit={doLogin}>
              <div className="field"><label>Email aziendale</label><input value={email} onChange={e => setEmail(e.target.value)} autoComplete="email" autoFocus disabled={submitting}/></div>
              <div className="field"><label>Password</label><input type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="current-password" disabled={submitting}/></div>
              {error && (
                <div style={{padding:'8px 10px', border:'1px solid var(--err)', borderRadius:4, background:'rgba(192,57,43,0.08)', color:'var(--err)', fontSize:12, marginBottom:12}}>
                  {error}
                </div>
              )}
              <div className="row" style={{justifyContent:'space-between', marginBottom:16, fontSize:12}}>
                <label className="row" style={{gap:6}}><input type="checkbox" defaultChecked/> Resta connesso</label>
                <span style={{color:'var(--text-3)', fontSize:10.5}}>Dev: <code>demo123</code></span>
              </div>
              <button type="submit" className="btn primary" style={{ width: '100%', justifyContent: 'center', padding: '12px' }} disabled={submitting}>
                {submitting ? 'Accesso in corso…' : 'Accedi al workspace'}
              </button>
            </form>
          )}
          {mfaChallengeToken && (
            <form onSubmit={doMfaVerify} data-testid="mfa-challenge-form">
              <div style={{ fontSize: 12.5, color: 'var(--text-2)', marginBottom: 14, lineHeight: 1.55 }}>
                Inserisci il codice 6 cifre dall'app authenticator, oppure uno dei <strong>backup code</strong> se non hai accesso all'app.
              </div>
              <div className="field">
                <label>Codice MFA</label>
                <input
                  type="text"
                  inputMode="text"
                  autoComplete="one-time-code"
                  autoFocus
                  maxLength={20}
                  value={mfaCode}
                  onChange={e => setMfaCode(e.target.value.toUpperCase().replace(/[^A-Z0-9-]/g, ''))}
                  placeholder="123456 oppure ABCD12-XY3Z"
                  disabled={submitting}
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 16, textAlign: 'center', letterSpacing: 2 }}
                  data-testid="mfa-challenge-code-input"
                />
              </div>
              {error && (
                <div style={{padding:'8px 10px', border:'1px solid var(--err)', borderRadius:4, background:'rgba(192,57,43,0.08)', color:'var(--err)', fontSize:12, marginBottom:12}}>
                  {error}
                </div>
              )}
              <button type="submit" className="btn primary" style={{ width: '100%', justifyContent: 'center', padding: '12px' }} disabled={submitting || !mfaCode} data-testid="mfa-challenge-submit-btn">
                {submitting ? 'Verifica…' : 'Verifica e accedi'}
              </button>
              <button type="button" className="btn ghost" style={{ width: '100%', justifyContent: 'center', padding: '8px', marginTop: 8 }} onClick={cancelMfa} disabled={submitting}>
                Annulla, torna al login
              </button>
            </form>
          )}
          <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--text-3)', margin: '18px 0', fontFamily: 'var(--font-mono)' }}>— oppure —</div>
          <button className="btn ghost" style={{ width: '100%', justifyContent: 'center', padding: '10px' }} disabled title="SSO SAML non ancora configurato">
            SSO SAML · Corporate
          </button>
          <div className="sep"/>
          <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.12em', textAlign: 'center' }}>
            Veridanto · human-in-the-loop by design
          </div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { Login });
