/**
 * Login Page JavaScript
 * Handles login form submission and validation
 */

document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.querySelector('form') || document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('userpassword');
    const rememberMeCheckbox = document.getElementById('customSwitchSuccess');
    const loginButton = document.getElementById('loginBtn') || loginForm?.querySelector('button[type="button"]') || loginForm?.querySelector('button[type="submit"]');

    // Create error display container if it doesn't exist
    let errorContainer = document.getElementById('login-error-container');
    if (!errorContainer) {
        errorContainer = document.createElement('div');
        errorContainer.id = 'login-error-container';
        errorContainer.className = 'alert alert-danger d-none mb-3';
        errorContainer.setAttribute('role', 'alert');
        loginForm.insertBefore(errorContainer, loginForm.firstChild);
    }

    // Show error message
    function showError(message) {
        errorContainer.textContent = message;
        errorContainer.classList.remove('d-none');
        errorContainer.classList.add('d-block');

        // Scroll to error
        errorContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    // Hide error message
    function hideError() {
        errorContainer.classList.add('d-none');
        errorContainer.classList.remove('d-block');
    }

    // Show field error
    function showFieldError(field, message) {
        hideError();
        const input = field === 'username' ? usernameInput : passwordInput;
        input.classList.add('is-invalid');

        // Remove existing feedback
        let feedback = input.parentElement.querySelector('.invalid-feedback');
        if (!feedback) {
            feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            input.parentElement.appendChild(feedback);
        }
        feedback.textContent = message;
    }

    // Clear field errors
    function clearFieldErrors() {
        [usernameInput, passwordInput].forEach(input => {
            input.classList.remove('is-invalid');
            const feedback = input.parentElement.querySelector('.invalid-feedback');
            if (feedback) {
                feedback.remove();
            }
        });
    }

    // Validate form
    function validateForm() {
        let isValid = true;
        clearFieldErrors();

        if (!usernameInput.value.trim()) {
            showFieldError('username', 'Username is required');
            isValid = false;
        }

        if (!passwordInput.value) {
            showFieldError('password', 'Password is required');
            isValid = false;
        }

        return isValid;
    }

    // Handle form submission
    async function handleLogin(e) {
        if (e) {
            e.preventDefault();
        }
        hideError();
        clearFieldErrors();

        // Validate form
        if (!validateForm()) {
            return;
        }

        // Disable button and show loading state
        loginButton.disabled = true;
        const originalText = loginButton.innerHTML;
        loginButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Logging in...';

        try {
            const result = await login(
                usernameInput.value.trim(),
                passwordInput.value,
                rememberMeCheckbox ? rememberMeCheckbox.checked : false
            );

            if (result.success) {
                // Show success message
                errorContainer.className = 'alert alert-success mb-3';
                errorContainer.textContent = result.message || 'Login successful! Redirecting...';
                errorContainer.classList.remove('d-none');
                errorContainer.classList.add('d-block');

                // Redirect after short delay
                setTimeout(() => {
                    window.location.href = result.redirect || 'index.php';
                }, 500);
            } else {
                // Show error
                if (result.errors) {
                    // Show field-specific errors
                    Object.keys(result.errors).forEach(field => {
                        showFieldError(field, result.errors[field]);
                    });
                } else {
                    showError(result.message || 'Login failed. Please try again.');
                }

                // Re-enable button
                loginButton.disabled = false;
                loginButton.innerHTML = originalText;
            }
        } catch (error) {
            console.error('Login error:', error);
            showError('An unexpected error occurred. Please try again.');

            // Re-enable button
            loginButton.disabled = false;
            loginButton.innerHTML = originalText;
        }
    }

    // Attach event listeners
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    if (loginButton) {
        loginButton.addEventListener('click', function (e) {
            e.preventDefault();
            handleLogin(e);
        });
    }

    // Clear errors on input
    usernameInput.addEventListener('input', function () {
        this.classList.remove('is-invalid');
        hideError();
    });

    passwordInput.addEventListener('input', function () {
        this.classList.remove('is-invalid');
        hideError();
    });

    // Handle Enter key
    [usernameInput, passwordInput].forEach(input => {
        input.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                handleLogin(e);
            }
        });
    });

    // Auto-check disabled to prevent console errors
    // Uncomment if you want to redirect already-logged-in users
    /*
    checkAuth().then(result => {
        if (result.authenticated) {
            window.location.href = 'index.php';
        }
    }).catch(() => {
        // Ignore errors
    });
    */
});

