document.addEventListener("DOMContentLoaded", () => {
    const ratingWrapper = document.querySelector(".pv-rating-wrapper");
    if (!ratingWrapper) return;

    const isLogged = ratingWrapper.getAttribute("data-logged") === "true";
    const stars = document.querySelectorAll(".pv-star-item");
    const lblMoyenne = document.getElementById("lblMoyenne");
    const lblVotesCount = document.getElementById("lblVotesCount");

    if (!isLogged) return; // Si non connecté, on fige le survol

    stars.forEach(star => {
        // Effet de survol progressif
        star.addEventListener("mouseenter", () => {
            const currentVal = parseInt(star.getAttribute("data-value"));
            stars.forEach((s, idx) => {
                if (idx < currentVal) {
                    s.classList.add("hover-active", "fa-solid");
                    s.classList.remove("fa-regular");
                } else {
                    s.classList.remove("hover-active", "fa-solid");
                    s.classList.add("fa-regular");
                }
            });
        });

        // Clic pour enregistrer la note (AJAX)
        star.addEventListener("click", () => {
            const val = parseInt(star.getAttribute("data-value"));

            fetch("ajax_rate_parc.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ parc_id: CURRENT_PARC_ID, note: val })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    lblMoyenne.innerText = data.nouvelle_moyenne;
                    lblVotesCount.innerText = data.total_votes;
                    
                    // On fige l'état actif sur les étoiles choisies
                    stars.forEach((s, idx) => {
                        if (idx < val) {
                            s.className = "fa-star fa-solid is-active pv-star-item";
                        } else {
                            s.className = "fa-star fa-regular pv-star-item";
                        }
                    });
                    alert("Votre note de " + val + " ★ a bien été prise en compte !");
                } else if (data.error) {
                    alert(data.error);
                }
            })
            .catch(() => alert("Une erreur est survenue lors de la communication de la note."));
        });
    });

    // Nettoyage au départ de la souris de la zone d'évaluation
    ratingWrapper.addEventListener("mouseleave", () => {
        stars.forEach(s => {
            s.classList.remove("hover-active");
            if (!s.classList.contains("is-active")) {
                s.className = "fa-star fa-regular pv-star-item";
            } else {
                s.className = "fa-star fa-solid is-active pv-star-item";
            }
        });
    });
});