document.addEventListener("DOMContentLoaded", () => {

    const overlay = document.getElementById("queue-overlay");
    const blue = document.getElementById("circle-blue");
    const red = document.getElementById("circle-red");
    const cancel = document.getElementById("circle-cancel");
    const imgBlue = document.getElementById("img-blue");
    const imgRed = document.getElementById("img-red");
    const countBlue = document.getElementById("count-blue");
    const countRed = document.getElementById("count-red");
    const queueTitle = document.getElementById("queue-title"); // AJOUT

    let myTeam = null; // Pour stocker l'équipe du joueur

    document.getElementById("btn-play").onclick = () => {
        overlay.style.display = "flex";
        refreshQueue();
    };

    function join(team) {
        if (myTeam) return; // Déjà dans une équipe

        let fd = new FormData();
        fd.append("team", team);

        fetch("php/join_team.php", { method: "POST", body: fd })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                myTeam = team;
                refreshQueue();
            } else {
                if (data.error === "team_full") {
                    queueTitle.textContent = "L'équipe est déjà complète !";
                    queueTitle.style.color = "red";
                    // Remettre le texte après 2 secondes
                    setTimeout(() => {
                        queueTitle.textContent = "Choisissez votre équipe";
                        queueTitle.style.color = "white";
                    }, 2000);
                } else if (data.error === "game_full") {
                    queueTitle.textContent = "Partie déjà complète !";
                    queueTitle.style.color = "red";
                    // Remettre le texte après 2 secondes
                    setTimeout(() => {
                        queueTitle.textContent = "Choisissez votre équipe";
                        queueTitle.style.color = "white";
                    }, 2000);
                }
            }
        });
    }

    blue.onclick = () => join("bleu");
    red.onclick = () => join("rouge");

    cancel.onclick = () => {
        if (myTeam) {
            fetch("php/leave_team.php")
            .then(() => {
                myTeam = null;
                overlay.style.display = "none";
            });
        } else {
            overlay.style.display = "none";
        }
    };

    function refreshQueue() {
        // TOUJOURS vérifier la redirection en premier
        fetch("php/check_redirect.php")
        .then(r => r.json())
        .then(data => {
            if (data.redirect) {
                window.location.href = data.url;
                return;
            }

            // Sinon, mettre à jour l'affichage
            fetch("php/teams.php")
            .then(r => r.json())
            .then(data => {
                // Affichage des images
                imgBlue.src = data.bleu >= 1 ? "image/green.png" : "image/grey.png";
                countBlue.style.display = data.bleu >= 1 ? "block" : "none";
                countBlue.textContent = data.bleu;

                imgRed.src = data.rouge >= 1 ? "image/green.png" : "image/grey.png";
                countRed.style.display = data.rouge >= 1 ? "block" : "none";
                countRed.textContent = data.rouge;

                const resetBtn = document.getElementById("reset-queue-btn");
                
                // Si partie en cours (locked), désactiver tout
                if (data.locked) {
                    blue.style.opacity = "0.5";
                    blue.style.cursor = "not-allowed";
                    red.style.opacity = "0.5";
                    red.style.cursor = "not-allowed";
                    resetBtn.disabled = true;
                    resetBtn.style.opacity = "0.5";
                    resetBtn.style.cursor = "not-allowed";
                    resetBtn.textContent = "Partie en cours...";
                } else {
                    // Sinon, comportement normal
                    if (data.bleu >= 1) {
                        blue.style.opacity = "0.5";
                        blue.style.cursor = "not-allowed";
                    } else {
                        blue.style.opacity = "1";
                        blue.style.cursor = "pointer";
                    }

                    if (data.rouge >= 1) {
                        red.style.opacity = "0.5";
                        red.style.cursor = "not-allowed";
                    } else {
                        red.style.opacity = "1";
                        red.style.cursor = "pointer";
                    }

                    resetBtn.disabled = false;
                    resetBtn.style.opacity = "1";
                    resetBtn.style.cursor = "pointer";
                    resetBtn.textContent = "Vider la file d'attente";

                    // Si partie prête, lancer la vérification de redirection
                    if (data.ready) {
                        checkRedirectRepeatedly();
                    }
                }
            });
        });
    }

    function checkRedirectRepeatedly() {
        const redirectInterval = setInterval(() => {
            fetch("php/check_redirect.php")
            .then(r => r.json())
            .then(data => {
                if (data.redirect) {
                    clearInterval(redirectInterval);
                    window.location.href = data.url;
                }
            });
        }, 500);
    }

    // Bouton reset
    document.getElementById("reset-queue-btn").onclick = () => {
        const resetBtn = document.getElementById("reset-queue-btn");
        if (resetBtn.disabled) return;
        
        fetch("php/reset_teams.php")
        .then(() => {
            myTeam = null;
            refreshQueue();
        })
        .catch(err => {
            console.error("Erreur reset:", err);
        });
    };

    // Vérifier au chargement
    checkRedirectRepeatedly();

    // Rafraîchir régulièrement
    setInterval(refreshQueue, 1000);
});