"use client"; import { useState, useEffect } from "react"; import Link from "next/link"; import { Button, Input, Checkbox } from "@/components/ui"; import { saveAuth, isAuthenticated, getToken, clearAuth } from '@/lib/auth'; import { API_ENDPOINTS } from '@/lib/api'; import dynamic from 'next/dynamic'; import { LoginBranding } from '@/components/auth/LoginBranding'; import { EnvelopeIcon, LockClosedIcon, ShieldCheckIcon, BoltIcon, UserGroupIcon, ChartBarIcon, ExclamationCircleIcon, CheckCircleIcon } from "@heroicons/react/24/outline"; const ThemeToggle = dynamic(() => import('@/components/ThemeToggle'), { ssr: false }); export default function LoginPage() { const [isLoading, setIsLoading] = useState(false); const [isSuperAdmin, setIsSuperAdmin] = useState(false); const [subdomain, setSubdomain] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const [successMessage, setSuccessMessage] = useState(''); const [formData, setFormData] = useState({ email: "", password: "", rememberMe: false, }); useEffect(() => { if (typeof window !== 'undefined') { const hostname = window.location.hostname; const sub = hostname.split('.')[0]; const superAdmin = sub === 'dash'; setSubdomain(sub); setIsSuperAdmin(superAdmin); // Verificar se tem parâmetro de erro de tenant não encontrado const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('error') === 'tenant_not_found') { console.log('⚠️ Tenant não encontrado, limpando autenticação...'); clearAuth(); localStorage.removeItem('agency-logo-url'); localStorage.removeItem('agency-primary-color'); localStorage.removeItem('agency-secondary-color'); setErrorMessage('Esta agência não existe mais ou foi desativada.'); return; } if (isAuthenticated()) { // Validar token antes de redirecionar para evitar loops const token = getToken(); fetch(API_ENDPOINTS.me, { headers: { 'Authorization': `Bearer ${token}` } }) .then(res => { if (res.ok) { const target = superAdmin ? '/superadmin' : '/dashboard'; window.location.href = target; } else { // Token inválido ou expirado clearAuth(); } }) .catch((err) => { console.error('Erro ao validar sessão:', err); // Em caso de erro de rede, não redireciona nem limpa, deixa o usuário tentar logar }); } } }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setErrorMessage(''); setSuccessMessage(''); // Validações do lado do cliente if (!formData.email) { setErrorMessage('Por favor, insira seu email para continuar.'); return; } if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) { setErrorMessage('Ops! O formato do email não parece correto. Por favor, verifique e tente novamente.'); return; } if (!formData.password) { setErrorMessage('Por favor, insira sua senha para acessar sua conta.'); return; } if (formData.password.length < 3) { setErrorMessage('A senha parece muito curta. Por favor, verifique se digitou corretamente.'); return; } setIsLoading(true); try { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: formData.email, password: formData.password, }), }); if (!response.ok) { const error = await response.json().catch(() => ({})); // Mensagens humanizadas para cada tipo de erro if (response.status === 401 || response.status === 403) { setErrorMessage('Email ou senha incorretos. Por favor, verifique seus dados e tente novamente.'); } else if (response.status >= 500) { setErrorMessage('Estamos com problemas no servidor no momento. Por favor, tente novamente em alguns instantes.'); } else { setErrorMessage(error.message || 'Algo deu errado ao tentar fazer login. Por favor, tente novamente.'); } setIsLoading(false); return; } const data = await response.json(); saveAuth(data.token, data.user); console.log('Login successful:', data.user); setSuccessMessage('Login realizado com sucesso! Redirecionando você agora...'); setTimeout(() => { const target = isSuperAdmin ? '/superadmin' : '/dashboard'; window.location.href = target; }, 1000); } catch (error: any) { console.error('Login error:', error); setErrorMessage('Não conseguimos conectar ao servidor. Verifique sua conexão com a internet e tente novamente.'); setIsLoading(false); } }; return ( <> {/* Script inline para aplicar cor primária ANTES do React */}