const { useState, useEffect } = React;

function Entrar() {
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');
  const [showPass, setShowPass] = useState(false);

  // Redireciona se já logado
  useEffect(() => {
    const token = localStorage.getItem('sx_token');
    if (token) window.location.href = '/minha-conta';
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    if (!email || !password) { setError('Preencha email e senha.'); return; }
    setLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Erro ao autenticar.');
      localStorage.setItem('sx_token', data.token);
      localStorage.setItem('sx_user', JSON.stringify(data.user));
      window.location.href = '/minha-conta';
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  const inputStyle = {
    width: '100%', padding: '14px 16px', background: '#14141C',
    border: '1px solid rgba(255,255,255,0.1)', borderRadius: 10,
    color: '#EFEFEF', fontFamily: "'Inter',sans-serif", fontSize: 15,
    outline: 'none', transition: 'border-color 0.2s',
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', padding: '24px', background: 'radial-gradient(ellipse at 50% 0%, rgba(123,63,242,0.08) 0%, transparent 60%), #0A0A0F' }}>
      <div style={{ width: '100%', maxWidth: 400 }}>

        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <a href="/" style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <img src="/assets/sx_fill.svg" style={{ height: 36, filter: 'brightness(0) invert(1)' }} alt="SX" />
            <img src="/assets/Logo-Sexy.svg" style={{ height: 16, filter: 'brightness(0) invert(1)', opacity: 0.7 }} alt="SEXY" />
          </a>
        </div>

        {/* Card */}
        <div style={{ background: '#14141C', border: '1px solid rgba(255,255,255,0.07)', borderRadius: 20, padding: '36px 32px' }}>
          <h1 style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 24, color: '#EFEFEF', textTransform: 'uppercase', letterSpacing: '0.02em', marginBottom: 6 }}>Entrar</h1>
          <p style={{ fontSize: 13, color: '#9999B2', fontFamily: "'Inter',sans-serif", marginBottom: 28, lineHeight: 1.5 }}>Acesse sua conta de assinante para ver os benefícios.</p>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#9999B2', letterSpacing: '0.06em', textTransform: 'uppercase', fontFamily: "'Inter',sans-serif", marginBottom: 6 }}>Email</label>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="seu@email.com"
                required
                style={inputStyle}
                onFocus={e => e.target.style.borderColor='rgba(123,63,242,0.5)'}
                onBlur={e => e.target.style.borderColor='rgba(255,255,255,0.1)'}
              />
            </div>

            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#9999B2', letterSpacing: '0.06em', textTransform: 'uppercase', fontFamily: "'Inter',sans-serif", marginBottom: 6 }}>Senha</label>
              <div style={{ position: 'relative' }}>
                <input
                  type={showPass ? 'text' : 'password'}
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  placeholder="••••••••"
                  required
                  style={{ ...inputStyle, paddingRight: 44 }}
                  onFocus={e => e.target.style.borderColor='rgba(123,63,242,0.5)'}
                  onBlur={e => e.target.style.borderColor='rgba(255,255,255,0.1)'}
                />
                <button type="button" onClick={() => setShowPass(!showPass)} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#55556A', padding: 4 }}>
                  {showPass
                    ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                    : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  }
                </button>
              </div>
            </div>

            {error && (
              <div style={{ background: 'rgba(255,22,117,0.1)', border: '1px solid rgba(255,22,117,0.25)', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#FF4D97', fontFamily: "'Inter',sans-serif" }}>{error}</div>
            )}

            <button type="submit" disabled={loading}
              style={{ width: '100%', padding: '14px', background: loading ? 'rgba(123,63,242,0.4)' : 'linear-gradient(135deg,#7B3FF2,#FF1675)', border: 'none', borderRadius: 10, color: '#fff', fontFamily: "'Space Grotesk',sans-serif", fontSize: 15, fontWeight: 700, cursor: loading ? 'not-allowed' : 'pointer', transition: 'opacity 0.2s', marginTop: 6 }}>
              {loading ? 'Entrando...' : 'Entrar na conta'}
            </button>
          </form>

          <div style={{ marginTop: 24, paddingTop: 20, borderTop: '1px solid rgba(255,255,255,0.06)', textAlign: 'center' }}>
            <span style={{ fontSize: 13, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>Ainda não é assinante? </span>
            <a href="/assinar" style={{ fontSize: 13, fontWeight: 600, color: '#7B3FF2', fontFamily: "'Inter',sans-serif" }}>Assinar agora</a>
          </div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 20 }}>
          <a href="/" style={{ fontSize: 12, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>← Voltar para o início</a>
        </div>
      </div>
    </div>
  );
}
