// Tag chip input widget
// Usage: call initTagInput('hiddenFieldId', 'containerId') after DOM ready
// The hidden field stores comma-separated tags.
// The container receives: a normal form-control input + a chips area below it.
// Optional: pass { suggestions: ['tag1', 'tag2'] } as third argument to show clickable suggestion chips.
// Returns: { addTag, clear } for external control.

function initTagInput(hiddenId, containerId, options) {
    const hidden = document.getElementById(hiddenId);
    const container = document.getElementById(containerId);
    if (!hidden || !container) return { addTag: function() {}, clear: function() {} };

    // Clear any previous render
    container.innerHTML = '';

    // Normal fixed-height text input
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'form-control';
    input.placeholder = 'Add tag\u2026';
    input.autocomplete = 'off';

    // Chips live below the input — does not affect input height
    const chipsArea = document.createElement('div');
    chipsArea.className = 'tag-chips-area';

    container.appendChild(input);
    container.appendChild(chipsArea);

    let tags = hidden.value
        ? hidden.value.split(',').map(t => t.trim()).filter(Boolean)
        : [];

    function escapeHtml(str) {
        return str
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function renderTags() {
        chipsArea.innerHTML = '';
        tags.forEach((tag, i) => {
            const chip = document.createElement('span');
            chip.className = 'badge rounded-pill bg-info text-dark tag-chip';
            chip.innerHTML =
                `${escapeHtml(tag)}` +
                `<span class="tag-remove ms-1" data-index="${i}" aria-label="Remove" role="button">&times;</span>`;
            chipsArea.appendChild(chip);
        });
        hidden.value = tags.join(',');
    }

    function addTag(val) {
        const trimmed = val.trim().replace(/,/g, '').slice(0, 50);
        if (trimmed && !tags.includes(trimmed)) {
            tags.push(trimmed);
            renderTags();
        }
    }

    input.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            addTag(input.value);
            input.value = '';
        } else if (e.key === 'Backspace' && input.value === '' && tags.length > 0) {
            tags.pop();
            renderTags();
        }
    });

    input.addEventListener('blur', () => {
        if (input.value.trim()) {
            addTag(input.value);
            input.value = '';
        }
    });

    chipsArea.addEventListener('click', e => {
        if (e.target.classList.contains('tag-remove')) {
            const idx = parseInt(e.target.dataset.index, 10);
            tags.splice(idx, 1);
            renderTags();
        }
    });

    // Render suggestion chips if provided
    if (options && options.suggestions && options.suggestions.length > 0) {
        const suggestionsRow = document.createElement('div');
        suggestionsRow.className = 'd-flex flex-wrap align-items-center gap-1 mt-2';
        suggestionsRow.innerHTML = '<small class="text-muted">Suggested:</small>';
        options.suggestions.forEach(s => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'btn btn-outline-secondary btn-sm py-0 px-2';
            btn.style.fontSize = '0.78rem';
            btn.textContent = s;
            btn.addEventListener('click', () => addTag(s));
            suggestionsRow.appendChild(btn);
        });
        container.appendChild(suggestionsRow);
    }

    renderTags();

    return {
        addTag: addTag,
        clear: function() {
            tags = [];
            input.value = '';
            renderTags();
        }
    };
}
