// =============================
//      LOGIN / REGISTER
// =============================

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

    const loginUser = document.getElementById("login-user");
    const loginPass = document.getElementById("login-pass");
    const btnLogin = document.getElementById("btn-login");

    const newUser = document.getElementById("new-user");
    const newPass = document.getElementById("new-pass");
    const btnCreate = document.getElementById("btn-create");

    const backMenu = document.getElementById("back-menu");

    const loginTitle = document.getElementById("login-title");
    const createTitle = document.getElementById("create-title");

    // Retour menu
    backMenu.addEventListener("click", () => {
        window.location.href = "index.html";
    });


    // =============================
    //     ANIMATION FEEDBACK
    // =============================
    function showFeedback(msg) {
        const container = document.getElementById("login-container");
        const fb = document.getElementById("login-feedback");
        const logo = document.getElementById("feedback-logo");
        const text = document.getElementById("feedback-text");
        const logoutBtn = document.getElementById("feedback-logout");

        text.textContent = msg;

        // Hide form
        container.style.opacity = "0";
        container.style.transition = "opacity 1s";

        setTimeout(() => container.style.display = "none", 900);

        // Show feedback
        fb.style.opacity = "1";
        fb.style.pointerEvents = "auto";

        setTimeout(() => {
            logo.style.transform = "translateY(-50px)";
            text.style.opacity = "1";
        }, 300);

        setTimeout(() => {
            logoutBtn.style.opacity = "1";
        }, 1500);
    }


    // =============================
    //     ERREUR ANIMÉE
    // =============================
    function showError(titleElement, buttonElement, message) {
        titleElement.textContent = message;
        titleElement.classList.add("error-msg");

        buttonElement.classList.add("btn-error");

        setTimeout(() => {
            titleElement.classList.remove("error-msg");
            buttonElement.classList.remove("btn-error");

            // Reset titles
            if (titleElement === createTitle) titleElement.textContent = "Créer un compte";
            if (titleElement === loginTitle) titleElement.textContent = "Se connecter";

        }, 1500);
    }


// =============================
//     CRÉER COMPTE
// =============================
btnCreate.addEventListener("click", () => {

    if (newUser.value.trim() === "" || newPass.value.trim() === "") {
        showError(createTitle, btnCreate, "Champs manquants");
        return;
    }

    const formData = new FormData();
    formData.append("username", newUser.value);
    formData.append("password", newPass.value);

    fetch("php/register.php", {
        method: "POST",
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {

            // Animation post-creation
            showFeedback("Compte créé !");

            // SUPPRIMER LA REDIRECTION AUTOMATIQUE
            // L'utilisateur reste sur la page de login
            // Mais maintenant la session est active grâce au register.php modifié

        } else {

            if (data.message === "exists") {
                showError(createTitle, btnCreate, "Utilisateur occupé");
            } else {
                showError(createTitle, btnCreate, "Erreur");
            }
        }
    })
    .catch(() => showError(createTitle, btnCreate, "Erreur serveur"));
});

    // =============================
    //        CONNEXION
    // =============================
    btnLogin.addEventListener("click", () => {

        if (loginUser.value.trim() === "" || loginPass.value.trim() === "") {
            showError(loginTitle, btnLogin, "Champs manquants");
            return;
        }

        const formData = new FormData();
        formData.append("username", loginUser.value);
        formData.append("password", loginPass.value);

        fetch("php/login.php", {
            method: "POST",
            body: formData
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {

                // Message personnalisé
                showFeedback("Bienvenue " + data.username + " !");

            } else {
                showError(loginTitle, btnLogin, "Informations incorrectes");
            }
        })
        .catch(() => showError(loginTitle, btnLogin, "Erreur serveur"));
    });


    // =============================
    //       DÉCONNEXION
    // =============================
    document.getElementById("feedback-logout").addEventListener("click", () => {
        fetch("php/logout.php")
            .then(() => window.location.href = "login.html");
    });

});
