<style>
    .floating-logo-login { position: fixed; top: 24px; left: 50%; transform: translateX(-50%); width: 140px; height: 140px; border-radius: 50%; background: rgba(255,255,255,0.2); backdrop-filter: blur(4px); box-shadow: 0 10px 20px rgba(0,0,0,0.15); display: flex; align-items: center; justify-content: center; animation: floatLogo 4s ease-in-out infinite; border: 2px solid rgba(255,255,255,0.5); z-index: 1000; }
    .floating-logo-login img { width: 80px; height: auto; }
    @keyframes floatLogo { 0%,100% { transform: translate(-50%, 0); } 50% { transform: translate(-50%, -8px); } }
</style>
<main class="wrap" style="display:flex;align-items:center;justify-content:center;min-height:80vh;">
<div class="floating-logo-login"><img src="/assets/logo-dark.png" alt="GestorEasy" /></div>
<div class="card" style="width:100%;max-width:360px;margin:auto;">
    <div class="muted" style="text-align:center;margin-top:2px;margin-bottom:12px;">Sistema de gestão empresarial</div>
    <div id="alert" class="alert alert-error" style="display:none;"></div>
    <form id="loginForm" style="margin-top:0.25rem;">
        <div class="form-group">
            <label for="email">E-mail</label>
            <input type="email" id="email" name="email" placeholder="Digite seu e-mail" autocomplete="email" required tabindex="1">
        </div>
        <div class="form-group">
            <label for="password">Senha</label>
            <input type="password" id="password" name="password" placeholder="Digite sua senha" autocomplete="current-password" required tabindex="2">
        </div>
        <button type="submit" class="btn" id="loginBtn" style="width:100%;" tabindex="3">Entrar</button>
        <div style="text-align:center; margin:8px 0 12px;">
            <a href="/forgot-password" style="text-decoration:none; color: var(--color-olive);" tabindex="4">Esqueci a senha</a>
        </div>
    </form>
    <div id="loading" class="loading" style="display:none;text-align:center;margin-top:0.5rem;">
        <p>Fazendo login...</p>
    </div>
</div>
</main>

<script>
    const loginForm = document.getElementById('loginForm');
    const loginBtn = document.getElementById('loginBtn');
    const loading = document.getElementById('loading');
    const alert = document.getElementById('alert');

    // Resolve o tenant atual a partir do cookie; se ausente, usa 'default'
    function resolveTenantId() {
        const m = document.cookie.match(/(?:^|; )x-tenant-id=([^;]+)/);
        return m ? decodeURIComponent(m[1]) : 'default';
    }

    function showAlert(message) {
        alert.textContent = message;
        alert.style.display = 'block';
    }

    function hideAlert() {
        alert.style.display = 'none';
    }

    function showLoading() {
        loading.style.display = 'block';
        loginBtn.disabled = true;
        loginBtn.textContent = 'Entrando...';
    }

    function hideLoading() {
        loading.style.display = 'none';
        loginBtn.disabled = false;
        loginBtn.textContent = 'Entrar';
    }

    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        hideAlert();
        showLoading();

        const formData = new FormData(loginForm);
        const loginData = {
            email: formData.get('email'),
            password: formData.get('password')
        };

        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'x-tenant-id': resolveTenantId(),
                    'Accept': 'application/json'
                },
                body: JSON.stringify(loginData)
            });

            const data = await response.json();

            const params = new URLSearchParams(window.location.search || '');
            const next = params.get('next') || '/dashboard';
            if (response.ok && data.access_token) {
                localStorage.setItem('auth_token', data.access_token);
                // Definir cookie para navegação HTML
                const maxAge = 7 * 24 * 60 * 60; // 7 dias
                document.cookie = `auth_token=${encodeURIComponent(data.access_token)}; Max-Age=${maxAge}; path=/; SameSite=Lax`;
                // Não sobrescrever x-tenant-id; backend já define conforme o contexto
                window.location.href = next;
            } else {
                showAlert(data.error || data.message || 'Erro ao fazer login. Verifique suas credenciais.');
            }
        } catch (error) {
            showAlert('Erro de conexão. Tente novamente.');
        } finally {
            hideLoading();
        }
    });

    // Melhorar usabilidade: pressionar Enter no campo senha foca o botão
    document.getElementById('password').addEventListener('keydown', function(ev){
        if (ev.key === 'Enter') {
            ev.preventDefault();
            document.getElementById('loginBtn').focus();
        }
    });

    document.addEventListener('DOMContentLoaded', async function() {
        // Se houver token salvo, validar antes de redirecionar.
        // Corrige loop de redirecionamento quando token inválido impede a digitação das credenciais.
        const params = new URLSearchParams(window.location.search || '');
        const next = params.get('next') || '/dashboard';
        const lsToken = localStorage.getItem('auth_token');
        const cookieMatch = document.cookie.match(/(?:^|; )auth_token=([^;]+)/);
        const token = lsToken || (cookieMatch ? decodeURIComponent(cookieMatch[1]) : null);
        if (!token) return;
        try {
            const res = await fetch('/api/auth/me', {
                method: 'GET',
                headers: { 
                    'Authorization': `Bearer ${token}`,
                    'x-tenant-id': resolveTenantId(),
                    'Accept': 'application/json'
                },
                credentials: 'include',
                cache: 'no-store'
            });
            if (res && res.ok) {
                const maxAge = 7 * 24 * 60 * 60; // 7 dias
                document.cookie = `auth_token=${encodeURIComponent(token)}; Max-Age=${maxAge}; path=/; SameSite=Lax`;
                window.location.href = next;
            } else {
                // Token inválido: limpar e permanecer na página de login
                localStorage.removeItem('auth_token');
                document.cookie = 'auth_token=; Max-Age=0; path=/';
            }
        } catch (_) {
            // Em erro de rede, não redirecionar para permitir o login manual
        }
    });
</script>