/* ============================================================
   LOGIN — Supabase Auth + Cloudflare Turnstile + Rate Limit
   - Gate Turnstile full-screen prima del login
   - 5 tentativi falliti → blocco 10 minuti per email
   - Refresh → Turnstile ripete
   ============================================================ */

// ----- Turnstile bootstrap: window._sfTurnstile + onTurnstileApiReady -----
// sono definiti in index.html PRIMA dello script Cloudflare per evitare race condition

function TurnstileWidget({ onToken, onExpired, onError, theme }) {
  const ref = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  React.useEffect(() => {
    const mount = () => {
      if (!ref.current || !window.turnstile) return;
      const sitekey = window.SF_CONFIG?.turnstileSiteKey;
      if (!sitekey || sitekey === "INSERIRE_QUI_LA_TURNSTILE_SITE_KEY") {
        console.error("Turnstile site key non configurata in SF_CONFIG.turnstileSiteKey");
        return;
      }
      try {
        widgetIdRef.current = window.turnstile.render(ref.current, {
          sitekey,
          theme: theme || "light",
          callback: (token) => { onToken && onToken(token); },
          "expired-callback": () => { onExpired && onExpired(); },
          "error-callback": () => { onError && onError(); },
        });
      } catch (e) {
        console.error("Turnstile render error", e);
      }
    };

    if (window._sfTurnstile.apiReady && window.turnstile) {
      mount();
    } else {
      window._sfTurnstile.pendingMounts.push(mount);
    }

    return () => {
      try {
        if (widgetIdRef.current && window.turnstile) {
          window.turnstile.remove(widgetIdRef.current);
        }
      } catch(_) {}
      widgetIdRef.current = null;
    };
  // eslint-disable-next-line
  }, []);

  return <div ref={ref} style={{ minHeight: 65 }} />;
}

