// fp-auth.jsx — Login / Sign-up screen
// Exports: AuthScreen

function AuthScreen() {
  const [mode, setMode] = useState('login'); // 'login' | 'signup' | 'reset'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const submit = async e => {
    e.preventDefault();
    setError(''); setSuccess(''); setLoading(true);
    if (mode === 'login') {
      const { error } = await sbClient.auth.signInWithPassword({ email, password });
      if (error) setError(error.message);
    } else if (mode === 'signup') {
      const { error } = await sbClient.auth.signUp({
        email, password,
        options: { data: { name } },
      });
      if (error) setError(error.message);
      else setSuccess('Revisa tu email para confirmar tu cuenta.');
    } else if (mode === 'reset') {
      const { error } = await sbClient.auth.resetPasswordForEmail(email, {
        redirectTo: window.location.origin,
      });
      if (error) setError(error.message);
      else setSuccess('Te enviamos un enlace para restablecer tu contraseña. Revisa tu email.');
    }
    setLoading(false);
  };

  const switchMode = (m) => { setMode(m); setError(''); setSuccess(''); };

  return (
    <div style={authStyles.page}>
      <div style={authStyles.card}>
        <div style={authStyles.logo}>
          <span style={authStyles.dot} />
          Feed Planner
        </div>
        <p style={authStyles.sub}>
          {mode === 'login' ? 'Ingresa a tu cuenta' : mode === 'signup' ? 'Crea tu cuenta' : 'Recuperar contraseña'}
        </p>

        {error && <div style={authStyles.alert}>{error}</div>}
        {success && <div style={{...authStyles.alert, background:'var(--green-light)', color:'var(--green)', borderColor:'var(--green)' }}>{success}</div>}

        <form onSubmit={submit} style={{display:'flex',flexDirection:'column',gap:12}}>
          {mode === 'signup' && (
            <div style={authStyles.field}>
              <label style={authStyles.label}>Nombre</label>
              <input style={authStyles.input} type="text" placeholder="Tu nombre" value={name} onChange={e=>setName(e.target.value)} required />
            </div>
          )}
          <div style={authStyles.field}>
            <label style={authStyles.label}>Email</label>
            <input style={authStyles.input} type="email" placeholder="tu@email.com" value={email} onChange={e=>setEmail(e.target.value)} required />
          </div>
          {mode !== 'reset' && (
            <div style={authStyles.field}>
              <label style={authStyles.label}>Contraseña</label>
              <input style={authStyles.input} type="password" placeholder="••••••••" value={password} onChange={e=>setPassword(e.target.value)} required minLength={6} />
            </div>
          )}
          {mode === 'login' && (
            <div style={{textAlign:'right',marginTop:-4}}>
              <button type="button" onClick={()=>switchMode('reset')} style={authStyles.link}>
                ¿Olvidaste tu contraseña?
              </button>
            </div>
          )}
          <button type="submit" style={authStyles.btn} disabled={loading}>
            {loading ? <Spinner size={18} color="#fff"/> : (mode === 'login' ? 'Entrar' : mode === 'signup' ? 'Crear cuenta' : 'Enviar enlace')}
          </button>
        </form>

        <div style={authStyles.toggle}>
          {mode === 'login' ? (
            <><span style={{color:'var(--ink-muted)'}}>¿Sin cuenta?</span>{' '}
            <button onClick={()=>switchMode('signup')} style={authStyles.link}>Regístrate</button></>
          ) : (
            <><span style={{color:'var(--ink-muted)'}}>¿Ya tienes cuenta?</span>{' '}
            <button onClick={()=>switchMode('login')} style={authStyles.link}>Inicia sesión</button></>
          )}
        </div>
      </div>
    </div>
  );
}

const authStyles = {
  page: { minHeight:'100vh', background:'var(--cream)', display:'flex', alignItems:'center', justifyContent:'center', padding:24 },
  card: { background:'#fff', borderRadius:20, padding:'40px 36px', width:'100%', maxWidth:400, boxShadow:'0 8px 40px rgba(28,25,23,0.12)', display:'flex', flexDirection:'column', gap:20 },
  logo: { fontFamily:"'Playfair Display',serif", fontSize:24, fontWeight:600, letterSpacing:'-0.3px', display:'flex', alignItems:'center', gap:8 },
  dot:  { width:9, height:9, borderRadius:'50%', background:'var(--accent)', display:'inline-block', flexShrink:0 },
  sub:  { fontSize:14, color:'var(--ink-soft)', marginTop:-12 },
  field:{ display:'flex', flexDirection:'column', gap:6 },
  label:{ fontSize:11.5, fontWeight:600, color:'var(--ink-soft)', letterSpacing:'0.06em', textTransform:'uppercase' },
  input:{ background:'var(--cream)', border:'1px solid var(--cream-dark)', borderRadius:9, padding:'11px 13px', fontFamily:"'DM Sans',sans-serif", fontSize:14, color:'var(--ink)', outline:'none', width:'100%' },
  btn:  { background:'var(--accent)', color:'#fff', border:'none', borderRadius:10, padding:'13px', fontFamily:"'DM Sans',sans-serif", fontSize:14, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8, transition:'opacity 0.15s' },
  alert:{ background:'var(--accent-light)', color:'var(--accent)', border:'1px solid var(--accent-mid)', borderRadius:9, padding:'10px 13px', fontSize:13, lineHeight:1.4 },
  toggle:{ textAlign:'center', fontSize:13 },
  link: { background:'none', border:'none', color:'var(--accent)', fontWeight:600, cursor:'pointer', fontFamily:'inherit', fontSize:13, padding:0 },
};

Object.assign(window, { AuthScreen });
