// auth.jsx — écran de connexion / inscription
const { useState: useAu } = React;

function AuthScreen({ t, onAuthed }) {
  const [mode, setMode] = useAu('signin'); // signin | signup
  const [email, setEmail] = useAu('');
  const [password, setPassword] = useAu('');
  const [loading, setLoading] = useAu(false);
  const [err, setErr] = useAu('');
  const [info, setInfo] = useAu('');

  const submit = async () => {
    setErr(''); setInfo('');
    if (!email || !password) { setErr('Renseigne ton email et ton mot de passe.'); return; }
    if (password.length < 6) { setErr('Mot de passe : 6 caractères minimum.'); return; }
    setLoading(true);
    try {
      if (mode === 'signup') {
        await window.FuelFitDB.signUp(email, password);
        // Selon la config Supabase, l'utilisateur peut être connecté direct ou devoir confirmer l'email.
        const session = await window.FuelFitDB.getSession();
        if (session) onAuthed(session);
        else setInfo('Compte créé ! Connecte-toi maintenant.'), setMode('signin');
      } else {
        const { session } = await window.FuelFitDB.signIn(email, password);
        onAuthed(session);
      }
    } catch (e) {
      setErr(e.message || 'Une erreur est survenue.');
    }
    setLoading(false);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: t.bg, display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', padding: '24px', fontFamily: '"Manrope", system-ui, sans-serif' }}>
      <div style={{ width: '100%', maxWidth: 360 }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ width: 72, height: 72, borderRadius: 22, margin: '0 auto 16px', background: `color-mix(in srgb, ${t.green} 18%, ${t.surface})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="spark" size={36} color={t.green} fill />
          </div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, color: t.text, fontFamily: 'Space Grotesk, sans-serif' }}>FuelFit</h1>
          <p style={{ margin: '6px 0 0', fontSize: 14, color: t.textMuted }}>Ton coach nutrition personnel</p>
        </div>

        {/* Onglets */}
        <div style={{ display: 'flex', gap: 4, padding: 4, borderRadius: 14, background: t.surfaceAlt, marginBottom: 18 }}>
          {[['signin', 'Connexion'], ['signup', 'Créer un compte']].map(([m, lbl]) => (
            <button key={m} onClick={() => { setMode(m); setErr(''); setInfo(''); }} style={{
              flex: 1, padding: '10px', borderRadius: 11, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5,
              background: mode === m ? t.surface : 'transparent', color: mode === m ? t.text : t.textMuted,
              boxShadow: mode === m ? t.shadow : 'none' }}>{lbl}</button>
          ))}
        </div>

        <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" autoCapitalize="none"
          style={{ width: '100%', padding: '14px 15px', borderRadius: 14, marginBottom: 10, background: t.surface,
            border: `1px solid ${t.border}`, color: t.text, fontFamily: 'inherit', fontSize: 15, outline: 'none', boxSizing: 'border-box' }} />
        <input type="password" value={password} onChange={e => setPassword(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') submit(); }} placeholder="Mot de passe"
          style={{ width: '100%', padding: '14px 15px', borderRadius: 14, marginBottom: 14, background: t.surface,
            border: `1px solid ${t.border}`, color: t.text, fontFamily: 'inherit', fontSize: 15, outline: 'none', boxSizing: 'border-box' }} />

        {err && <div style={{ fontSize: 13, color: t.red, marginBottom: 12, lineHeight: 1.4 }}>{err}</div>}
        {info && <div style={{ fontSize: 13, color: t.green, marginBottom: 12, lineHeight: 1.4 }}>{info}</div>}

        <button onClick={submit} disabled={loading} style={{ width: '100%', padding: '15px', borderRadius: 14, border: 'none',
          cursor: 'pointer', background: t.green, color: t.onAccent, fontWeight: 700, fontSize: 15.5, fontFamily: 'inherit', opacity: loading ? 0.6 : 1 }}>
          {loading ? 'Patiente…' : (mode === 'signup' ? 'Créer mon compte' : 'Se connecter')}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen });
