// Tag editor shared between create/edit project pages.
// Autocompletes against /api/tags/autocomplete/ and lets users create new
// tags (unprefixed → general). Populates the hidden `tags` input as
// "category:name category:name …" on submit.
(function () {
    const input = document.getElementById('tag-input');
    if (!input) return;
    const suggestions = document.getElementById('tag-suggestions');
    const chips = document.getElementById('tag-chips');
    const hidden = document.getElementById('id_tags');

    // category slug -> color, provided by the server (json_script).
    const colorMap = {};
    try {
        const el = document.getElementById('packs-tag-categories');
        if (el) JSON.parse(el.textContent).forEach(c => { colorMap[c.slug] = c.color; });
    } catch (e) { /* ignore */ }

    const tags = new Map(); // "category:name" -> {category, name, color}

    function render() {
        chips.innerHTML = '';
        tags.forEach((tag) => {
            const chip = document.createElement('span');
            chip.className = 'tag-chip';
            chip.style.borderColor = tag.color;
            chip.style.color = tag.color;
            chip.textContent = tag.name;
            const x = document.createElement('button');
            x.type = 'button';
            x.className = 'tag-chip-remove';
            x.textContent = '×';
            x.title = 'Remove tag';
            x.setAttribute('aria-label', 'Remove tag ' + tag.name);
            x.addEventListener('click', () => { tags.delete(tag.category + ':' + tag.name); render(); });
            chip.appendChild(x);
            chips.appendChild(chip);
        });
        hidden.value = Array.from(tags.values()).map(t => t.category + ':' + t.name).join(' ');
        document.dispatchEvent(new CustomEvent('tags-changed', { detail: { tags: hidden.value } }));
    }

    function addTag(category, name, color) {
        const canonical = category.toLowerCase();
        color = color || colorMap[canonical] || '#666666';
        tags.set(canonical + ':' + name, { category: canonical, name, color });
        render();
    }

    (hidden.value || '').split(' ').filter(Boolean).forEach(raw => {
        const [category, ...rest] = raw.split(':');
        addTag(category, rest.join(':'));
    });

    let timer = null;
    input.addEventListener('input', () => {
        clearTimeout(timer);
        const q = input.value.trim();
        if (!q) { suggestions.hidden = true; return; }
        timer = setTimeout(async () => {
            try {
                const resp = await fetch(
                    "/api/tags/autocomplete/?q=" + encodeURIComponent(q),
                    { headers: { 'Accept': 'application/json' } }
                );
                const results = await resp.json();
                suggestions.innerHTML = '';
                for (const t of results.slice(0, 8)) {
                    const item = document.createElement('button');
                    item.type = 'button';
                    item.className = 'tag-suggestion';
                    item.innerHTML = '<span class="tag-dot" style="background:' + t.color + ';"></span> ' +
                        '<strong>' + t.name + '</strong> <small>(' + t.category_name + ')</small>';
                    item.addEventListener('click', () => { addTag(t.category, t.name, t.color); input.value = ''; suggestions.hidden = true; });
                    suggestions.appendChild(item);
                }
                suggestions.hidden = results.length === 0;
            } catch (e) {
                suggestions.hidden = true;
            }
        }, 200);
    });

    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            const q = input.value.trim();
            if (!q) return;
            const [category, ...rest] = q.includes(':') ? q.split(':') : ['general', q];
            const name = rest.join(':').trim();
            if (name) addTag(category, name);
            input.value = '';
            suggestions.hidden = true;
        }
        if (e.key === 'Escape') suggestions.hidden = true;
    });

    document.addEventListener('click', (e) => {
        if (!e.target.closest('.tag-editor')) suggestions.hidden = true;
    });
})();
