const t = window.t || (k => k);
const Auth = () => {
  const {go, login, route} = useApp();
  const [mode, setMode] = useState(route.params?.mode || 'login');
  const [email, setEmail] = useState('');
  const [pass, setPass] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [isInstructor, setIsInstructor] = useState(false);
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const [forgotMsg, setForgotMsg] = useState('');
  const [resetToken, setResetToken] = useState('');

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const token = params.get('reset');
    if (token) {
      setResetToken(token);
      setMode('reset');
      window.history.replaceState({}, '', window.location.pathname);
    }
  }, []);

  const hasBackend = async () => { try { return !!(await window.__backendReady); } catch(e){ return false; } };

  const submit = async (e) => {
    e && e.preventDefault();
    setErr('');
    setForgotMsg('');
    if (mode === 'reset') {
      if (!pass || pass.length < 8) { setErr(t('auth.pass_short')); return; }
      setBusy(true);
      try {
        await window.api.resetPassword(resetToken, pass);
        setForgotMsg(t('auth.reset_ok'));
        setMode('login');
      } catch (er) {
        setErr(er.error === 'token_invalid' ? t('auth.token_invalid') : 'Error: ' + (er.error || 'desconocido'));
      }
      setBusy(false);
      return;
    }
    if (mode === 'forgot') {
      if (!email) { setErr(t('auth.enter_email')); return; }
      setBusy(true);
      try {
        await window.api.forgotPassword(email);
        setForgotMsg(t('auth.forgot_sent'));
      } catch (er) {
        // Show success message even on error to prevent email enumeration
        setForgotMsg(t('auth.forgot_sent'));
      }
      setBusy(false);
      return;
    }
    if (!email || !pass) { setErr(t('auth.fill_all')); return; }
    if (mode === 'signup' && !name) { setErr(t('auth.tell_name')); return; }
    if (mode === 'signup' && !phone) { setErr(t('auth.phone_required') || 'Introduce tu teléfono'); return; }
    if (mode === 'signup' && phone.replace(/[^0-9]/g,'').length < 9) { setErr(t('auth.phone_invalid') || 'Teléfono inválido (mínimo 9 dígitos)'); return; }
    setBusy(true);
    try {
      if (mode === 'signup') {
        // Backend is REQUIRED for registration — no demo fallback
        const backendUp = await window.isBackendReady();
        if (!backendUp) {
          setErr(t('auth.server_unavailable') || 'Servidor no disponible. Inténtalo de nuevo en unos segundos.');
          setBusy(false);
          return;
        }
        try {
          await window.api.register({ email, password: pass, name, license: isInstructor ? 'INSTRUCTOR' : '', phone });
        } catch (er) {
          if (er.error === 'email_taken') { setErr(t('auth.email_taken')); setBusy(false); return; }
          if (er.error === 'password_too_short') { setErr(t('auth.pass_short')); setBusy(false); return; }
          if (er.error === 'network_error') { setErr(t('auth.server_unavailable') || 'Servidor no disponible. Inténtalo de nuevo.'); setBusy(false); return; }
          setErr(er.error || 'No se pudo crear la cuenta'); setBusy(false); return;
        }
      }
      const r = await login(email, pass);
      if (!r || r.ok === false) {
        setErr(r && r.error === 'credentials_invalid' ? t('auth.bad_creds') :
               r && r.error === 'account_blocked' ? t('auth.blocked') :
               (r && r.error) || 'Error al iniciar sesión');
      }
    } finally { setBusy(false); }
  };

  return <div style={{minHeight:'100dvh',display:'flex',padding:'40px 20px',boxSizing:'border-box'}}>
    <div style={{width:'100%',maxWidth:400,margin:'auto'}}>
      <button className="btn btn-ghost btn-sm" onClick={()=>go('landing')} style={{marginBottom:24}}><Icon name="chev_left" size={14}/> {t('auth.back_btn')}</button>
      <div className="card" style={{padding:32}}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:28,fontWeight:600}}><LogoMark size={22}/> AeroPlan</div>
        <h1 className="display" style={{fontSize:30,marginBottom:6}}>{mode==='login'?t('auth.welcome'):mode==='forgot'?t('auth.recover'):mode==='reset'?t('auth.new_password'):t('auth.create_account')}</h1>
        <p style={{color:'var(--ink-dim)',fontSize:14,marginBottom:24}}>{mode==='login'?t('auth.login_subtitle'):mode==='forgot'?t('auth.forgot_subtitle'):mode==='reset'?t('auth.reset_subtitle'):t('auth.signup_subtitle')}</p>
        <form onSubmit={submit} style={{display:'flex',flexDirection:'column',gap:14}}>
          {mode==='signup' && <>
            <div><label className="label">{t('auth.name')}</label><input className="field" value={name} onChange={e=>setName(e.target.value)} placeholder="Jesús Soler"/></div>
            <div><label className="label">{t('auth.phone') || 'Teléfono'}</label><input className="field" inputMode="tel" value={phone} onChange={e=>{const v=e.target.value.replace(/[^0-9+\s()-]/g,'');setPhone(v);}} placeholder="+34 612 345 678" maxLength={18}/></div>
            <label style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer',fontSize:13,color:'var(--ink-dim)',marginTop:4}}>
              <input type="checkbox" checked={isInstructor} onChange={e=>setIsInstructor(e.target.checked)} style={{width:16,height:16,accentColor:'var(--accent)'}}/>
              {t('auth.instructor')}
            </label>
          </>}
          {mode!=='reset' && <div><label className="label">{t('auth.email')}</label><input className="field" value={email} onChange={e=>setEmail(e.target.value)} placeholder="piloto@ejemplo.com"/></div>}
          {mode!=='forgot' && <div><label className="label">{t('auth.password')}</label><input type="password" className="field" value={pass} onChange={e=>setPass(e.target.value)} placeholder="••••••••"/></div>}
          {err && <div style={{color:'var(--err)',fontSize:13}}>{err}</div>}
          {forgotMsg && <div style={{color:'var(--ok)',fontSize:13}}>{forgotMsg}</div>}
          <button className="btn btn-primary" type="submit" disabled={busy} style={{marginTop:6}}>{busy?'…':(mode==='login'?t('auth.login_btn'):mode==='forgot'?t('auth.forgot_btn'):mode==='reset'?t('auth.reset_btn'):t('auth.signup_btn'))}</button>
        </form>
        {mode === 'login' && <div style={{textAlign:'center',marginTop:12}}>
          <button onClick={()=>{setMode('forgot');setErr('');setForgotMsg('');}} style={{color:'var(--ink-dim)',fontSize:13}}>{t('auth.forgot_link')}</button>
        </div>}
        <div style={{textAlign:'center',marginTop:mode==='login'?8:20,fontSize:13,color:'var(--ink-dim)'}}>
          {mode==='login'?<>{t('auth.no_account')} <button onClick={()=>{setMode('signup');setErr('');setForgotMsg('');}} style={{color:'var(--accent)',fontWeight:600}}>{t('auth.signup_link')}</button></>
            :mode==='forgot'?<>{t('auth.remember')} <button onClick={()=>{setMode('login');setErr('');setForgotMsg('');}} style={{color:'var(--accent)',fontWeight:600}}>{t('auth.back')}</button></>
            :mode==='reset'?<><button onClick={()=>{setMode('login');setErr('');setForgotMsg('');}} style={{color:'var(--accent)',fontWeight:600}}>{t('auth.back_login')}</button></>
            :<>{t('auth.has_account')} <button onClick={()=>{setMode('login');setErr('');setForgotMsg('');}} style={{color:'var(--accent)',fontWeight:600}}>{t('auth.login_link')}</button></>}
        </div>
      </div>
    </div>
  </div>;
};
window.Auth = Auth;
