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;
        }
    }

     // Registration Handler
    const registerBtn = document.getElementById("registerBtn");
    document.getElementById("registerForm").addEventListener("submit", async (e) => {
        e.preventDefault();
        toggleButtonLoading(registerBtn, true);
        const formData = new FormData(e.target);
        const password = e.target.password.value;
        const confirmPassword = e.target.confirm_password.value;

        // Compare passwords
        if (password !== confirmPassword) {
            toggleButtonLoading(registerBtn, false)
            showAlert("danger", "Passwords do not match.");
            return;
        }


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