// Login page specific functionality
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('login-form');
    const loginBtn = document.getElementById('login-btn');
    const loginText = document.getElementById('login-text');
    const loading = document.querySelector('.loading');
    const errorMessage = document.getElementById('error-message');
    
    // Check if already logged in
    checkSession();
    
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const email = document.getElementById('email').value.trim();
        const password = document.getElementById('password').value;
        
        if (!email || !password) {
            showError('Please enter both email and password');
            return;
        }
        
        setLoading(true);
        hideError();
        
        try {
            const response = await apiClient.post('/auth/login', {
                email,
                password
            });
            
            if (response.success) {
                // Redirect based on user role
                if (response.user && response.user.isAdmin) {
                    window.location.href = '/admin.html';
                } else {
                    window.location.href = '/dashboard.html';
                }
            } else {
                showError(response.error || 'Login failed');
            }
        } catch (error) {
            console.error('Login error:', error);
            showError(error.message || 'Login failed. Please try again.');
        } finally {
            setLoading(false);
        }
    });
    
    async function checkSession() {
        try {
            const response = await apiClient.get('/auth/session');
            if (response.authenticated && response.user) {
                // Already logged in, redirect based on user role
                if (response.user.isAdmin) {
                    window.location.href = '/admin.html';
                } else {
                    window.location.href = '/dashboard.html';
                }
            }
        } catch (error) {
            // Not logged in, continue with login form
            console.log('Not logged in');
        }
    }
    
    function setLoading(isLoading) {
        loginBtn.disabled = isLoading;
        loginText.style.display = isLoading ? 'none' : 'inline';
        loading.style.display = isLoading ? 'block' : 'none';
    }
    
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }
    
    function hideError() {
        errorMessage.style.display = 'none';
    }
    
    // Check for URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('expired') === 'true') {
        showError('Your session has expired. Please log in again.');
    }
});