// ----- helper edge function call -----
async function _callAuthFn(name, payload) {
  const cfg = window.SF_CONFIG || {};
  const url = `${cfg.url}/functions/v1/${name}`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${cfg.anonKey}`,
    },
    body: JSON.stringify(payload || {}),
  });
  if (!res.ok) {
    let body = null;
    try { body = await res.json(); } catch(_) {}
    throw new Error(body?.error || `${name} HTTP ${res.status}`);
  }
  return res.json();
}

function fmtBlockMessage(remainingSeconds) {
  if (!remainingSeconds || remainingSeconds <= 0) return "Riprova tra qualche istante";
  const mins = Math.ceil(remainingSeconds / 60);
  if (mins <= 1) return "Troppi tentativi. Riprova tra meno di 1 minuto";
  return `Troppi tentativi. Riprova tra ${mins} minuti`;
}

/* ============================================================
   LoginField
   ============================================================ */

function LoginField({ label, type = "text", value, onChange, placeholder, dark, accent, autoFocus, onKey, disabled }) {
  const [focus, setFocus] = useState(false);
  const [show, setShow] = useState(false);
  const isPw = type === "password";
  const t = isPw && show ? "text" : type;
  return (
    <label style={{ display: 'block' }}>
      <span style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 7,
        color: dark ? 'var(--ad-text-2)' : 'var(--ink-2)', letterSpacing: '.01em' }}>{label}</span>
      <span style={{ position: 'relative', display: 'block' }}>
        <input type={t} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
          autoFocus={autoFocus} onKeyDown={onKey} disabled={disabled}
          onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
          style={{ width: '100%', padding: '12px 14px', paddingRight: isPw ? 42 : 14, fontSize: 14.5, fontWeight: 500,
            borderRadius: 'var(--r-md)', outline: 'none', transition: 'box-shadow .15s, background .15s, border-color .15s',
            color: dark ? 'var(--ad-text)' : 'var(--ink)',
            background: dark ? focus ? '#1f2530' : '#171c25' : focus ? '#fff' : 'var(--surface-2)',
            border: '1.5px solid ' + (focus ? accent : dark ? 'var(--ad-line)' : 'var(--line)'),
            boxShadow: focus ? '0 0 0 4px color-mix(in srgb, ' + accent + ' 16%, transparent)' : 'none',
            opacity: disabled ? 0.6 : 1 }} />
        {isPw &&
          <button type="button" onClick={() => setShow((s) => !s)} tabIndex={-1}
            style={{ position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)', padding: 8,
              color: dark ? 'var(--ad-text-2)' : 'var(--ink-3)', display: 'flex' }}>
            <Icon name={show ? 'eyeOff' : 'eye'} size={18} />
          </button>
        }
      </span>
    </label>);
}

/* ============================================================
   LoginPanel (commerciale / backoffice)
   ============================================================ */

function LoginPanel({ role, onLogin }) {
  const r = RUOLI[role];
  const accent = r.color;
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const submit = async () => {
    if (!email.trim() || !pw.trim()) { setError('Inserisci email e password'); return; }
    setLoading(true);
    setError('');

    const emailNorm = email.trim().toLowerCase();

    try {
      // 1) Precheck rate limit
      const pre = await _callAuthFn('auth-precheck', { email: emailNorm });
      if (!pre.ok) {
        if (pre.blocked) {
          setError(fmtBlockMessage(pre.remainingSeconds));
        } else {
          setError('Errore verifica accesso');
        }
        setLoading(false);
        return;
      }

      // 2) Tentativo login Supabase
      let success = false;
      let profile = null;
      let authError = null;
      try {
        const out = await window.AuthAPI.signIn(emailNorm, pw);
        profile = out.profile;
        success = true;
      } catch (e) {
        authError = e;
      }

      // 3) Report esito
      let report = null;
      try {
        report = await _callAuthFn('auth-report', { email: emailNorm, success });
      } catch (_) { /* non bloccare */ }

      if (!success) {
        if (report?.blocked) {
          setError(fmtBlockMessage(report.remainingSeconds));
        } else {
          const left = report?.attempts ? Math.max(0, 5 - report.attempts) : null;
          setError(
            (authError?.message || 'Credenziali non valide') +
            (left != null && left > 0 ? ` — ${left} tentativ${left===1?'o':'i'} rimasti` : '')
          );
        }
        setLoading(false);
        return;
      }

      // 4) Verifica ruolo
      if (profile.role !== role && profile.ruolo !== role) {
        await window.AuthAPI.signOut();
        setError('Le tue credenziali non corrispondono al ruolo selezionato');
        setLoading(false);
        return;
      }
      window.CURRENT_USER = profile;
      onLogin(profile.role || profile.ruolo);
    } catch(e) {
      console.error('login error', e);
      setError(e.message || 'Errore di connessione');
      setLoading(false);
    }
  };

  return (
    <div style={{ width: '50%', flexShrink: 0, padding: '4px 2px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 6 }}>
        <span style={{ width: 9, height: 9, borderRadius: 99, background: accent }} />
        <span style={{ fontSize: 13, fontWeight: 800, color: accent, letterSpacing: '.04em', textTransform: 'uppercase' }}>
          Accesso {r.label}
        </span>
      </div>
      <h2 style={{ margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 25, fontWeight: 800, letterSpacing: '-.02em', color: 'var(--ink)' }}>
        Bentornato
      </h2>
      <p style={{ margin: '0 0 22px', fontSize: 13.5, color: 'var(--ink-3)' }}>{r.desc}</p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        <LoginField label="Email aziendale" value={email} onChange={e => { setEmail(e); setError(''); }}
          placeholder="nome@menabue.it" accent={accent} disabled={loading} />
        <LoginField label="Password" type="password" value={pw} onChange={e => { setPw(e); setError(''); }}
          placeholder="••••••••" accent={accent} onKey={(e) => e.key === 'Enter' && submit()} disabled={loading} />
      </div>

      {error && (
        <div style={{ marginTop: 12, padding: '10px 13px', borderRadius: 'var(--r-md)',
          background: 'var(--red-tint)', border: '1px solid var(--red-tint-2)',
          fontSize: 13, fontWeight: 600, color: 'var(--red)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="alertCircle" size={16} />
          <span>{error}</span>
        </div>
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '16px 0 20px' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-2)', cursor: 'pointer' }}>
          <span onClick={() => setRemember((v) => !v)} style={{ width: 18, height: 18, borderRadius: 5,
            border: '1.5px solid ' + (remember ? accent : 'var(--line)'), background: remember ? accent : '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', transition: '.15s' }}>
            {remember && <Icon name="check" size={13} stroke={2.6} style={{ color: '#fff' }} />}
          </span>
          Ricordami
        </label>
        <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>
          Password dimenticata? Contatta l'admin
        </span>
      </div>

      <Btn full size="lg" onClick={submit} iconRight="arrowRight" disabled={loading}
        style={{ background: 'var(--red)', boxShadow: '0 6px 18px -6px rgba(200,16,46,.5)' }}>
        {loading ? 'Accesso in corso…' : 'Accedi'}
      </Btn>
    </div>);
}

/* ============================================================
   AdminFace
   ============================================================ */

function AdminFace({ onLogin, onBack, visible }) {
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const submit = async () => {
    if (!email.trim() || !pw.trim()) { setError('Inserisci email e password'); return; }
    setLoading(true);
    setError('');

    const emailNorm = email.trim().toLowerCase();

    try {
      const pre = await _callAuthFn('auth-precheck', { email: emailNorm });
      if (!pre.ok) {
        if (pre.blocked) setError(fmtBlockMessage(pre.remainingSeconds));
        else setError('Errore verifica accesso');
        setLoading(false);
        return;
      }

      let success = false, profile = null, authError = null;
      try {
        const out = await window.AuthAPI.signIn(emailNorm, pw);
        profile = out.profile;
        success = true;
      } catch (e) { authError = e; }

      let report = null;
      try { report = await _callAuthFn('auth-report', { email: emailNorm, success }); } catch(_){}

      if (!success) {
        if (report?.blocked) {
          setError(fmtBlockMessage(report.remainingSeconds));
        } else {
          const left = report?.attempts ? Math.max(0, 5 - report.attempts) : null;
          setError(
            (authError?.message || 'Credenziali admin non valide') +
            (left != null && left > 0 ? ` — ${left} tentativ${left===1?'o':'i'} rimasti` : '')
          );
        }
        setLoading(false);
        return;
      }

      const role = profile.role || profile.ruolo;
      if (role !== 'admin') {
        await window.AuthAPI.signOut();
        setError('Queste credenziali non sono admin');
        setLoading(false);
        return;
      }
      window.CURRENT_USER = profile;
      onLogin('admin');
    } catch(e) {
      console.error('admin login error', e);
      setError(e.message || 'Errore di connessione');
      setLoading(false);
    }
  };

  return (
    <div style={{ position: 'absolute', inset: 0, borderRadius: 'var(--r-xl)', padding: '34px 38px',
      background: 'linear-gradient(165deg, #161a22 0%, #0e1218 100%)', border: '1px solid var(--ad-line)',
      transform: 'rotateY(180deg)', boxShadow: 'var(--sh-card)',
      opacity: visible ? 1 : 0, pointerEvents: visible ? 'auto' : 'none', transition: 'opacity .14s linear .42s',
      display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -80, right: -60, width: 260, height: 260, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,64,90,.20), transparent 70%)', pointerEvents: 'none' }} />
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,64,90,.14)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ad-red)' }}>
            <Icon name="shield" size={19} />
          </span>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--ad-red)', letterSpacing: '.12em' }}>MODALITÀ ADMIN</div>
            <div style={{ fontSize: 11.5, color: 'var(--ad-text-2)' }}>Accesso riservato</div>
          </div>
        </div>
        <button onClick={onBack} title="Torna indietro" style={{ width: 32, height: 32, borderRadius: 8,
          color: 'var(--ad-text-2)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid var(--ad-line)' }}>
          <Icon name="refresh" size={16} />
        </button>
      </div>

      <h2 style={{ position: 'relative', margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 24,
        fontWeight: 800, letterSpacing: '-.02em', color: 'var(--ad-text)' }}>Console di controllo</h2>
      <p style={{ position: 'relative', margin: '0 0 22px', fontSize: 13, color: 'var(--ad-text-2)' }}>
        Gestione completa di prodotti, prezzi e utenti.
      </p>

      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <LoginField label="Email amministratore" value={email} onChange={e => { setEmail(e); setError(''); }} dark accent="var(--ad-red)" disabled={loading} />
        <LoginField label="Password" type="password" value={pw} onChange={e => { setPw(e); setError(''); }} placeholder="••••••••" dark accent="var(--ad-red)" onKey={(e) => e.key === 'Enter' && submit()} disabled={loading} />
      </div>

      {error && (
        <div style={{ marginTop: 12, padding: '10px 13px', borderRadius: 'var(--r-md)',
          background: 'rgba(255,64,90,.12)', border: '1px solid rgba(255,64,90,.3)',
          fontSize: 13, fontWeight: 600, color: 'var(--ad-red)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="alertCircle" size={16} />
          <span>{error}</span>
        </div>
      )}

      <div style={{ position: 'relative', marginTop: 'auto', paddingTop: 22 }}>
        <Btn full size="lg" onClick={submit} icon="lock" disabled={loading}
          style={{ background: 'var(--ad-red)', color: '#fff', boxShadow: '0 8px 22px -8px rgba(255,64,90,.6)' }}>
          {loading ? 'Verifica in corso…' : 'Sblocca console'}
        </Btn>
        <div style={{ marginTop:14, fontSize:11.5, color:'var(--ad-text-2)', textAlign:'center', opacity:.7 }}>
          Recovery OTP via email in arrivo prossimamente
        </div>
      </div>
    </div>);
}

/* ============================================================
   TurnstileGate — schermata full-screen prima del login
   ============================================================ */

function TurnstileGate({ onPass }) {
  const [status, setStatus] = useState('waiting'); // waiting | verifying | error
  const [errorMsg, setErrorMsg] = useState('');

  const onToken = async (token) => {
    setStatus('verifying');
    setErrorMsg('');
    try {
      const r = await _callAuthFn('verify-turnstile', { token });
      if (r.success) {
        onPass();
      } else {
        setStatus('error');
        setErrorMsg('Verifica fallita. Ricarica la pagina per riprovare.');
      }
    } catch (e) {
      console.error('turnstile verify error', e);
      setStatus('error');
      setErrorMsg('Errore di connessione. Ricarica la pagina.');
    }
  };

  const onExpired = () => {
    setStatus('waiting');
  };

  const onError = () => {
    setStatus('error');
    setErrorMsg('Errore durante la verifica. Ricarica la pagina.');
  };

  return (
    <div style={{ position:'fixed', inset:0, zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center',
      background: 'linear-gradient(160deg, #c8102e 0%, #9c0a22 100%)', color:'#fff' }}>
      {/* Pattern di sfondo */}
      <div style={{ position:'absolute', inset:0, opacity:.08, pointerEvents:'none',
        backgroundImage:'radial-gradient(circle at 1px 1px, #fff 1px, transparent 0)', backgroundSize:'26px 26px' }} />
      <div style={{ position:'absolute', right:-180, bottom:-140, color:'rgba(255,255,255,.05)', pointerEvents:'none' }}>
        <Icon name="forklift" size={620} stroke={0.4} />
      </div>

      <div style={{ position:'relative', display:'flex', flexDirection:'column', alignItems:'center', gap:30, maxWidth:440, padding:'0 32px', textAlign:'center' }}>
        <img src="assets/menabue-logo-white.png" alt="Menabue Carrelli Elevatori" style={{ height:64, width:'auto' }} />

        <div>
          <h1 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:34, fontWeight:800, letterSpacing:'-.02em', lineHeight:1.05 }}>
            Smart Fleet<br/>Management
          </h1>
          <p style={{ margin:'14px 0 0', fontSize:14.5, color:'rgba(255,255,255,.82)', lineHeight:1.5 }}>
            Stiamo verificando che l'accesso provenga da un dispositivo legittimo.
          </p>
        </div>

        <div style={{ display:'flex', justifyContent:'center', minHeight:78 }}>
          {status === 'verifying' ? (
            <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 24px', borderRadius:99,
              background:'rgba(255,255,255,.16)', fontSize:13.5, fontWeight:700 }}>
              <span className="spin" style={{ width:16, height:16, borderRadius:99, border:'2px solid rgba(255,255,255,.3)',
                borderTopColor:'#fff', display:'inline-block' }} />
              Verifica server in corso…
            </div>
          ) : (
            <TurnstileWidget onToken={onToken} onExpired={onExpired} onError={onError} theme="dark" />
          )}
        </div>

        {errorMsg && (
          <div style={{ padding:'12px 18px', borderRadius:'var(--r-md)', background:'rgba(0,0,0,.25)',
            border:'1px solid rgba(255,255,255,.25)', fontSize:13.5, fontWeight:600 }}>
            <Icon name="alertCircle" size={16} style={{ verticalAlign:'-3px', marginRight:6 }} />
            {errorMsg}
          </div>
        )}

        <div style={{ fontSize:11.5, color:'rgba(255,255,255,.55)', letterSpacing:'.05em' }}>
          Protetto da Cloudflare Turnstile
        </div>
      </div>

      <style>{`
        @keyframes _spin { to { transform: rotate(360deg); } }
        .spin { animation: _spin 0.9s linear infinite; }
      `}</style>
    </div>
  );
}

/* ============================================================
   Login (entrypoint)
   ============================================================ */

/* ============================================================
   LoginMobile — layout dedicato per iPhone/Android
   ============================================================ */

function LoginMobile({ onLogin }) {
  const [mode, setMode] = useState('commerciale');       // 'commerciale' | 'backoffice' | 'admin'
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const isAdmin = mode === 'admin';
  const accent = isAdmin ? 'var(--red)' : (RUOLI[mode]?.color || 'var(--red)');

  const submit = async () => {
    if (!email.trim() || !pw.trim()) { setError('Inserisci email e password'); return; }
    setLoading(true);
    setError('');
    const emailNorm = email.trim().toLowerCase();

    try {
      const pre = await _callAuthFn('auth-precheck', { email: emailNorm });
      if (!pre.ok) {
        if (pre.blocked) setError(fmtBlockMessage(pre.remainingSeconds));
        else setError('Errore verifica accesso');
        setLoading(false);
        return;
      }

      let success = false, profile = null, authError = null;
      try {
        const out = await window.AuthAPI.signIn(emailNorm, pw);
        profile = out.profile;
        success = true;
      } catch (e) { authError = e; }

      let report = null;
      try { report = await _callAuthFn('auth-report', { email: emailNorm, success }); } catch(_){}

      if (!success) {
        if (report?.blocked) {
          setError(fmtBlockMessage(report.remainingSeconds));
        } else {
          const left = report?.attempts ? Math.max(0, 5 - report.attempts) : null;
          setError(
            (authError?.message || 'Credenziali non valide') +
            (left != null && left > 0 ? ` — ${left} tentativ${left===1?'o':'i'} rimasti` : '')
          );
        }
        setLoading(false);
        return;
      }

      const role = profile.role || profile.ruolo;
      if (isAdmin && role !== 'admin') {
        await window.AuthAPI.signOut();
        setError('Queste credenziali non sono admin');
        setLoading(false);
        return;
      }
      if (!isAdmin && role !== mode) {
        await window.AuthAPI.signOut();
        setError('Le tue credenziali non corrispondono al ruolo selezionato');
        setLoading(false);
        return;
      }
      window.CURRENT_USER = profile;
      onLogin(role);
    } catch(e) {
      console.error('mobile login error', e);
      setError(e.message || 'Errore di connessione');
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight:'100dvh', display:'flex', flexDirection:'column',
      background: isAdmin ? 'var(--ad-bg)' : 'var(--surface)',
      padding:'24px 22px 32px',
      transition:'background .3s',
    }}>
      {/* Header: logo + titolo */}
      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', marginBottom:26 }}>
        <img src={isAdmin ? 'assets/menabue-logo-white.png' : 'assets/menabue-logo.png'}
          alt="Menabue Carrelli Elevatori"
          style={{ height:38, width:'auto', marginBottom:16 }} />
        <div style={{ display:'inline-flex', alignItems:'center', gap:7, padding:'4px 11px', borderRadius:99,
          background: isAdmin ? 'rgba(255,64,90,.14)' : 'var(--red-tint)',
          color: isAdmin ? 'var(--ad-red)' : 'var(--red)',
          fontSize:11, fontWeight:800, letterSpacing:'.04em' }}>
          <span style={{ width:6, height:6, borderRadius:99, background:'currentColor' }} />
          {isAdmin ? 'MODALITÀ ADMIN' : 'PIATTAFORMA INTERNA'}
        </div>
      </div>

      <h1 style={{
        margin:'0 0 4px', textAlign:'center',
        fontFamily:'var(--font-display)', fontSize:26, fontWeight:800, letterSpacing:'-.02em',
        color: isAdmin ? 'var(--ad-text)' : 'var(--ink)',
      }}>
        {isAdmin ? 'Console di controllo' : 'Bentornato'}
      </h1>
      <p style={{
        margin:'0 0 22px', textAlign:'center', fontSize:13.5,
        color: isAdmin ? 'var(--ad-text-2)' : 'var(--ink-3)',
      }}>
        {isAdmin ? 'Accesso riservato agli amministratori' : 'Accedi con le tue credenziali aziendali'}
      </p>

      {/* Toggle Commerciale / Backoffice (solo se non admin) */}
      {!isAdmin && (
        <div style={{ position:'relative', display:'flex', padding:4, borderRadius:'var(--r-md)',
          background:'var(--line-2)', marginBottom:20 }}>
          <span style={{ position:'absolute', top:4, bottom:4, width:'calc(50% - 4px)', borderRadius:8,
            background:'#fff', boxShadow:'var(--sh-1)', transition:'transform .35s cubic-bezier(.7,.05,.25,1)',
            transform: mode === 'backoffice' ? 'translateX(100%)' : 'none' }} />
          {[['commerciale','Commerciale'],['backoffice','Back Office']].map(([k,lbl]) => (
            <button key={k} onClick={()=>{ setMode(k); setError(''); }}
              style={{ position:'relative', flex:1, padding:'10px 0', fontSize:13.5, fontWeight:700,
                color: mode===k ? RUOLI[k].color : 'var(--ink-3)', zIndex:1, background:'transparent' }}>
              {lbl}
            </button>
          ))}
        </div>
      )}

      {/* Form */}
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <LoginField label="Email" value={email} onChange={e=>{ setEmail(e); setError(''); }}
          placeholder="nome@menabue.it" accent={accent} dark={isAdmin} disabled={loading} />
        <LoginField label="Password" type="password" value={pw} onChange={e=>{ setPw(e); setError(''); }}
          placeholder="••••••••" accent={accent} dark={isAdmin} disabled={loading}
          onKey={(e)=>e.key==='Enter' && submit()} />
      </div>

      {error && (
        <div style={{ marginTop:12, padding:'10px 13px', borderRadius:'var(--r-md)',
          background: isAdmin ? 'rgba(255,64,90,.12)' : 'var(--red-tint)',
          border: '1px solid ' + (isAdmin ? 'rgba(255,64,90,.3)' : 'var(--red-tint-2)'),
          fontSize:13, fontWeight:600,
          color: isAdmin ? 'var(--ad-red)' : 'var(--red)',
          display:'flex', alignItems:'center', gap:8 }}>
          <Icon name="alertCircle" size={16} />
          <span>{error}</span>
        </div>
      )}

      <div style={{ marginTop:20 }}>
        <Btn full size="lg" onClick={submit} iconRight={isAdmin ? null : "arrowRight"} icon={isAdmin ? "lock" : null} disabled={loading}
          style={{ background: isAdmin ? 'var(--ad-red)' : 'var(--red)',
            boxShadow: isAdmin ? '0 8px 22px -8px rgba(255,64,90,.6)' : '0 6px 18px -6px rgba(200,16,46,.5)' }}>
          {loading ? (isAdmin ? 'Verifica in corso…' : 'Accesso in corso…') : (isAdmin ? 'Sblocca console' : 'Accedi')}
        </Btn>
      </div>

      {/* Toggle admin/back to standard */}
      <div style={{ display:'flex', justifyContent:'center', marginTop:'auto', paddingTop:32 }}>
        {isAdmin ? (
          <button onClick={()=>{ setMode('commerciale'); setError(''); setEmail(''); setPw(''); }}
            style={{ display:'inline-flex', alignItems:'center', gap:7, padding:'10px 20px', borderRadius:99,
              fontSize:12, fontWeight:600, color:'var(--ad-text-2)', background:'transparent',
              border:'1px solid var(--ad-line)' }}>
            <Icon name="refresh" size={13} /> Torna al login standard
          </button>
        ) : (
          <button onClick={()=>{ setMode('admin'); setError(''); setEmail(''); setPw(''); }}
            style={{ display:'inline-flex', alignItems:'center', gap:7, padding:'10px 20px', borderRadius:99,
              fontSize:12, fontWeight:600, color:'var(--ink-4)', background:'transparent',
              border:'1px solid var(--line)' }}>
            <Icon name="lock" size={13} /> Accesso riservato
          </button>
        )}
      </div>

      <div style={{ textAlign:'center', marginTop:20, fontSize:11,
        color: isAdmin ? 'var(--ad-text-2)' : 'var(--ink-4)', opacity:.7 }}>
        © 2026 Menabue · Smart Fleet Management
      </div>
    </div>
  );
}

/* ============================================================
   Login (entrypoint) — sceglie mobile vs desktop
   ============================================================ */

function Login({ onLogin }) {
  const [verified, setVerified] = useState(false);
  const vp = useViewport();
  const [mode, setMode] = useState('commerciale');
  const [flipped, setFlipped] = useState(false);
  const trackX = mode === 'backoffice' ? '-50%' : '0%';

  if (!verified) {
    return <TurnstileGate onPass={() => setVerified(true)} />;
  }

  // Mobile: layout dedicato snello
  if (vp.isMobile) {
    return <LoginMobile onLogin={onLogin} />;
  }

  // Desktop/tablet: layout originale con pannello rosso laterale e flip admin
  return (
    <div className={"login-root" + (flipped ? " is-dark" : "")} style={{
      height: '100vh', display: 'flex', overflow: 'hidden', position: 'relative',
      background: flipped ? 'var(--ad-bg)' : 'var(--bg)', transition: 'background .6s ease' }}>

      <div style={{ width: '44%', maxWidth: 620, position: 'relative', flexShrink: 0,
        background: flipped ?
          'linear-gradient(160deg, #11151c 0%, #0b0e13 100%)' :
          'linear-gradient(160deg, #c8102e 0%, #9c0a22 100%)',
        transition: 'background .6s ease', overflow: 'hidden',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '46px 52px' }}>
        <div style={{ position: 'absolute', inset: 0, opacity: flipped ? .05 : .09, pointerEvents: 'none',
          backgroundImage: 'radial-gradient(circle at 1px 1px, #fff 1px, transparent 0)', backgroundSize: '26px 26px' }} />
        <div style={{ position: 'absolute', right: -120, bottom: -90, color: 'rgba(255,255,255,.06)', transition: '.6s' }}>
          <Icon name="forklift" size={460} stroke={0.5} />
        </div>
        <div style={{ position: 'relative' }}>
          <img src="assets/menabue-logo-white.png" alt="Menabue Carrelli Elevatori" style={{ height: 58, width: 'auto', display: 'block' }} />
        </div>
        <div style={{ position: 'relative' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px', borderRadius: 99,
            background: 'rgba(255,255,255,.12)', color: '#fff', fontSize: 12, fontWeight: 700, letterSpacing: '.04em', marginBottom: 22 }}>
            <span style={{ width: 7, height: 7, borderRadius: 99, background: '#fff', animation: 'pulseDot 2s infinite' }} />
            Piattaforma interna
          </div>
          <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', color: '#fff', fontWeight: 800,
            fontSize: 54, lineHeight: .98, letterSpacing: '-.025em' }}>
            Smart Fleet<br /><span style={{ color: flipped ? 'var(--ad-red)' : '#ffd2d8' }}>Management</span>
          </h1>
          <p style={{ margin: '20px 0 0', maxWidth: 380, color: 'rgba(255,255,255,.78)', fontSize: 15, lineHeight: 1.55 }}>
            Gestione commerciale di mezzi disponibili, pronta consegna, usato, STR e categorie complementari.
          </p>
        </div>
        <div style={{ position: 'relative', display: 'flex', gap: 26, color: 'rgba(255,255,255,.7)', fontSize: 12.5, fontWeight: 600 }}>
          <span>smartfleet-menabue.it</span>
        </div>
      </div>

      <div className="scroll" style={{ flex: 1, display: 'block', position: 'relative', overflowY: 'auto' }}>
        <div style={{ minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32 }}>
          <div style={{ width: '100%', maxWidth: 452, perspective: 2200 }}>
            <div className="login-flip-wrapper" style={{ position: 'relative', transformStyle: 'preserve-3d',
              transition: 'transform .9s cubic-bezier(.7,.05,.25,1)',
              transform: flipped ? 'rotateY(180deg)' : 'rotateY(0deg)',
              minHeight: 668 }}>

              <div style={{ position: 'absolute', inset: 0, borderRadius: 'var(--r-xl)', background: '#fff',
                boxShadow: 'var(--sh-card)', border: '1px solid var(--line)', padding: '32px 38px',
                transform: 'rotateY(0deg)',
                opacity: flipped ? 0 : 1, pointerEvents: flipped ? 'none' : 'auto',
                transition: 'opacity .14s linear .42s', display: 'flex', flexDirection: 'column' }}>

                <div style={{ display:'flex', justifyContent:'center', marginBottom:20 }}>
                  <img src="assets/smartfleet-emblem.png" alt="Smart Fleet Management" style={{ height:64, width:'auto' }} />
                </div>

                <div style={{ position: 'relative', display: 'flex', padding: 4, borderRadius: 'var(--r-md)',
                  background: 'var(--line-2)', marginBottom: 26 }}>
                  <span style={{ position: 'absolute', top: 4, bottom: 4, width: 'calc(50% - 4px)', borderRadius: 8,
                    background: '#fff', boxShadow: 'var(--sh-1)', transition: 'transform .42s cubic-bezier(.7,.05,.25,1)',
                    transform: mode === 'backoffice' ? 'translateX(100%)' : 'none' }} />
                  {[['commerciale', 'Commerciale'], ['backoffice', 'Back Office']].map(([k, lbl]) =>
                    <button key={k} onClick={() => setMode(k)} style={{ position: 'relative', flex: 1, padding: '9px 0',
                      fontSize: 13.5, fontWeight: 700, color: mode === k ? RUOLI[k].color : 'var(--ink-3)', transition: 'color .3s', zIndex: 1 }}>
                      {lbl}
                    </button>
                  )}
                </div>

                <div style={{ overflow: 'hidden', margin: '0 -2px' }}>
                  <div style={{ display: 'flex', width: '200%', transition: 'transform .5s cubic-bezier(.7,.05,.25,1)',
                    transform: 'translateX(' + trackX + ')' }}>
                    <LoginPanel role="commerciale" onLogin={onLogin} />
                    <LoginPanel role="backoffice" onLogin={onLogin} />
                  </div>
                </div>

                <div style={{ height: mode === 'backoffice' ? 52 : 0, opacity: mode === 'backoffice' ? 1 : 0,
                  overflow: 'hidden', transition: 'height .4s, opacity .4s', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                  <button onClick={() => setFlipped(true)} title="Accesso amministratore" className="admin-key"
                    style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 22px', borderRadius: 99,
                      color: 'var(--ink-4)', fontSize: 12, fontWeight: 600, transition: '.2s', opacity: .55, cursor: 'pointer',
                      background: 'transparent', border: '1px solid var(--line)', font: 'inherit', lineHeight: 1 }}
                    onMouseEnter={(e) => {e.currentTarget.style.opacity = 1;e.currentTarget.style.color = 'var(--red)';e.currentTarget.style.borderColor = 'var(--red-tint-2)';}}
                    onMouseLeave={(e) => {e.currentTarget.style.opacity = .55;e.currentTarget.style.color = 'var(--ink-4)';e.currentTarget.style.borderColor = 'var(--line)';}}>
                    <Icon name="lock" size={13} style={{ pointerEvents: 'none' }} />
                    <span style={{ letterSpacing: '.04em', pointerEvents: 'none' }}>accesso riservato</span>
                  </button>
                </div>
              </div>

              <AdminFace onLogin={onLogin} onBack={() => setFlipped(false)} visible={flipped} />
            </div>

            <p style={{ textAlign: 'center', marginTop: 22, fontSize: 12, color: flipped ? 'var(--ad-text-2)' : 'var(--ink-4)', transition: '.6s' }}>© 2026 Menabue · Smart Fleet Management</p>
          </div>
        </div>
      </div>
    </div>);
}

Object.assign(window, { Login });