document.addEventListener('DOMContentLoaded', function() {
    const showAlert = (type, message) => {
        const alertPlaceholder = document.getElementById("alert-placeholder");
        alertPlaceholder.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>`;
    };

    function toggleButtonLoading(button, isLoading) {
        const text = button.querySelector(".btn-text");
        const spinner = button.querySelector(".spinner-border");
        
        if (isLoading) {
            text.classList.add("d-none");
            spinner.classList.remove("d-none");
            button.disabled = true;
        } else {
            text.classList.remove("d-none");
            spinner.classList.add("d-none");
            button.disabled = false;
        }
    }

    const loginBtn = document.getElementById("loginBtn");
    document.getElementById("loginForm").addEventListener('submit', async function(e) {
        e.preventDefault();
        toggleButtonLoading(loginBtn, true);
        const formData = new FormData(e.target);

        const response = await fetch(`${window.APP_BASE || ""}/loginUser.php`, {
            method: "POST",
            body: formData,
        });
        const result = await response.json();
        if(result.success) {
            toggleButtonLoading(loginBtn, false);
            showAlert("success", result.message);
            e.target.reset();
            setTimeout(()=> {
                window.location.href = `${window.APP_BASE || ""}/dashboard`;
            }, 1500);
        } else {
            toggleButtonLoading(loginBtn, false);
            showAlert("danger", result.message);
        }
    })

});
