const form = `
<form class="contact-form" id="contact-form">
    <label for="message">Sporočilo:</label>
    <textarea id="message" name="message" rows="5" class="page-input" required></textarea>
    <button type="submit" class="page-btn">Pošlji</button>
    <p><em>Vaše sporočilo bo vezano na vaš račun, zato vam bomo lahko odgovorili na e-pošto, ki ste jo vnesli ob registraciji.</em></p>
</form>`;

document.addEventListener("DOMContentLoaded", () => {
    const contactFormContainer = document.getElementById("contact-form-container");
    // Najdi cookie "token" v cookies
    const isLoggedIn = document.cookie.split(";").some(cookie => cookie.trim().startsWith("token="));
    if (contactFormContainer && isLoggedIn) {
        contactFormContainer.innerHTML = form;

        document.getElementById("contact-form").addEventListener("submit", (e) => {
            e.preventDefault();

            const url = "https://ssnj.dcrubro.com/api/kontakt";
            const message = document.getElementById("message").value;
            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ "token": document.cookie.split(";").find(cookie => cookie.trim().startsWith("token=")).split("=")[1], "message": message })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return response.json();
            })
            .then(data => {
                console.log("Success:", data);
                document.getElementById("contact-form").innerHTML = `<p class="page-paragraph-success">Hvala za vaše sporočilo! Odgovorili vam bomo v najkrajšem možnem času.</p>`;
                setTimeout(() => {
                    window.location.href = "/";
                }, 3000);
            })
            .catch((error) => {
                console.error("Error:", error);
                document.getElementById("contact-form").innerHTML = `<p class="page-paragraph-error">Prišlo je do napake pri pošiljanju vašega sporočila. Prosimo, poskusite znova pozneje.</p>`;
                setTimeout(() => {
                    window.location.href = "/";
                }, 3000);
            });

            // TODO: Popravi margin pri success in error textu da ne bo offsetan

        });
    } else if (contactFormContainer) {
        contactFormContainer.innerHTML = `<p class="page-paragraph">Za pošiljanje sporočila se morate prijaviti.</p>`;
    }
});