$(document).ready(function() {
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();

        // Clear previous error messages
        $('.error-msg').fadeOut();

        const formData = $(this).serialize();
        const submitBtn = $(this).find('button[type="submit"]');
        const originalBtnText = submitBtn.html();

        // Loading state
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Authenticating...');

        $.ajax({
            url: 'site/APIs/login.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Authenticated',
                        text: response.message,
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.href = 'site/index.php';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Login Failed',
                        text: response.message
                    });
                    
                    // Also show message under fields if applicable
                    showFieldMessage('#login-error-container', response.message, 'text-danger');
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'System Error',
                    text: 'Unable to connect to the server. Please try again later.'
                });
            },
            complete: function() {
                submitBtn.prop('disabled', false).html(originalBtnText);
            }
        });
    });

    function showFieldMessage(selector, message, textClass) {
        const el = $(selector);
        el.html(`<small class="${textClass}">${message}</small>`).fadeIn();
        
        setTimeout(() => {
            el.fadeOut();
        }, 5000);
    }
});
