(function() {
    if (window.nxtfIconPickerInit) return;
    window.nxtfIconPickerInit = true;
    var ICONS = window.nxtfIconPickerIcons || [];
    if (!Array.isArray(ICONS)) {
        ICONS = [];
    }

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

    function getItemClasses(isSelected) {
        return 'nxtf-icon-picker-item' + (isSelected ? ' is-selected' : '');
    }

    function ensureIconItems(container) {
        var grid = container ? container.querySelector('[data-icon-grid]') : null;
        if (!grid || grid.getAttribute('data-icon-loaded') === '1') {
            return;
        }

        var input = container.querySelector('[data-icon-picker-input]');
        var selectedIcon = input ? String(input.value || '') : '';
        var isLocked = isContainerLocked(container);
        var html = '';

        ICONS.forEach(function(icon) {
            var isSelected = selectedIcon === icon;
            var iconName = icon.replace('dashicons-', '');

            html += '<button type="button" data-icon-item="' + escapeAttr(icon) + '" title="' + escapeAttr(iconName) + '"'
                + ' class="' + getItemClasses(isSelected) + '"'
                + (isLocked ? ' disabled' : '')
                + '><span class="nxtf-icon-picker-item-icon dashicons ' + escapeAttr(icon) + '"></span></button>';
        });

        grid.innerHTML = html;
        grid.setAttribute('data-icon-loaded', '1');
    }

    function init() {
        document.addEventListener('click', handleClick);
        document.addEventListener('input', handleInput);
        closeAllDropdowns();
    }

    function handleClick(e) {
        var container = e.target.closest('.nxtf-icon-picker');

        if (!container) {
            closeAllDropdowns();
            return;
        }

        if (isContainerLocked(container)) {
            if (e.target.closest('[data-icon-toggle]') || e.target.closest('[data-icon-item]') || e.target.closest('[data-icon-clear]')) {
                e.preventDefault();
                e.stopPropagation();
            }
            return;
        }

        if (e.target.closest('[data-icon-toggle]')) {
            e.preventDefault();
            e.stopPropagation();
            var dropdown = container.querySelector('[data-icon-dropdown]');
            var isOpen = container.classList.contains('nxtf-icon-picker--open');

            closeAllDropdowns();

            if (!isOpen && dropdown) {
                ensureIconItems(container);
                container.classList.add('nxtf-icon-picker--open');
                var searchInput = dropdown.querySelector('[data-icon-search]');
                if (searchInput) {
                    searchInput.value = '';
                    searchInput.focus();
                    container.querySelectorAll('[data-icon-item]').forEach(function(item) {
                        item.classList.remove('is-hidden');
                    });
                }
            }
            return;
        }

        var iconItem = e.target.closest('[data-icon-item]');
        if (iconItem) {
            e.preventDefault();
            selectIcon(container, iconItem.getAttribute('data-icon-item'));
            closeDropdown(container);
            return;
        }

        var clearBtn = e.target.closest('[data-icon-clear]');
        if (clearBtn) {
            e.preventDefault();
            clearIcon(container);
            closeDropdown(container);
            return;
        }
    }

    function handleInput(e) {
        if (!e.target.hasAttribute('data-icon-search')) return;
        var container = e.target.closest('.nxtf-icon-picker');
        if (!container) return;
        if (isContainerLocked(container)) return;
        ensureIconItems(container);
        var search = e.target.value.toLowerCase();
        container.querySelectorAll('[data-icon-item]').forEach(function(item) {
            var iconName = item.getAttribute('data-icon-item').toLowerCase();
            item.classList.toggle('is-hidden', iconName.indexOf(search) === -1);
        });
    }

    function selectIcon(container, icon) {
        if (isContainerLocked(container)) return;

        var input = container.querySelector('[data-icon-picker-input]');
        var toggleBtn = container.querySelector('[data-icon-toggle]');
        if (!input || !toggleBtn) return;

        var toggleIcon = toggleBtn.querySelector('.nxtf-icon-picker-toggle-icon');
        var label = toggleBtn.querySelector('[data-icon-label]');
        var clearBtn = container.querySelector('[data-icon-clear]');

        input.value = icon;
        if (toggleIcon) {
            toggleIcon.className = 'nxtf-icon-picker-toggle-icon dashicons ' + icon;
        }
        if (label) label.textContent = icon;
        if (clearBtn) {
            setClearButtonState(container, clearBtn, true);
        }

        container.querySelectorAll('[data-icon-item]').forEach(function(item) {
            item.classList.toggle('is-selected', item.getAttribute('data-icon-item') === icon);
        });

        input.dispatchEvent(new Event('change', { bubbles: true }));
    }

    function clearIcon(container) {
        if (isContainerLocked(container)) return;

        var input = container.querySelector('[data-icon-picker-input]');
        var toggleBtn = container.querySelector('[data-icon-toggle]');
        if (!input || !toggleBtn) return;

        var toggleIcon = toggleBtn.querySelector('.nxtf-icon-picker-toggle-icon');
        var label = toggleBtn.querySelector('[data-icon-label]');
        var clearBtn = container.querySelector('[data-icon-clear]');

        input.value = '';
        if (toggleIcon) {
            toggleIcon.className = 'nxtf-icon-picker-toggle-icon dashicons dashicons-admin-generic';
        }
        if (label) label.textContent = 'Select an icon';
        if (clearBtn) {
            setClearButtonState(container, clearBtn, false);
        }

        container.querySelectorAll('[data-icon-item]').forEach(function(item) {
            item.classList.remove('is-selected');
        });

        input.dispatchEvent(new Event('change', { bubbles: true }));
    }

    function closeDropdown(container) {
        if (container) {
            container.classList.remove('nxtf-icon-picker--open');
        }
    }

    function isContainerLocked(container) {
        return !!(container && container.classList.contains('nxtf-icon-picker-locked'));
    }

    function setClearButtonState(container, clearBtn, hasValue) {
        if (!clearBtn) return;

        var isLocked = isContainerLocked(container);
        clearBtn.disabled = isLocked || !hasValue;
    }

    function closeAllDropdowns() {
        document.querySelectorAll('.nxtf-icon-picker').forEach(function(container) {
            container.classList.remove('nxtf-icon-picker--open');
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
