// Author  Raivis Rampāns
// Created 09.06.2025
// Editor Raivis
// Modified 09.06.2025

document.addEventListener("DOMContentLoaded", function () {
    const categoryInput = document.getElementById("categoryInput");
    const categoryTags = document.getElementById("categoryTags");
    const form = document.getElementById("shareForm");

    let categories = [];

    categoryInput.addEventListener("keydown", function (e) {
        if (e.key === "Enter") {
            e.preventDefault();
            const value = categoryInput.value.trim().toLowerCase();
            if (value !== "" && categories.length < 3 && !categories.includes(value)) {
                categories.push(value);
                renderCategories();
                categoryInput.value = "";
            }
        }
    });

    function renderCategories() {
        categoryTags.innerHTML = "";

        categories.forEach((cat, index) => {
            const tag = document.createElement("span");
            tag.className = "badge bg-secondary d-flex align-items-center";
            tag.style.gap = "6px";
            tag.innerHTML = `
                ${cat}
                <button type="button" class="btn-close btn-close-white btn-sm" data-index="${index}" aria-label="Remove"></button>
                <input type="hidden" name="categories[]" value="${cat}">
            `;
            categoryTags.appendChild(tag);
        });
    }

    categoryTags.addEventListener("click", function (e) {
        if (e.target.matches(".btn-close")) {
            const index = e.target.getAttribute("data-index");
            categories.splice(index, 1);
            renderCategories();
        }
    });
});