const errmsg = `
<div class="form-group">
    <p class="page-paragraph-error">Napaka pri prijavi! Preverite uporabniško ime in geslo 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());

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

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

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

        if (response.status === 200) {
            // Nastavi cookie, 3 ure veljaven
            document.cookie = `token=${data.token}; max-age=${3 * 60 * 60}; path=/; secure; samesite=strict`;
            document.cookie = `username=${username}; max-age=${3 * 60 * 60}; path=/; secure; samesite=strict`;
            
            window.location.href = "/";
            return;
        }

        const message = data.message || "Napaka pri prijavi! Preverite uporabniško ime in geslo oz. poskusite kasneje.";
        form.insertAdjacentHTML(
            "beforeend",
            `<div class="form-group"><p class="page-paragraph-error">${message}</p></div>`
        );
    } catch (error) {
        form.insertAdjacentHTML("beforeend", errmsg);
    }
});