// Login form handler — uses fetch API to authenticate
document.addEventListener('DOMContentLoaded', function () {
    const form = document.querySelector('#loginForm');
    const errorMsg = document.getElementById('errorMsg');

    form.addEventListener('submit', async function (event) {
        event.preventDefault();
        if (errorMsg) errorMsg.textContent = '';

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const remember = document.getElementById('remember').checked ? 'on' : '';

        if (!username || !password) {
            if (errorMsg) errorMsg.textContent = 'Please fill in all fields.';
            return;
        }

        try {
            const response = await fetch('/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password, remember })
            });

            if (response.ok) {
                const result = await response.json();
                // Redirect based on role
                if (result.role === 'admin') {
                    window.location.href = '/admin-games';
                } else {
                    window.location.href = '/home';
                }
            } else {
                const error = await response.json();
                if (errorMsg) errorMsg.textContent = error.error || 'Login failed.';
            }
        } catch (err) {
            console.error('Login error:', err);
            if (errorMsg) errorMsg.textContent = 'Network error. Please try again.';
        }
    });
});
