const cachedData = {};

document.addEventListener("DOMContentLoaded", () => {
    const cards = document.querySelectorAll('.pt-park-card');

    // 1. Chargement des barres de progression dès l'affichage de la page
    cards.forEach(card => {
        const slug = card.dataset.slug;
        if (!slug) return;

        fetch(`get_times.php?slug=${slug}`)
        .then(res => res.json())
        .then(data => {
            if (data.error) throw new Error();

            let attractions = [];
            
            // Extraction universelle multiniveaux (Lands -> Rides / Lands -> Attractions / Direct)
            if (data.attractions && Array.isArray(data.attractions)) {
                attractions = data.attractions;
            } else if (data.lands && Array.isArray(data.lands)) {
                data.lands.forEach(land => {
                    if (land.attractions && Array.isArray(land.attractions)) {
                        attractions = attractions.concat(land.attractions);
                    } else if (land.rides && Array.isArray(land.rides)) {
                        attractions = attractions.concat(land.rides);
                    }
                });
            }

            // Uniformisation stricte des objets reçus
            attractions = attractions.map(ride => ({
                name: ride.name,
                is_open: ride.is_open === true || ride.is_open === 1 || ride.is_open === "true",
                wait_time: parseInt(ride.wait_time) || 0
            }));

            cachedData[slug] = attractions; // Sauvegarde en mémoire instantanée pour le clic

            if (attractions.length === 0) {
                marquerFerme(slug);
                return;
            }

            const openRides = attractions.filter(ride => ride.is_open || ride.wait_time > 0);
            if (openRides.length === 0) {
                updateBarre(slug, 0, 'low', 'Fermé');
                return;
            }

            const totalWait = openRides.reduce((sum, ride) => sum + ride.wait_time, 0);
            const averageWait = totalWait / openRides.length;

            // Affluence calculée sur un maximum critique de 45 minutes d'attente moyenne globale
            let percentage = Math.min(Math.round((averageWait / 45) * 100), 100);
            if (percentage < 5) percentage = 8;

            let statusClass = 'low';
            let statusText = 'Fluide';
            if (percentage >= 35 && percentage < 70) { statusClass = 'medium'; statusText = 'Modéré'; }
            else if (percentage >= 70) { statusClass = 'high'; statusText = 'Saturé'; }

            updateBarre(slug, percentage, statusClass, statusText);
        })
        .catch(() => {
            const box = document.getElementById(`att-box-${slug}`);
            if (box) box.querySelector('.pt-text-info').innerText = "Indisponible";
        });
    });

    // Événements de fermeture de la PopUp modale
    const modal = document.getElementById('ridesModal');
    if (modal) {
        modal.addEventListener('click', (e) => { if (e.target === modal) window.fermerPopUp(); });
    }
    window.addEventListener('keydown', (e) => { if (e.key === 'Escape') window.fermerPopUp(); });
});

// 2. FONCTION APPELÉE LORS DU CLIC SUR UNE CARTE
window.ouvrirPopUp = function(element) {
    const slug = element.dataset.slug;
    const parkName = element.dataset.name;
    const modal = document.getElementById('ridesModal');
    const modalParkName = document.getElementById('modalParkName');
    const modalRidesList = document.getElementById('modalRidesList');

    if (!modal || !modalRidesList) return;

    modalParkName.innerText = parkName;
    modalRidesList.innerHTML = `
        <div class="pt-spinner">
            <i class="fa-solid fa-circle-notch fa-spin"></i>
            <p>Génération de la liste des attractions...</p>
        </div>`;
    
    modal.classList.add('active');

    // Utilisation immédiate du cache de fond
    if (cachedData[slug] && cachedData[slug].length > 0) {
        renderRides(cachedData[slug], modalRidesList);
    } else {
        // Option de secours synchrone
        fetch(`get_times.php?slug=${slug}`)
        .then(res => res.json())
        .then(data => {
            let attractions = [];
            if (data.attractions && Array.isArray(data.attractions)) {
                attractions = data.attractions;
            } else if (data.lands && Array.isArray(data.lands)) {
                data.lands.forEach(land => {
                    if (land.attractions && Array.isArray(land.attractions)) {
                        attractions = attractions.concat(land.attractions);
                    } else if (land.rides && Array.isArray(land.rides)) {
                        attractions = attractions.concat(land.rides);
                    }
                });
            }
            
            attractions = attractions.map(ride => ({
                name: ride.name,
                is_open: ride.is_open === true || ride.is_open === 1 || ride.is_open === "true",
                wait_time: parseInt(ride.wait_time) || 0
            }));

            cachedData[slug] = attractions;
            renderRides(attractions, modalRidesList);
        })
        .catch(() => {
            modalRidesList.innerHTML = `<p style="text-align:center; padding:20px; color:#ff4757; font-weight:600;">Erreur lors du traitement.</p>`;
        });
    }
};

window.fermerPopUp = function() {
    const modal = document.getElementById('ridesModal');
    if (modal) modal.classList.remove('active');
};

function renderRides(attractions, container) {
    if (!attractions || attractions.length === 0) {
        container.innerHTML = `<p style="text-align:center; padding:20px; color:#718096;">Aucune attraction répertoriée pour le moment.</p>`;
        return;
    }

    // Classement décroissant par temps d'attente
    attractions.sort((a, b) => b.wait_time - a.wait_time);

    let html = '';
    attractions.forEach(ride => {
        let badgeClass = 'closed';
        let badgeText = 'Fermé';

        if (ride.is_open) {
            badgeText = `${ride.wait_time} min`;
            if (ride.wait_time < 15) badgeClass = 'low';
            else if (ride.wait_time < 40) badgeClass = 'medium';
            else badgeClass = 'high';
        }

        html += `
            <div class="pt-ride-row">
                <span class="pt-ride-name">${ride.name}</span>
                <span class="pt-wait-badge ${badgeClass}">${badgeText}</span>
            </div>
        `;
    });
    container.innerHTML = html;
}

function updateBarre(slug, percentage, statusClass, statusText) {
    const box = document.getElementById(`att-box-${slug}`);
    if (box) {
        box.querySelector('.pt-text-info').innerText = `Fréquentation : ${percentage}%`;
        const badge = box.querySelector('.pt-badge');
        badge.className = `pt-badge ${statusClass}`;
        badge.innerText = statusText;
        const fill = box.querySelector('.pt-progress-fill');
        fill.className = `pt-progress-fill ${statusClass}`;
        fill.style.width = `${percentage}%`;
    }
}

function marquerFerme(slug) {
    const box = document.getElementById(`att-box-${slug}`);
    if (box) {
        box.querySelector('.pt-text-info').innerText = "Parc Fermé";
        const badge = box.querySelector('.pt-badge');
        badge.className = "pt-badge";
        badge.style.background = "#edf2f7";
        badge.style.color = "#718096";
        badge.innerText = "Clos";
    }
}