document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('search-input');
    const coauthorsOptions = document.getElementById('coauthors-options');
    const selectedCoauthors = document.getElementById('selected-coauthors');
    const hiddenField = document.getElementById('authorkit-coauthors-input');

    function updateHiddenField() {
        const selectedIds = Array.from(selectedCoauthors.querySelectorAll('.coauthor-item')).map(item => item.dataset.userId);
        hiddenField.value = selectedIds.join(',');
    }

    // Filter and display coauthors options based on search input
    searchInput.addEventListener('keyup', function () {
        const filter = searchInput.value.toLowerCase();

        if (filter.trim() === '') {
            coauthorsOptions.style.display = 'none';
            return;
        }

        let hasMatch = false;
        Array.from(coauthorsOptions.querySelectorAll('li')).forEach(option => {
            const text = option.querySelector('span').textContent.toLowerCase();
            const matches = text.includes(filter);
            option.style.display = matches ? '' : 'none';
            if (matches) hasMatch = true;
        });

        coauthorsOptions.style.display = hasMatch ? 'block' : 'none';
    });

    // Close Coauthors options when user click outside of search box
    document.addEventListener('click', function (e) {
        if (!searchInput.contains(e.target)) {
            coauthorsOptions.style.display = 'none';
        }
    });


    // Add selected user to co-authors list
    coauthorsOptions.addEventListener('click', function (e) {
        const option = e.target.closest('li');
        if (option) {
            const userId = option.dataset.userId;
            const userName = option.querySelector('span').textContent;
            const userAvatar = option.dataset.avatar;

            // Add selected co-author to the list
            const coauthorItem = document.createElement('div');
            coauthorItem.className = 'coauthor-item';
            coauthorItem.dataset.userId = userId;
            coauthorItem.dataset.displayName = userName;
            coauthorItem.innerHTML = `
						<img src="${userAvatar}" alt="${userName}" width="32" height="32" />
						${userName}
						<button type="button" class="remove-coauthor" data-user-id="${userId}" data-display-name="${userName}">×</button>
					`;
            selectedCoauthors.appendChild(coauthorItem);

            // Remove from options
            option.remove();
            updateHiddenField();
        }
    });

    // Remove co-author and add back to options
    selectedCoauthors.addEventListener('click', function (e) {
        if (e.target.classList.contains('remove-coauthor')) {
            const userId = e.target.dataset.userId;
            const displayName = e.target.dataset.displayName;
            const coauthorItem = e.target.closest('.coauthor-item');

            // Add back to options
            const newOption = document.createElement('li');
            newOption.dataset.userId = userId;
            newOption.dataset.avatar = coauthorItem.querySelector('img').src;
            newOption.innerHTML = `
						<img src="${newOption.dataset.avatar}" alt="${coauthorItem.textContent.trim()}" width="24" height="24" />
						<span>${displayName}</span>`;
            coauthorsOptions.appendChild(newOption);

            // Remove from selected list
            coauthorItem.remove();
            updateHiddenField();
        }
    });
});
