document.addEventListener("DOMContentLoaded", () => {
    const modal = document.getElementById("coasterModal");
    const btnNew = document.getElementById("btnNewCoaster");
    const btnClose = document.getElementById("btnCloseModal");
    const modalTitle = document.getElementById("modalTitle");
    
    const fieldId = document.getElementById("field_id");
    const fieldNom = document.getElementById("field_nom");
    const fieldAnnee = document.getElementById("field_annee");
    const fieldConstructeur = document.getElementById("field_constructeur");
    const fieldHauteur = document.getElementById("field_hauteur");
    const fieldLongueur = document.getElementById("field_longueur");
    const fieldVitesse = document.getElementById("field_vitesse");
    const fieldStatut = document.getElementById("field_statut");

    btnNew.addEventListener("click", () => {
        modalTitle.innerText = "Ajouter une attraction";
        fieldId.value = "";
        fieldNom.value = "";
        fieldAnnee.value = "";
        fieldConstructeur.value = "";
        fieldHauteur.value = "";
        fieldLongueur.value = "";
        fieldVitesse.value = "";
        fieldStatut.value = "Ouvert";
        modal.style.display = "flex";
    });

    document.querySelectorAll(".btnEditClass").forEach(btn => {
        btn.addEventListener("click", () => {
            const data = JSON.parse(btn.getAttribute("data-json"));
            modalTitle.innerText = "Éditer l'attraction";
            fieldId.value = data.id;
            fieldNom.value = data.nom;
            fieldAnnee.value = data.annee_ouverture || "";
            fieldConstructeur.value = data.constructeur || "";
            fieldHauteur.value = data.hauteur || "";
            fieldLongueur.value = data.longueur || "";
            fieldVitesse.value = data.vitesse || "";
            fieldStatut.value = data.statut;
            modal.style.display = "flex";
        });
    });

    btnClose.addEventListener("click", () => { modal.style.display = "none"; });
    window.addEventListener("click", (e) => { if (e.target === modal) modal.style.display = "none"; });
});