document.addEventListener("DOMContentLoaded", function () {
    let userIdToDelete = null;

    // 1. MISE A JOUR ASYNCHRONE DU ROLE (DROP DOWN AJAX)
    const roleSelects = document.querySelectorAll(".eu-role-select");
    roleSelects.forEach(select => {
        select.addEventListener("change", function () {
            const userId = this.getAttribute("data-user-id");
            const newRole = this.value;

            // Verrouillage de sécurité temporaire pendant l'appel réseau
            this.disabled = true;

            const formData = new FormData();
            formData.append("action", "update_role");
            formData.append("user_id", userId);
            formData.append("role", newRole);

            fetch("edituser.php", {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                this.disabled = false;
                if (data.status === "success") {
                    displayFlashAlert("success", data.message);
                } else {
                    displayFlashAlert("danger", data.message);
                    // Rétablissement de la valeur précédente en cas d'erreur
                    this.value = (newRole === "admin") ? "membre" : "admin";
                }
            })
            .catch(error => {
                this.disabled = false;
                displayFlashAlert("danger", "Une erreur de communication est survenue.");
                this.value = (newRole === "admin") ? "membre" : "admin";
            });
        });
    });

    // 2. LOGIQUE APPLICATIVE DE LA MODALE DE CONFIRMATION SÛRE
    const deleteButtons = document.querySelectorAll(".eu-btn-delete");
    const modalOverlay = document.getElementById("euDeleteModal");
    const modalUsername = document.getElementById("euModalUsername");
    const cancelBtn = document.getElementById("euCancelDelete");
    const confirmBtn = document.getElementById("euConfirmDelete");

    deleteButtons.forEach(btn => {
        btn.addEventListener("click", function () {
            userIdToDelete = this.getAttribute("data-user-id");
            const username = this.getAttribute("data-username");

            modalUsername.textContent = username;
            modalOverlay.classList.add("active");
        });
    });

    cancelBtn.addEventListener("click", closeModal);
    modalOverlay.addEventListener("click", function (e) {
        if (e.target === modalOverlay) closeModal();
    });

    function closeModal() {
        modalOverlay.classList.remove("active");
        userIdToDelete = null;
    }

    // Confirmation de la suppression de compte via AJAX
    confirmBtn.addEventListener("click", function () {
        if (!userIdToDelete) return;

        confirmBtn.disabled = true;
        confirmBtn.textContent = "Suppression...";

        const formData = new FormData();
        formData.append("action", "delete_user");
        formData.append("user_id", userIdToDelete);

        fetch("edituser.php", {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            confirmBtn.disabled = false;
            confirmBtn.textContent = "Supprimer le compte";
            closeModal();

            if (data.status === "success") {
                displayFlashAlert("success", data.message);
                
                // Effacement de la ligne du tableau avec une transition fluide
                const targetRow = document.getElementById("user-row-" + userIdToDelete);
                if (targetRow) {
                    targetRow.style.opacity = "0";
                    targetRow.style.transform = "translateX(-12px)";
                    targetRow.style.transition = "all 0.35s cubic-bezier(0.4, 0, 0.2, 1)";
                    setTimeout(() => {
                        targetRow.remove();
                        // Recharge la page de sécurité s'il n'y a plus aucun inscrit sur l'écran courant
                        if (document.querySelectorAll(".eu-table tbody tr").length === 0) {
                            window.location.reload();
                        }
                    }, 350);
                }
            } else {
                displayFlashAlert("danger", data.message);
            }
        })
        .catch(error => {
            confirmBtn.disabled = false;
            confirmBtn.textContent = "Supprimer le compte";
            closeModal();
            displayFlashAlert("danger", "Impossible de joindre le serveur d'authentification.");
        });
    });

    // GENERATEUR DE NOTIFICATIONS VOLANTES (FLASH ALERTS)
    function displayFlashAlert(type, text) {
        const alertBox = document.getElementById("euAlertContainer");
        const iconClass = type === "success" ? "fa-circle-check" : "fa-circle-xmark";
        
        alertBox.innerHTML = `
            <div class="eu-alert eu-alert-${type}">
                <i class="fa-solid ${iconClass}"></i>
                <span>${text}</span>
            </div>
        `;

        // Masquage et destruction automatique après 4 secondes
        setTimeout(() => {
            const currentAlert = alertBox.querySelector(".eu-alert");
            if (currentAlert) {
                currentAlert.style.opacity = "0";
                currentAlert.style.transform = "translateY(-10px)";
                currentAlert.style.transition = "all 0.3s ease";
                setTimeout(() => currentAlert.remove(), 300);
            }
        }, 4000);
    }
});