// ===== Elejemais — Auth (Login / Recuperar senha) =====

const { useState: useState_auth } = React;

function Auth() {
  const [mode, setMode]       = useState_auth('login'); // 'login' | 'reset'
  const [email, setEmail]     = useState_auth('');
  const [password, setPass]   = useState_auth('');
  const [loading, setLoading] = useState_auth(false);
  const [error, setError]     = useState_auth('');
  const [success, setSuccess] = useState_auth('');

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    setLoading(true);
    try {
      if (mode === 'login') {
        await window.API.signIn(email, password);
      } else {
        await window.API.resetPassword(email);
        setSuccess('Link de redefinição enviado para ' + email);
      }
    } catch (err) {
      const msgs = {
        'Invalid login credentials': 'E-mail ou senha incorretos.',
        'Email not confirmed':       'Confirme seu e-mail antes de entrar.',
        'Email logins are disabled': 'Login por e-mail não está ativado. Ative em Authentication → Providers no Supabase.',
      };
      const match = Object.entries(msgs).find(([k]) => err.message?.includes(k));
      setError(match ? match[1] : (err.message || 'Erro inesperado. Tente novamente.'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fadein" style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--bg)',
      padding: '24px',
    }}>
      <div style={{ width: '100%', maxWidth: 400, display: 'flex', flexDirection: 'column', gap: 24 }}>

        {/* Logo */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          <img src="/Images/logo.jpg" alt="Elejemais" style={{ width: 44, height: 44, objectFit: "contain" }} />
          <div className="serif" style={{ fontSize: 28, letterSpacing: '-0.01em', lineHeight: 1 }}>Elejemais</div>
          <div className="eyebrow">Plataforma de campanha</div>
        </div>

        {/* Card */}
        <div className="card" style={{ padding: '28px 32px', display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div>
            <h2 className="serif" style={{ fontSize: 22, margin: '0 0 4px', letterSpacing: '-0.01em' }}>
              {mode === 'login' ? 'Entrar na conta' : 'Recuperar senha'}
            </h2>
            <p className="dim" style={{ margin: 0, fontSize: 13, lineHeight: 1.55 }}>
              {mode === 'login'
                ? 'Acesse sua plataforma de campanha.'
                : 'Informe seu e-mail para receber o link de redefinição.'}
            </p>
          </div>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 13, fontWeight: 500 }}>E-mail</label>
              <input
                className="input"
                type="email"
                placeholder="seu@email.com"
                value={email}
                onChange={e => setEmail(e.target.value)}
                required
                autoFocus
              />
            </div>

            {mode === 'login' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <label style={{ fontSize: 13, fontWeight: 500 }}>Senha</label>
                  <button
                    type="button"
                    onClick={() => go('reset')}
                    style={{
                      background: 'none', border: 'none', cursor: 'pointer',
                      fontSize: 12, color: 'var(--accent)', padding: 0,
                    }}
                  >
                    Esqueci a senha
                  </button>
                </div>
                <input
                  className="input"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={e => setPass(e.target.value)}
                  required
                />
              </div>
            )}

            {error && (
              <div style={{
                padding: '10px 14px', borderRadius: 8,
                background: 'oklch(0.97 0.02 20)', color: 'oklch(0.42 0.18 20)',
                fontSize: 13, lineHeight: 1.5,
              }}>
                {error}
              </div>
            )}

            {success && (
              <div style={{
                padding: '10px 14px', borderRadius: 8,
                background: 'var(--accent-soft)', color: 'var(--accent-strong)',
                fontSize: 13, lineHeight: 1.5,
              }}>
                {success}
              </div>
            )}

            <button
              className="btn btn--primary btn--block"
              type="submit"
              disabled={loading}
              style={{ marginTop: 4 }}
            >
              {loading
                ? (mode === 'login' ? 'Entrando…' : 'Enviando…')
                : (mode === 'login' ? 'Entrar' : 'Enviar link de redefinição')}
            </button>
          </form>

          {mode === 'reset' && (
            <div style={{ textAlign: 'center', fontSize: 13 }}>
              <button onClick={() => go('login')} style={{
                background: 'none', border: 'none', cursor: 'pointer',
                color: 'var(--accent)', fontSize: 13, padding: 0,
              }}>
                ← Voltar para o login
              </button>
            </div>
          )}
        </div>

        <div className="dim" style={{ textAlign: 'center', fontSize: 12 }}>
          © 2026 Elejemais · Dados protegidos por LGPD
        </div>
      </div>
    </div>
  );
}

window.Auth = Auth;
