const kljuc = new URLSearchParams(window.location.search).get("kljuc");

function getCookie(name) {
    const match = document.cookie.split(";").map(c => c.trim()).find(c => c.startsWith(name + "="));
    return match ? match.split("=")[1] : null;
}

function getKey() {
    const url = `https://ssnj.dcrubro.com/api/vnos`;
    fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            pk: kljuc
        })
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            console.error("API Error:", data.message);
            return;
        }

        let build = `
            <h3 class="entry-title">${data.data.kljuc}</h3>
            <p class="entry-definition">${data.data.tip}</p>
            ${data.data.vsebina}
            <p class="entry-example">${data.data.primer}</p>
            <p class="entry-example">Vnos dodal: ${data.data.avtor}</p>
        `;

        // Voting UI: up, sum, down
        const voteSum = Number(data.data.ocenaSuma) || 0;
        const voteHtml = `
            <div class="vote-controls" style="display:flex;align-items:center;gap:8px;margin-top:8px;">
                <button id="vote-up" class="page-btn" aria-label="Upvote">▲</button>
                <span id="vote-sum" style="min-width:36px;text-align:center;font-weight:600;">${voteSum}</span>
                <button id="vote-down" class="page-btn" aria-label="Downvote">▼</button>
            </div>
        `;

        build += voteHtml;

        // Preveri lastinino
        let addIf = ``;

        if (data.data.avtor === getCookie("username")) {
            addIf = `<br><button id="delete-entry-button" class="page-btn nav-btn-danger">Izbriši vnos</button>`;
        }

        build += addIf;

        document.getElementById("page-title").innerText = `Vnos '${data.data.kljuc}'`;
        // replace contents (avoid appending duplicates)
        document.getElementById("entry-container-single").innerHTML = build;

        // Initialize vote state after rendering
        initVoting(data.data);

        document.getElementById("delete-entry-button")?.addEventListener("click", () => {
            document.getElementById("delete-entry-modal").style.visibility = "visible";
        });

        document.getElementById("cancel-delete")?.addEventListener("click", () => {
            document.getElementById("delete-entry-modal").style.visibility = "hidden";
        });

        document.getElementById("confirm-delete")?.addEventListener("click", () => {
            fetch("https://ssnj.dcrubro.com/api/izbrisi-vnos", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ "token": document.cookie.split(";").find(cookie => cookie.trim().startsWith("token=")).split("=")[1], "pk": kljuc })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return response.json();
            })
            .then(data => {
                console.log("Success:", data);
                window.location.href = "/";
            })
            .catch((error) => {
                console.error("Error:", error);
                document.getElementById("delete-entry-modal").style.visibility = "hidden";
            });
        });

        document.getElementById("close-modal")?.addEventListener("click", () => {
            document.getElementById("delete-entry-modal").style.visibility = "hidden";
        });
    })
    .catch((error) => {
        console.error("Error:", error);
    });
}

getKey();

function initVoting(entryData) {
    const upBtn = document.getElementById("vote-up");
    const downBtn = document.getElementById("vote-down");
    const sumEl = document.getElementById("vote-sum");
    if (!upBtn || !downBtn || !sumEl) return;

    const token = getCookie("token");

    let currentVote = 0;

    function setActive(v) {
        upBtn.classList.toggle("nav-btn-primary", v === 1);
        downBtn.classList.toggle("nav-btn-primary", v === -1);
        currentVote = v;
    }

    if (!token) {
        const showLogin = () => alert("Prijavite se, da lahko glasujete.");
        upBtn.addEventListener("click", showLogin);
        downBtn.addEventListener("click", showLogin);
        return;
    }

    // fetch whether the current user has voted
    fetch("https://ssnj.dcrubro.com/api/semvolil", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token: token, pk: kljuc })
    })
    .then(r => r.json())
    .then(obj => {
        const v = obj?.vote || 0;
        setActive(v);
    })
    .catch(err => console.error("semvolil error", err));

    upBtn.addEventListener("click", () => submitVote(1));
    downBtn.addEventListener("click", () => submitVote(-1));

    function submitVote(vote) {
        const tokenNow = getCookie("token");
        if (!tokenNow) { alert("Prijavite se, da lahko glasujete."); return; }

        // if user clicks the same vote, send 0 to remove it
        const sendVote = (vote === currentVote) ? 0 : vote;

        fetch("https://ssnj.dcrubro.com/api/volI", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ token: tokenNow, pk: kljuc, vote: sendVote })
        })
        .then(r => r.json())
        .then(() => {
            // refresh current score
            return fetch("https://ssnj.dcrubro.com/api/vnos", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ pk: kljuc })
            });
        })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                const newSum = Number(d.data.ocenaSuma) || 0;
                sumEl.innerText = newSum;
                setActive(sendVote);
            }
        })
        .catch(err => console.error("vote error", err));
    }
}