// AcademiaDental — Auth (Login + Registro + Compra con pago)
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

function AuthScreen({ onAuthed }) {
  // mode: 'login' | 'register' | 'buy' | 'paying' | 'success' | 'failed' | 'forgot' | 'forgot-sent' | 'reset'
  const [mode, setMode] = useStateA('login');
  const [email, setEmail] = useStateA('valentina@odonto.cl');
  const [password, setPassword] = useStateA('demo1234');
  const [newPassword, setNewPassword] = useStateA('');
  const [name, setName] = useStateA('');
  const [err, setErr] = useStateA('');
  const [busy, setBusy] = useStateA(false);
  const [block, setBlock] = useStateA(null);

  // Compra
  const [moduleId, setModuleId] = useStateA('periodoncia');
  const [gateway, setGateway] = useStateA('flow');
  const [refCode, setRefCode] = useStateA('');
  const [paymentStatus, setPaymentStatus] = useStateA(null);

  // Detectar retorno desde pago o link de reseteo
  useEffectA(() => {
    const params = new URLSearchParams(location.search);
    if (params.get('payment') === 'failed') {
      setMode('failed');
      setPaymentStatus({ reason: params.get('reason') || 'desconocido' });
    } else if (params.get('payment') === 'ok') {
      setMode('success');
      setEmail(params.get('email') || '');
      setPaymentStatus({ moduleId: params.get('module') });
    } else if (params.get('welcome') === '1') {
      setMode('success');
      setPaymentStatus({ moduleId: params.get('module') });
    } else if (params.get('reset') === '1' || location.hash.includes('type=recovery')) {
      setMode('reset');
    }
  }, []);

  const modules = window.AD_DATA ? window.AD_DATA.modules : [];
  const selectedMod = useMemoA(() => modules.find(m => m.id === moduleId), [moduleId]);
  const totalCourse = useMemoA(() => modules.reduce((s, m) => s + m.price, 0), [modules]);

  // ---- Submit handlers ----
  async function submitLogin(e) {
    e && e.preventDefault();
    setErr(''); setBusy(true);

    const useSupa = window.AD_CONFIG && window.AD_CONFIG.useSupabase && window.supabase;

    if (useSupa) {
      try {
        const client = window.supabase.createClient(
          window.AD_CONFIG.supabase.url,
          window.AD_CONFIG.supabase.anonKey
        );
        const { data, error } = await client.auth.signInWithPassword({ email, password });
        if (error) {
          setErr(/invalid/i.test(error.message) ? 'Email o contraseña incorrectos' : error.message);
          setBusy(false);
          return;
        }
        const meta = data.user.user_metadata || {};
        const localSession = {
          email: data.user.email,
          name: meta.name || data.user.email.split('@')[0],
          deviceId: window.AD_STATE.thisDeviceId(),
          expires: Date.now() + 7 * 86400000,
          supabaseUserId: data.user.id
        };
        try {
          const users = JSON.parse(localStorage.getItem('ad.users') || '{}');
          let h = 5381;
          for (let i = 0; i < password.length; i++) h = ((h << 5) + h) ^ password.charCodeAt(i);
          users[email.toLowerCase()] = {
            name: localSession.name,
            email: email.toLowerCase(),
            passHash: (h >>> 0).toString(16),
            code: meta.ref_code || 'USER-0000',
            createdAt: Date.now()
          };
          localStorage.setItem('ad.users', JSON.stringify(users));
          const r = window.AD_STATE.login({ email, password });
          if (r.ok) { onAuthed(r.session); return; }
          if (r.blocked === 'session_in_use') { setBlock({ kind: 'session', info: r.activeOn }); setBusy(false); return; }
          if (r.blocked === 'device_limit') { setBlock({ kind: 'devices', devices: r.devices }); setBusy(false); return; }
        } catch (_) {}
        onAuthed(localSession);
        return;
      } catch (err) {
        setErr('Error de conexión: ' + err.message);
        setBusy(false);
        return;
      }
    }

    setTimeout(() => {
      const r = window.AD_STATE.login({ email, password });
      if (r.ok) { onAuthed(r.session); return; }
      if (r.blocked === 'session_in_use') { setBlock({ kind: 'session', info: r.activeOn }); }
      else if (r.blocked === 'device_limit') { setBlock({ kind: 'devices', devices: r.devices }); }
      else setErr(r.error);
      setBusy(false);
    }, 300);
  }

  function submitRegister(e) {
    e && e.preventDefault();
    setErr(''); setBusy(true);
    setTimeout(() => {
      const r = window.AD_STATE.registerUser({ name, email, password });
      if (!r.ok) { setErr(r.error); setBusy(false); return; }
      const r2 = window.AD_STATE.login({ email, password });
      if (r2.ok) onAuthed(r2.session);
      else { setErr('Cuenta creada pero no se pudo iniciar sesión'); setBusy(false); }
    }, 300);
  }

  async function submitBuy(e) {
    e && e.preventDefault();
    setErr('');
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setErr('Email inválido'); return; }
    if (!password || password.length < 6) { setErr('Contraseña mínima 6 caracteres'); return; }
    if (!name || name.length < 2) { setErr('Ingresa tu nombre completo'); return; }
    if (!moduleId) { setErr('Selecciona un módulo'); return; }

    setBusy(true); setMode('paying');
    try {
      const resp = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, name, moduleId, gateway, refCode })
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || 'Error al iniciar pago');
      // Redirect to gateway
      location.href = data.redirectUrl;
    } catch (e) {
      setErr(e.message);
      setMode('buy');
      setBusy(false);
    }
  }

  function takeOver() {
    window.AD_STATE.takeOverSession(email);
    const r = window.AD_STATE.login({ email, password });
    if (r.ok) onAuthed(r.session); else { setErr(r.error || 'Error'); setBlock(null); }
  }
  function removeDevice(id) {
    window.AD_STATE.removeDevice(email, id);
    setBlock(null);
    submitLogin();
  }

  // ---- Recuperación de contraseña ----
  async function submitForgot(e) {
    e && e.preventDefault();
    setErr('');
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setErr('Ingresa un email válido'); return; }
    setBusy(true);

    // Si Supabase está configurado, usa el método nativo
    const useSupa = window.AD_CONFIG && window.AD_CONFIG.useSupabase && window.AD_SUPABASE;
    if (useSupa) {
      try {
        const client = window.supabase.createClient(window.AD_CONFIG.supabase.url, window.AD_CONFIG.supabase.anonKey);
        const { error } = await client.auth.resetPasswordForEmail(email, {
          redirectTo: location.origin + location.pathname + '?reset=1'
        });
        if (error) throw error;
        setMode('forgot-sent');
        setBusy(false);
        return;
      } catch (err) {
        setErr('No pudimos enviar el correo: ' + err.message);
        setBusy(false);
        return;
      }
    }

    // Fallback localStorage: regenera contraseña aleatoria y la muestra
    setTimeout(() => {
      const users = JSON.parse(localStorage.getItem('ad.users') || '{}');
      const user = users[email.toLowerCase()];
      if (!user) {
        setErr('No existe una cuenta con ese email');
        setBusy(false);
        return;
      }
      // Generate temporary password
      const temp = 'temp' + Math.random().toString(36).slice(2, 8);
      // hash via the same algorithm as state.js
      let h = 5381;
      for (let i = 0; i < temp.length; i++) h = ((h << 5) + h) ^ temp.charCodeAt(i);
      user.passHash = (h >>> 0).toString(16);
      users[email.toLowerCase()] = user;
      localStorage.setItem('ad.users', JSON.stringify(users));
      setPaymentStatus({ tempPassword: temp });
      setMode('forgot-sent');
      setBusy(false);
    }, 400);
  }

  async function submitReset(e) {
    e && e.preventDefault();
    setErr('');
    if (!newPassword || newPassword.length < 6) { setErr('Mínimo 6 caracteres'); return; }
    setBusy(true);

    const useSupa = window.AD_CONFIG && window.AD_CONFIG.useSupabase;
    if (useSupa && window.supabase) {
      try {
        const client = window.supabase.createClient(window.AD_CONFIG.supabase.url, window.AD_CONFIG.supabase.anonKey);
        // Supabase auto-detecta el token de recovery del hash de la URL
        const { error } = await client.auth.updateUser({ password: newPassword });
        if (error) throw error;
        history.replaceState(null, '', location.pathname);
        window.AD_TOAST && window.AD_TOAST.show('Contraseña actualizada ✓');
        setMode('login');
        setPassword(newPassword);
        setBusy(false);
      } catch (err) {
        setErr('Error: ' + err.message);
        setBusy(false);
      }
    } else {
      // Fallback (localStorage) — necesita que el email esté en el estado
      setTimeout(() => {
        const users = JSON.parse(localStorage.getItem('ad.users') || '{}');
        const user = users[email.toLowerCase()];
        if (!user) { setErr('Sesión de recuperación inválida'); setBusy(false); return; }
        let h = 5381;
        for (let i = 0; i < newPassword.length; i++) h = ((h << 5) + h) ^ newPassword.charCodeAt(i);
        user.passHash = (h >>> 0).toString(16);
        users[email.toLowerCase()] = user;
        localStorage.setItem('ad.users', JSON.stringify(users));
        history.replaceState(null, '', location.pathname);
        window.AD_TOAST && window.AD_TOAST.show('Contraseña actualizada ✓');
        setMode('login');
        setPassword(newPassword);
        setBusy(false);
      }, 300);
    }
  }

  // ====== RENDER BLOQUEO DE SESIÓN ======
  if (block && block.kind === 'session') {
    return (
      <div className="auth-shell">
        <div style={{textAlign:'center',marginBottom:18}}>
          <div style={{width:64,height:64,borderRadius:'50%',background:'var(--red-pale)',margin:'0 auto 14px',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <Icon.Lock style={{width:28,height:28,color:'var(--red)'}}/>
          </div>
          <h2 className="syne" style={{fontSize:18,fontWeight:600,marginBottom:6}}>Sesión activa en otro dispositivo</h2>
          <p style={{fontSize:13,color:'var(--gray-600)',lineHeight:1.55}}>Solo puedes usar un dispositivo a la vez.</p>
        </div>
        <button className="btn" onClick={takeOver}>Cerrar otra sesión y entrar</button>
        <button className="btn secondary" onClick={() => setBlock(null)}>Volver</button>
      </div>
    );
  }
  if (block && block.kind === 'devices') {
    return (
      <div className="auth-shell">
        <div style={{textAlign:'center',marginBottom:18}}>
          <div style={{width:64,height:64,borderRadius:'50%',background:'var(--red-pale)',margin:'0 auto 14px',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <Icon.Shield style={{width:28,height:28,color:'var(--red)'}}/>
          </div>
          <h2 className="syne" style={{fontSize:18,fontWeight:600}}>Límite de dispositivos alcanzado</h2>
          <p style={{fontSize:13,color:'var(--gray-600)',lineHeight:1.55}}>Máximo 2. Elimina uno para continuar.</p>
        </div>
        {block.devices.map((d) => (
          <div className="device-row" key={d.id}>
            <div className="device-icon">{/iPhone|Android|iPad/i.test(d.name) ? <Icon.Phone style={{width:18,height:18}}/> : <Icon.Laptop style={{width:18,height:18}}/>}</div>
            <div style={{flex:1}}>
              <div style={{fontSize:13,fontWeight:500}}>{d.name}</div>
              <div className="small muted">Última actividad: hace poco</div>
            </div>
            <button className="btn danger small" style={{width:'auto'}} onClick={() => removeDevice(d.id)}>Quitar</button>
          </div>
        ))}
        <div style={{height:10}}/>
        <button className="btn secondary" onClick={() => setBlock(null)}>Volver</button>
      </div>
    );
  }

  // ====== PROCESANDO PAGO ======
  if (mode === 'paying') {
    return (
      <div className="auth-shell" style={{justifyContent:'center',alignItems:'center',textAlign:'center'}}>
        <div style={{width:64,height:64,borderRadius:'50%',background:'var(--teal-pale)',display:'flex',alignItems:'center',justifyContent:'center',marginBottom:18}}>
          <span className="spinner dark" style={{width:24,height:24,borderWidth:3}}/>
        </div>
        <h2 className="syne" style={{fontSize:20,fontWeight:600,marginBottom:6}}>Redirigiendo al pago…</h2>
        <p style={{fontSize:13,color:'var(--gray-600)'}}>Te llevamos a {gateway === 'flow' ? 'Flow' : 'Webpay'} para completar la compra de forma segura.</p>
      </div>
    );
  }

  // ====== PAGO EXITOSO ======
  if (mode === 'success') {
    const mid = paymentStatus && paymentStatus.moduleId;
    const mod = modules.find(m => m.id === mid);
    return (
      <div className="auth-shell" style={{justifyContent:'center',textAlign:'center'}}>
        <div style={{width:74,height:74,borderRadius:'50%',background:'var(--teal-pale)',margin:'0 auto 16px',display:'flex',alignItems:'center',justifyContent:'center'}}>
          <Icon.Check style={{width:34,height:34,color:'var(--teal)'}}/>
        </div>
        <h2 className="syne" style={{fontSize:22,fontWeight:700,marginBottom:8}}>¡Pago confirmado!</h2>
        <p style={{fontSize:14,color:'var(--gray-600)',marginBottom:14,lineHeight:1.55}}>
          {mod ? <>Tu acceso a <strong>{mod.name}</strong> está activo.</> : 'Tu compra está confirmada.'}<br/>
          {email ? <>Te enviamos un correo a <strong>{email}</strong> con los datos.</> : null}
        </p>
        <div className="alert alert-teal" style={{marginBottom:14,textAlign:'left'}}>
          <div className="alert-title">Inicia sesión para entrar al módulo</div>
          Usa el correo y contraseña que ingresaste al comprar.
        </div>
        <button className="btn" onClick={() => { setMode('login'); history.replaceState(null, '', location.pathname); }}>
          Ingresar ahora →
        </button>
      </div>
    );
  }

  // ====== PAGO FALLIDO ======
  if (mode === 'failed') {
    return (
      <div className="auth-shell" style={{justifyContent:'center',textAlign:'center'}}>
        <div style={{width:74,height:74,borderRadius:'50%',background:'var(--red-pale)',margin:'0 auto 16px',display:'flex',alignItems:'center',justifyContent:'center'}}>
          <Icon.X style={{width:34,height:34,color:'var(--red)'}}/>
        </div>
        <h2 className="syne" style={{fontSize:22,fontWeight:700,marginBottom:8}}>Pago no completado</h2>
        <p style={{fontSize:14,color:'var(--gray-600)',marginBottom:18}}>
          {paymentStatus && paymentStatus.reason === 'rechazado' ? 'Tu pago fue rechazado.' : 'Algo salió mal en el proceso de pago.'}
          <br/>No se realizó ningún cobro. Puedes intentar nuevamente.
        </p>
        <button className="btn" onClick={() => { setMode('buy'); history.replaceState(null, '', location.pathname); }}>Intentar de nuevo</button>
        <button className="btn secondary" onClick={() => { setMode('login'); history.replaceState(null, '', location.pathname); }}>Volver al login</button>
      </div>
    );
  }

  // ====== FORM PRINCIPAL ======
  return (
    <div className="auth-shell">
      <div className="auth-logo-block">
        <div className="auth-logo">
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="var(--teal)" strokeWidth="2"><path d="M12 2a5 5 0 1 0 0 10A5 5 0 0 0 12 2z"/><path d="M20 21a8 8 0 1 0-16 0"/></svg>
        </div>
        <div className="logo-mark" style={{fontSize:24,fontWeight:700,fontFamily:'Syne',color:'var(--gray-900)'}}>
          Academia<span style={{color:'var(--teal-light)'}}>Dental</span>
        </div>
        <div className="small muted" style={{marginTop:6}}>Formación clínica basada en evidencia</div>
      </div>

      <div className="tab-row" style={{marginBottom:18}}>
        <button className={'tab-btn ' + (mode === 'login' ? 'active' : '')} onClick={() => { setMode('login'); setErr(''); }}>Ingresar</button>
        <button className={'tab-btn ' + (mode === 'buy' ? 'active' : '')} onClick={() => { setMode('buy'); setErr(''); }}>Comprar acceso</button>
      </div>

      {/* LOGIN */}
      {mode === 'login' ? (
        <form onSubmit={submitLogin}>
          <label className="label">Correo electrónico</label>
          <input className="input-field" type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)}/>
          <label className="label">Contraseña</label>
          <input className={'input-field ' + (err ? 'err' : '')} type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)}/>
          {err ? <div className="small text-red" style={{marginBottom:8}}>{err}</div> : null}
          <div style={{textAlign:'right',marginBottom:14}}>
            <button type="button" onClick={() => { setMode('forgot'); setErr(''); }}
              style={{background:'none',border:'none',color:'var(--teal)',fontSize:12,fontWeight:500,cursor:'pointer',padding:0,textDecoration:'underline'}}>
              ¿Olvidaste tu contraseña?
            </button>
          </div>
          <button className="btn" type="submit" disabled={busy}>{busy ? <span className="spinner"/> : 'Ingresar'}</button>
          <button type="button" className="btn secondary" onClick={() => setMode('buy')}>
            <Icon.Download style={{width:14,height:14}}/> ¿Nuevo? Comprar acceso
          </button>
          <div className="small muted" style={{textAlign:'center',marginTop:14,lineHeight:1.6}}>
            Demo: <strong>valentina@odonto.cl</strong> / <strong>demo1234</strong>
          </div>
        </form>
      ) : null}

      {/* COMPRAR */}
      {mode === 'buy' ? (
        <form onSubmit={submitBuy}>
          <div className="alert alert-teal" style={{marginBottom:16}}>
            <div className="alert-title">🦷 Empieza ya</div>
            Selecciona qué módulo quieres y completa el registro. Tras el pago entras directo al contenido.
          </div>

          <label className="label">Elige qué quieres estudiar</label>
          <div style={{display:'grid',gap:6,marginBottom:14}}>
            {modules.map((m) => (
              <button type="button" key={m.id}
                onClick={() => setModuleId(m.id)}
                className="mod-row"
                style={{
                  borderColor: moduleId === m.id ? 'var(--teal-mid)' : 'var(--gray-200)',
                  borderWidth: moduleId === m.id ? '2px' : '1px',
                  background: moduleId === m.id ? 'var(--teal-pale)' : 'var(--white)'
                }}>
                <div className="mod-info" style={{textAlign:'left'}}>
                  <div className="mod-name">{m.name}</div>
                  <div className="mod-sub">{m.subtitle}</div>
                </div>
                <span style={{fontFamily:'Syne',fontSize:14,fontWeight:600,color:'var(--teal)'}}>${m.price.toLocaleString('es-CL')}</span>
              </button>
            ))}
            <button type="button" onClick={() => setModuleId('curso-completo')}
              className="mod-row"
              style={{
                borderColor: moduleId === 'curso-completo' ? 'var(--amber)' : '#EF9F27',
                borderWidth: '2px',
                background: 'linear-gradient(135deg, #FAEEDA 0%, #F0D49C 100%)'
              }}>
              <div className="mod-info" style={{textAlign:'left'}}>
                <div className="mod-name" style={{color:'var(--amber)'}}>⭐ Curso completo</div>
                <div className="mod-sub">Los 15 módulos · 12 meses · ahorro $300.000+</div>
              </div>
              <span style={{fontFamily:'Syne',fontSize:14,fontWeight:700,color:'var(--amber)'}}>$800.000</span>
            </button>
          </div>

          <label className="label">Nombre completo</label>
          <input className="input-field" type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Ana Pérez"/>
          <label className="label">Correo electrónico</label>
          <input className="input-field" type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@correo.cl"/>
          <label className="label">Contraseña <span className="small muted">(usa esta misma para iniciar sesión luego)</span></label>
          <input className="input-field" type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••"/>

          <label className="label" style={{marginTop:8}}>Código de referido <span className="small muted">(opcional · 10% OFF)</span></label>
          <input className="input-field" type="text" value={refCode} onChange={(e) => setRefCode(e.target.value)} placeholder="VALE-4821"/>

          <label className="label">Método de pago</label>
          <div className="tab-row" style={{marginBottom:14}}>
            <button type="button" className={'tab-btn ' + (gateway === 'flow' ? 'active' : '')} onClick={() => setGateway('flow')}>Flow</button>
            <button type="button" className={'tab-btn ' + (gateway === 'webpay' ? 'active' : '')} onClick={() => setGateway('webpay')}>Webpay</button>
          </div>

          <div className="card" style={{background:'var(--teal-pale)',border:'1px solid var(--teal-mid)',marginBottom:14}}>
            <div className="row-between">
              <span>Total a pagar</span>
              <span style={{fontFamily:'Syne',fontSize:22,fontWeight:700,color:'var(--teal)'}}>
                ${(selectedMod ? selectedMod.price : (moduleId === 'curso-completo' ? 800000 : 0)).toLocaleString('es-CL')}
              </span>
            </div>
            <div className="small muted" style={{marginTop:4}}>Pago único · acceso por 6 meses</div>
          </div>

          {err ? <div className="alert alert-red" style={{marginBottom:10}}>{err}</div> : null}

          <button className="btn" type="submit" disabled={busy}>
            {busy ? <span className="spinner"/> : <>🔒 Ir a pagar {gateway === 'flow' ? 'con Flow' : 'con Webpay'}</>}
          </button>
          <button type="button" className="btn secondary" onClick={() => setMode('login')}>Ya tengo cuenta — iniciar sesión</button>

          <div className="card" style={{marginTop:14,padding:'10px 12px',background:'var(--gray-100)'}}>
            <div className="small muted" style={{lineHeight:1.5}}>
              🔒 Pago 100% seguro · No vemos los datos de tu tarjeta · La cuenta se crea automáticamente al confirmar el pago
            </div>
          </div>
        </form>
      ) : null}

      {/* FORGOT — pedir email */}
      {mode === 'forgot' ? (
        <form onSubmit={submitForgot}>
          <div className="alert alert-teal" style={{marginBottom:14}}>
            <div className="alert-title">Recuperar contraseña</div>
            Ingresa el email de tu cuenta y te enviaremos un enlace para crear una nueva.
          </div>
          <label className="label">Correo electrónico</label>
          <input className="input-field" type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@correo.cl"/>
          {err ? <div className="alert alert-red" style={{marginBottom:10}}>{err}</div> : null}
          <button className="btn" type="submit" disabled={busy}>
            {busy ? <span className="spinner"/> : <><Icon.Send style={{width:14,height:14}}/> Enviar enlace de recuperación</>}
          </button>
          <button type="button" className="btn secondary" onClick={() => { setMode('login'); setErr(''); }}>
            <Icon.Back style={{width:14,height:14}}/> Volver al login
          </button>
        </form>
      ) : null}

      {/* FORGOT-SENT — confirmación */}
      {mode === 'forgot-sent' ? (
        <div style={{textAlign:'center'}}>
          <div style={{width:64,height:64,borderRadius:'50%',background:'var(--teal-pale)',margin:'0 auto 16px',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <Icon.Send style={{width:28,height:28,color:'var(--teal)'}}/>
          </div>
          <h2 className="syne" style={{fontSize:20,fontWeight:600,marginBottom:8}}>Revisa tu correo</h2>
          <p style={{fontSize:13,color:'var(--gray-600)',marginBottom:16,lineHeight:1.55}}>
            Te enviamos un enlace a <strong>{email}</strong>.<br/>
            Haz click en él para crear una contraseña nueva.
          </p>
          {paymentStatus && paymentStatus.tempPassword ? (
            <div className="alert alert-amber" style={{textAlign:'left',marginBottom:14}}>
              <div className="alert-title">Modo demo (sin email)</div>
              Tu nueva contraseña temporal es:<br/>
              <code style={{fontSize:14,background:'rgba(0,0,0,0.05)',padding:'4px 8px',borderRadius:6,display:'inline-block',marginTop:6}}>{paymentStatus.tempPassword}</code><br/>
              <span className="small">Cámbiala apenas inicies sesión.</span>
            </div>
          ) : (
            <div className="alert alert-teal" style={{textAlign:'left',marginBottom:14}}>
              ¿No te llega? Revisa la carpeta de spam o promociones.
            </div>
          )}
          <button className="btn" onClick={() => { setMode('login'); setErr(''); }}>Volver al login</button>
        </div>
      ) : null}

      {/* RESET — nueva contraseña desde link de email */}
      {mode === 'reset' ? (
        <form onSubmit={submitReset}>
          <div style={{textAlign:'center',marginBottom:16}}>
            <div style={{width:60,height:60,borderRadius:'50%',background:'var(--teal-pale)',margin:'0 auto 12px',display:'flex',alignItems:'center',justifyContent:'center'}}>
              <Icon.Lock style={{width:26,height:26,color:'var(--teal)'}}/>
            </div>
            <h2 className="syne" style={{fontSize:20,fontWeight:600,marginBottom:6}}>Nueva contraseña</h2>
            <p className="small muted">Crea una contraseña que recuerdes fácil.</p>
          </div>
          <label className="label">Nueva contraseña</label>
          <input className="input-field" type="password" autoComplete="new-password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="Mínimo 6 caracteres"/>
          {err ? <div className="alert alert-red" style={{marginBottom:10}}>{err}</div> : null}
          <button className="btn" type="submit" disabled={busy}>
            {busy ? <span className="spinner"/> : 'Guardar nueva contraseña'}
          </button>
          <button type="button" className="btn secondary" onClick={() => { setMode('login'); history.replaceState(null,'',location.pathname); }}>
            Cancelar
          </button>
        </form>
      ) : null}

      {mode === 'login' || mode === 'buy' ? (
        <div className="card" style={{marginTop:14,padding:'10px 12px'}}>
          <div className="flex" style={{gap:8,alignItems:'center'}}>
            <Icon.Lock style={{width:14,height:14,color:'var(--gray-400)'}}/>
            <div className="small muted">Máx. 2 dispositivos · Sin sesión simultánea · Datos cifrados</div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { AuthScreen });
