// auth.js - Handles Authentication Logic

document.addEventListener('DOMContentLoaded', function () {

    // 0. Check if already logged in (Only on login page)
    if (window.location.pathname.includes('login.html')) {
        fetch('api/auth.php?action=check')
            .then(res => res.json())
            .then(data => {
                if (data && data.authenticated) {
                    window.location.href = 'dashboard.html';
                }
            })
            .catch(() => { /* Ignore errors here, just let them login */ });
    }

    // 1. Handle Login Form
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            const errorDiv = document.getElementById('login-error');

            errorDiv.style.display = 'none';

            fetch('api/auth.php?action=login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, password })
            })
                .then(res => res.json())
                .then(data => {
                    if (data.redirect) {
                        window.location.href = data.redirect;
                    } else {
                        errorDiv.textContent = data.error || 'Login failed';
                        errorDiv.style.display = 'block';
                    }
                })
                .catch(err => {
                    console.error(err);
                    errorDiv.textContent = 'An error occurred. Please try again.';
                    errorDiv.style.display = 'block';
                });
        });
        return; // Stop here if we rely on login form logic
    }

    // 2. Check Session on protected pages
    // Only run if NOT on login page
    if (!window.location.pathname.includes('login.html')) {
        // Create and append a blocking overlay immediately
        const overlay = document.createElement('div');
        overlay.id = 'auth-overlay';
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = '#f8fafc';
        overlay.style.zIndex = '9999';
        overlay.style.display = 'flex';
        overlay.style.justifyContent = 'center';
        overlay.style.alignItems = 'center';
        overlay.innerHTML = '<div style="font-family: sans-serif; color: #64748b;">Verifying session...</div>';
        document.body.appendChild(overlay);

        checkAuth(overlay);
    }

    // 3. Handle Logout Buttons
    document.body.addEventListener('click', function (e) {
        if (e.target.closest('a[onclick="logoutUser()"]') || e.target.closest('.logout-btn')) {
            // Let the inline onclick or specific handler do work, or we can catch it here.
            // Our inline onclick="logoutUser()" calls global function, which calls logout() below.
        }
    });
});

function checkAuth(overlay) {
    fetch('api/auth.php?action=check')
        .then(res => {
            if (res.status === 401 || res.status === 403) {
                // Not authenticated
                throw new Error('Unauthorized');
            }
            if (!res.ok) {
                // Server error (500 etc)
                throw new Error('Server Error');
            }
            return res.json();
        })
        .then(data => {
            if (data && data.authenticated) {
                // User is logged in
                // Remove overlay to reveal content
                if (overlay) overlay.remove();
                updateUserProfile(data.user);
            } else {
                throw new Error('Not authenticated');
            }
        })
        .catch(err => {
            console.error('Auth check error:', err);
            // On any error, redirect to login
            window.location.href = 'login.html';
        });
}

function updateUserProfile(user) {
    // Find profile elements and update
    const profileName = document.querySelector('.user-profile .font-bold');
    const profileRole = document.querySelector('.user-profile .text-muted');
    const profileAvatar = document.querySelector('.user-profile .avatar');

    if (profileName) profileName.textContent = user.name;
    if (profileRole) profileRole.textContent = user.role;
    if (profileAvatar) profileAvatar.textContent = getInitials(user.name);
}

function logout() {
    fetch('api/auth.php?action=logout', { method: 'POST' })
        .then(() => window.location.href = 'login.html');
}

function getInitials(name) {
    if (!name) return '??';
    return name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
}
