const errmsg = `
<div class="form-group">
    <p class="page-paragraph-error">Napaka pri registraciji! Preverite vnešene podatke oz. poskusite kasneje.</p>
</div>
`;

document.getElementById("login-form").addEventListener("submit", async function(event) {
    event.preventDefault();

    // Izbriši prejšnje napake
    const previousErrors = document.querySelectorAll(".page-paragraph-error");
    previousErrors.forEach(error => error.remove());
    // Izbriši prejšnje uspehe
    const previousSuccesses = document.querySelectorAll(".page-paragraph-success");
    previousSuccesses.forEach(success => success.remove());

    const username = document.getElementById("username").value;
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;
    const confirmPassword = document.getElementById("confirm-password").value;
    const form = document.getElementById("login-form");

    try {
        // Veljavnost vnosa
        if (!username || !email || !password || !confirmPassword) {
            form.insertAdjacentHTML(
                "beforeend",
                `<div class="form-group"><p class="page-paragraph-error">Vsa polja so obvezna!</p></div>`
            );
            return;
        }

        if (!email.includes("@")) {
            form.insertAdjacentHTML(
                "beforeend",
                `<div class="form-group"><p class="page-paragraph-error">Neveljaven email naslov!</p></div>`
            );
            return;
        }

        if (password !== confirmPassword) {
            form.insertAdjacentHTML(
                "beforeend",
                `<div class="form-group"><p class="page-paragraph-error">Gesli se ne ujemata!</p></div>`
            );
            return;
        }

        const response = await fetch("https://ssnj.dcrubro.com/api/registracija", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ "username": username, "email": email, "password": password })
        });

        const data = await response.json().catch(() => ({}));

        if (response.status === 200) {
            setTimeout(() => {
                form.insertAdjacentHTML(
                    "beforeend",
                    `<div class="form-group"><p class="page-paragraph-success">Uspešna registracija! Preusmerjanje na prijavo...</p></div>`
                );
            }, 500);
            window.location.href = "/login.html";
            return;
        }

        if (response.status === 409) {
            // Prefer the server-provided message when available; otherwise map known conflict types to Slovenian text
            const serverMsg = (data && data.message) ? String(data.message).toLowerCase() : "";
            let userMsg = "Uporabniško ime ali e-pošta je že zasedena.";

            if (serverMsg.includes("username") || serverMsg.includes("uporab") || serverMsg.includes("user")) {
                userMsg = "Uporabniško ime je že zasedeno.";
            } else if (serverMsg.includes("email") || serverMsg.includes("e-pošta") || serverMsg.includes("e-naslov")) {
                userMsg = "E-poštni naslov je že uporabljen.";
            } else if (serverMsg) {
                userMsg = data.message; // show server message if it's something specific
            }

            form.insertAdjacentHTML(
                "beforeend",
                `<div class="form-group"><p class="page-paragraph-error">${userMsg}</p></div>`
            );
            return;
        }

        const message = data.message || "Napaka pri registracijo! Preverite vnešene podatke oz. poskusite kasneje.";
        form.insertAdjacentHTML(
            "beforeend",
            `<div class="form-group"><p class="page-paragraph-error">${message}</p></div>`
        );
    } catch (error) {
        form.insertAdjacentHTML("beforeend", errmsg);
    }
});