/* ============================================================================
 * FLUXO ZAP · Tela de Login Premium
 * ========================================================================= */

const LoginScreen = ({ onLoginSuccess }) => {
  const t = useTheme();
  const { showToast } = useToast();
  
  const [isRegister, setIsRegister] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  
  // Form states
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [passwordConfirm, setPasswordConfirm] = React.useState('');
  
  // Feedback states
  const [errorMsg, setErrorMsg] = React.useState('');
  const [successMsg, setSuccessMsg] = React.useState('');
  const [verifyNotice, setVerifyNotice] = React.useState(false);

  const isBloom = t.name === 'BLOOM';

  const handleLogin = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      setErrorMsg('Por favor, preencha todos os campos.');
      return;
    }

    setLoading(true);
    setErrorMsg('');
    setSuccessMsg('');

    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) {
        if (data.code === 'EMAIL_NOT_VERIFIED') {
          setErrorMsg('Seu e-mail ainda não foi verificado. Verifique seu e-mail para ativar sua conta.');
          setVerifyNotice(true);
        } else {
          setErrorMsg(data.message || 'E-mail ou senha incorretos.');
        }
        setLoading(false);
        return;
      }

      showToast('Login efetuado com sucesso!', 'success');
      localStorage.setItem('fluxo_token', data.token);
      localStorage.setItem('fluxo_workspace', 'ws_1');
      if (data.user) {
        localStorage.setItem('fluxo_user', JSON.stringify(data.user));
      }
      
      // Callback to app.jsx to update auth state
      if (onLoginSuccess) {
        onLoginSuccess(data.token, data.user);
      }
    } catch (err) {
      console.error(err);
      setErrorMsg('Erro de conexão com o servidor. Tente novamente.');
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    if (!name || !email || !password || !passwordConfirm) {
      setErrorMsg('Por favor, preencha todos os campos.');
      return;
    }

    if (password.length < 6) {
      setErrorMsg('A senha deve ter pelo menos 6 caracteres.');
      return;
    }

    if (password !== passwordConfirm) {
      setErrorMsg('As senhas não coincidem.');
      return;
    }

    setLoading(true);
    setErrorMsg('');
    setSuccessMsg('');
    setVerifyNotice(false);

    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, password })
      });

      const data = await res.json();

      if (!res.ok) {
        setErrorMsg(data.message || 'Erro ao realizar o cadastro.');
        setLoading(false);
        return;
      }

      setSuccessMsg('Cadastro realizado com sucesso!');
      setVerifyNotice(true);
      
      // Limpa formulário de registro
      setName('');
      setPassword('');
      setPasswordConfirm('');
    } catch (err) {
      console.error(err);
      setErrorMsg('Erro de conexão ao realizar o cadastro.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      width: '100vw',
      height: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: '#07090F',
      backgroundImage: 'radial-gradient(circle at 50% 50%, rgba(91, 141, 239, 0.08) 0%, transparent 60%), radial-gradient(circle at 10% 10%, rgba(16, 185, 129, 0.04) 0%, transparent 40%)',
      position: 'relative',
      overflow: 'hidden'
    }}>
      {/* Decorative premium elements */}
      <div style={{
        position: 'absolute',
        top: '10%',
        left: '15%',
        width: 300,
        height: 300,
        background: 'rgba(91, 141, 239, 0.15)',
        filter: 'blur(120px)',
        borderRadius: '50%',
        pointerEvents: 'none'
      }} />
      <div style={{
        position: 'absolute',
        bottom: '10%',
        right: '15%',
        width: 300,
        height: 300,
        background: 'rgba(16, 185, 129, 0.12)',
        filter: 'blur(120px)',
        borderRadius: '50%',
        pointerEvents: 'none'
      }} />

      {/* Main card */}
      <Card style={{
        width: '100%',
        maxWidth: 440,
        padding: '40px 32px',
        background: isBloom ? '#FFFBF4' : 'rgba(13, 17, 28, 0.75)',
        backdropFilter: 'blur(20px)',
        border: isBloom ? `2px solid ${t.border}` : '1px solid rgba(255, 255, 255, 0.08)',
        boxShadow: isBloom ? '8px 8px 0px 0px #14131A' : '0 20px 50px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05)',
        borderRadius: 24,
        zIndex: 5,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'stretch',
        animation: 'fadeInUp 0.6s cubic-bezier(0.16, 1, 0.3, 1)'
      }}>
        {/* Logo and Brand */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{
            display: 'inline-flex',
            width: 48,
            height: 48,
            background: 'linear-gradient(135deg, #10B981, #5B8DEF)',
            borderRadius: 14,
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 24,
            fontWeight: 700,
            boxShadow: '0 8px 24px -6px rgba(91, 141, 239, 0.5)',
            marginBottom: 16
          }}>
            ⚡
          </div>
          <h1 style={{
            margin: 0,
            fontFamily: t.fontDisplay,
            fontSize: 28,
            fontWeight: 800,
            letterSpacing: '-0.04em',
            color: t.text
          }}>
            FLUXO<span style={{ color: '#10B981' }}>ZAP</span>
          </h1>
          <p style={{
            margin: '6px 0 0',
            fontSize: 13.5,
            color: t.textMuted,
            fontWeight: 500
          }}>
            {isRegister ? 'Crie sua conta para começar' : 'Acesse sua área de trabalho'}
          </p>
        </div>

        {/* Success / Error Feedbacks */}
        {errorMsg && (
          <div style={{
            background: 'rgba(239, 68, 68, 0.1)',
            border: '1px solid rgba(239, 68, 68, 0.2)',
            borderRadius: 12,
            padding: '12px 16px',
            color: '#F87171',
            fontSize: 13,
            lineHeight: 1.4,
            marginBottom: 20,
            display: 'flex',
            alignItems: 'center',
            gap: 10
          }}>
            <span style={{ fontSize: 16 }}>⚠️</span>
            <div style={{ flex: 1 }}>{errorMsg}</div>
          </div>
        )}

        {successMsg && (
          <div style={{
            background: 'rgba(16, 185, 129, 0.1)',
            border: '1px solid rgba(16, 185, 129, 0.2)',
            borderRadius: 12,
            padding: '12px 16px',
            color: '#34D399',
            fontSize: 13,
            lineHeight: 1.4,
            marginBottom: 20,
            display: 'flex',
            alignItems: 'center',
            gap: 10
          }}>
            <span style={{ fontSize: 16 }}>✅</span>
            <div style={{ flex: 1 }}>{successMsg}</div>
          </div>
        )}

        {/* Verification mode warning (Console environment notice) */}
        {verifyNotice && (
          <div style={{
            background: 'rgba(91, 141, 239, 0.08)',
            border: '1px solid rgba(91, 141, 239, 0.15)',
            borderRadius: 12,
            padding: '14px 16px',
            color: '#9CA3AF',
            fontSize: 12.5,
            lineHeight: 1.5,
            marginBottom: 20
          }}>
            <div style={{ color: '#5B8DEF', fontWeight: 700, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              <span>✉️</span> Link de Verificação Disponível
            </div>
            Como estamos no modo de homologação, o link de ativação foi enviado diretamente para o terminal do servidor backend. Por favor, <strong>verifique os logs do seu terminal</strong> para clicar no link e ativar esta conta.
          </div>
        )}

        {/* Form */}
        <form onSubmit={isRegister ? handleRegister : handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {isRegister && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted, letterSpacing: '0.02em' }}>NOME COMPLETO</label>
              <input
                type="text"
                placeholder="Ex: João Silva"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                style={{
                  padding: '12px 16px',
                  background: isBloom ? '#FFF' : 'rgba(255, 255, 255, 0.03)',
                  border: isBloom ? `2px solid ${t.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                  borderRadius: 12,
                  color: t.text,
                  fontSize: 14,
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  fontFamily: t.fontBody
                }}
              />
            </div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted, letterSpacing: '0.02em' }}>E-MAIL</label>
            <input
              type="email"
              placeholder="seu@e-mail.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              style={{
                padding: '12px 16px',
                background: isBloom ? '#FFF' : 'rgba(255, 255, 255, 0.03)',
                border: isBloom ? `2px solid ${t.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                borderRadius: 12,
                color: t.text,
                fontSize: 14,
                outline: 'none',
                transition: 'border-color 0.2s',
                fontFamily: t.fontBody
              }}
            />
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted, letterSpacing: '0.02em' }}>SENHA</label>
              {!isRegister && (
                <a href="#" onClick={(e) => { e.preventDefault(); showToast('Recuperação de senha por e-mail em breve!', 'info'); }} style={{ fontSize: 11.5, color: '#5B8DEF', textDecoration: 'none', fontWeight: 600 }}>
                  Esqueceu a senha?
                </a>
              )}
            </div>
            <input
              type="password"
              placeholder="••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              style={{
                padding: '12px 16px',
                background: isBloom ? '#FFF' : 'rgba(255, 255, 255, 0.03)',
                border: isBloom ? `2px solid ${t.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                borderRadius: 12,
                color: t.text,
                fontSize: 14,
                outline: 'none',
                transition: 'border-color 0.2s',
                fontFamily: t.fontBody
              }}
            />
          </div>

          {isRegister && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted, letterSpacing: '0.02em' }}>CONFIRMAR SENHA</label>
              <input
                type="password"
                placeholder="••••••"
                value={passwordConfirm}
                onChange={(e) => setPasswordConfirm(e.target.value)}
                required
                style={{
                  padding: '12px 16px',
                  background: isBloom ? '#FFF' : 'rgba(255, 255, 255, 0.03)',
                  border: isBloom ? `2px solid ${t.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                  borderRadius: 12,
                  color: t.text,
                  fontSize: 14,
                  outline: 'none',
                  transition: 'border-color 0.2s',
                  fontFamily: t.fontBody
                }}
              />
            </div>
          )}

          <Btn
            type="submit"
            variant="primary"
            loading={loading}
            style={{
              marginTop: 10,
              padding: '13px',
              borderRadius: 12,
              fontSize: 14.5,
              fontWeight: 700,
              letterSpacing: '-0.01em',
              justifyContent: 'center',
              background: 'linear-gradient(135deg, #10B981, #5B8DEF)',
              color: '#FFF'
            }}
          >
            {loading ? (isRegister ? 'Criando conta...' : 'Entrando...') : (isRegister ? 'Criar minha conta ⚡' : 'Entrar no sistema ⚡')}
          </Btn>
        </form>

        {/* Divider */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          margin: '24px 0',
          color: t.textMuted,
          fontSize: 12
        }}>
          <span style={{ flex: 1, height: 1, background: isBloom ? t.border : 'rgba(255, 255, 255, 0.06)' }} />
          <span>ou</span>
          <span style={{ flex: 1, height: 1, background: isBloom ? t.border : 'rgba(255, 255, 255, 0.06)' }} />
        </div>

        {/* Toggle Mode Button */}
        <button
          onClick={() => {
            setIsRegister(!isRegister);
            setErrorMsg('');
            setSuccessMsg('');
            setVerifyNotice(false);
          }}
          style={{
            background: 'transparent',
            border: 'none',
            color: t.text,
            fontSize: 13.5,
            fontWeight: 600,
            cursor: 'pointer',
            textAlign: 'center',
            fontFamily: t.fontBody
          }}
        >
          {isRegister ? (
            <span>Já tem uma conta? <strong style={{ color: '#5B8DEF' }}>Faça login</strong></span>
          ) : (
            <span>Não tem conta? <strong style={{ color: '#10B981' }}>Registre-se grátis</strong></span>
          )}
        </button>
      </Card>

      <style>{`
        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </div>
  );
};

window.LoginScreen = LoginScreen;
