// assets/js/roster.js
console.log('Roster JS Loaded');

document.addEventListener('DOMContentLoaded', function () {
    // 1. Read Data
    let membersList = [];
    const dataEl = document.getElementById('roster-data');
    if (dataEl) {
        try {
            membersList = JSON.parse(dataEl.textContent);
            console.log('Roster Members Loaded:', membersList.length);
        } catch (e) {
            console.error('Failed to parse roster data', e);
        }
    }

    // 2. Setup UI
    const containers = document.querySelectorAll('.tag-input-container');
    const suggestionBox = document.createElement('div');
    suggestionBox.id = 'member-suggestions';
    document.body.appendChild(suggestionBox);

    containers.forEach(container => {
        const input = container.querySelector('.tag-input');

        // Attach event listeners to EXISTING tags
        container.querySelectorAll('.tag .remove').forEach(btn => {
            btn.addEventListener('click', function () {
                if (container.classList.contains('disabled')) return;
                this.closest('.tag').remove();
                updateHidden(container);
            });
        });

        if (!input) return; // Read only mode

        input.addEventListener('input', function () {
            const val = this.value.trim().toLowerCase();
            // console.log('Search:', val);

            if (val.length < 1) {
                suggestionBox.style.display = 'none';
                return;
            }

            const matches = membersList.filter(m => m.name.toLowerCase().includes(val));
            showSuggestions(matches, this);
        });

        // Hide delay
        input.addEventListener('blur', () => {
            setTimeout(() => { suggestionBox.style.display = 'none'; }, 200);
        });

        input.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                const val = this.value.trim();
                if (val) {
                    addTag(container.querySelector('.tags-list'), val, '');
                    updateHidden(container);
                    this.value = '';
                    suggestionBox.style.display = 'none';
                }
            }
        });
    });

    function showSuggestions(matches, inputElement) {
        suggestionBox.innerHTML = '';
        if (matches.length === 0) {
            suggestionBox.style.display = 'none';
            return;
        }

        matches.slice(0, 10).forEach(m => {
            const div = document.createElement('div');
            div.className = 'suggestion-item';
            div.textContent = m.name;
            div.addEventListener('click', () => {
                const container = inputElement.closest('.tag-input-container');
                const list = container.querySelector('.tags-list');
                addTag(list, m.name, m.id);
                updateHidden(container);
                inputElement.value = '';
                suggestionBox.style.display = 'none';
                inputElement.focus();
            });
            suggestionBox.appendChild(div);
        });

        const rect = inputElement.getBoundingClientRect();
        suggestionBox.style.top = (window.scrollY + rect.bottom) + 'px';
        suggestionBox.style.left = (window.scrollX + rect.left) + 'px';
        suggestionBox.style.display = 'block';
    }

    function addTag(list, name, id) {
        const tag = document.createElement('span');
        tag.className = 'tag';
        tag.dataset.id = id || '';
        tag.dataset.name = name;
        tag.innerHTML = `${name} <span class="remove">&times;</span>`;

        const removeBtn = tag.querySelector('.remove');
        removeBtn.addEventListener('click', function () {
            if (list.closest('.disabled')) return;
            tag.remove();
            updateHidden(list.closest('.tag-input-container'));
        });
        list.appendChild(tag);
    }

    function updateHidden(container) {
        const list = container.querySelector('.tags-list');
        const hidden = container.querySelector('.assignments-json');
        const data = Array.from(list.children).map(t => ({
            id: t.dataset.id,
            name: t.dataset.name
        }));
        hidden.value = JSON.stringify(data);
    }
});
