/**
 * Override: Searchable category select
 * Se monta sobre el <select id="vly-category"> existente.
 * No modifica el widget original, solo lo envuelve.
 */
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        var nativeSelect = document.getElementById('vly-category');
        if (!nativeSelect) return;

        var field = nativeSelect.closest('.vly-search-field-category');
        if (!field) return;

        // --- Construir estructura ---
        var container = document.createElement('div');
        container.className = 'vly-cat-select';

        // Trigger
        var trigger = document.createElement('button');
        trigger.type = 'button';
        trigger.className = 'vly-cat-select__trigger';
        trigger.setAttribute('aria-haspopup', 'listbox');
        trigger.setAttribute('aria-expanded', 'false');

        var valueSpan = document.createElement('span');
        valueSpan.className = 'vly-cat-select__value';

        var arrowSpan = document.createElement('span');
        arrowSpan.className = 'vly-cat-select__arrow';
        arrowSpan.innerHTML = '<svg viewBox="0 0 12 8" fill="none"><path d="M1 1.5L6 6.5L11 1.5" stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';

        trigger.appendChild(valueSpan);
        trigger.appendChild(arrowSpan);

        // Dropdown
        var dropdown = document.createElement('div');
        dropdown.className = 'vly-cat-select__dropdown';

        // Search
        var searchWrap = document.createElement('div');
        searchWrap.className = 'vly-cat-select__search';

        var searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'vly-cat-select__search-input';
        searchInput.placeholder = '¿A dónde quieres ir?';
        searchInput.setAttribute('autocomplete', 'off');
        searchInput.setAttribute('autocorrect', 'off');
        searchInput.setAttribute('autocapitalize', 'off');
        searchInput.setAttribute('spellcheck', 'false');

        searchWrap.appendChild(searchInput);

        // List
        var list = document.createElement('div');
        list.className = 'vly-cat-select__list';
        list.setAttribute('role', 'listbox');

        // Empty message
        var emptyMsg = document.createElement('div');
        emptyMsg.className = 'vly-cat-select__empty';
        emptyMsg.textContent = 'No se encontraron resultados';

        // Poblar opciones desde el select nativo
        var options = [];
        var nativeOptions = nativeSelect.options;
        for (var i = 0; i < nativeOptions.length; i++) {
            var opt = nativeOptions[i];
            var optEl = document.createElement('div');
            optEl.className = 'vly-cat-select__option';
            optEl.setAttribute('role', 'option');
            optEl.setAttribute('data-value', opt.value);
            optEl.textContent = opt.textContent.trim();

            if (opt.selected) {
                optEl.classList.add('is-selected');
            }

            list.appendChild(optEl);
            options.push(optEl);
        }

        dropdown.appendChild(searchWrap);
        dropdown.appendChild(list);
        dropdown.appendChild(emptyMsg);
        container.appendChild(trigger);
        container.appendChild(dropdown);

        // Insertar en el DOM
        field.appendChild(container);

        // --- Estado ---
        var isOpen = false;
        var focusedIndex = -1;

        // Set initial display value
        updateDisplay();

        function updateDisplay() {
            var selected = nativeSelect.options[nativeSelect.selectedIndex];
            if (selected) {
                valueSpan.textContent = selected.textContent.trim();
                // Si el valor está vacío es el placeholder
                if (selected.value === '') {
                    valueSpan.classList.add('is-placeholder');
                } else {
                    valueSpan.classList.remove('is-placeholder');
                }
            }
        }

        function open() {
            if (isOpen) return;
            isOpen = true;
            container.classList.add('is-open');
            trigger.setAttribute('aria-expanded', 'true');

            // Limpiar búsqueda previa
            searchInput.value = '';
            filterOptions('');
            focusedIndex = -1;

            // Focus en el search input con un pequeño delay para mobile
            setTimeout(function () {
                searchInput.focus({ preventScroll: true });
            }, 50);
        }

        function close() {
            if (!isOpen) return;
            isOpen = false;
            container.classList.remove('is-open');
            trigger.setAttribute('aria-expanded', 'false');
            focusedIndex = -1;
        }

        function selectOption(optEl) {
            var value = optEl.getAttribute('data-value');

            // Actualizar select nativo
            nativeSelect.value = value;
            // Disparar evento change por si hay listeners
            var event;
            try {
                event = new Event('change', { bubbles: true });
            } catch (e) {
                event = document.createEvent('Event');
                event.initEvent('change', true, true);
            }
            nativeSelect.dispatchEvent(event);

            // Actualizar visual
            options.forEach(function (o) {
                o.classList.remove('is-selected');
            });
            optEl.classList.add('is-selected');

            updateDisplay();
            close();
        }

        function filterOptions(query) {
            var q = query.toLowerCase().trim();
            var visibleCount = 0;

            // Normalizar: quitar acentos para búsqueda más flexible
            var qNorm = removeAccents(q);

            options.forEach(function (optEl) {
                var text = optEl.textContent.toLowerCase();
                var textNorm = removeAccents(text);

                if (!q || textNorm.indexOf(qNorm) !== -1) {
                    optEl.classList.remove('is-hidden');
                    visibleCount++;
                } else {
                    optEl.classList.add('is-hidden');
                    optEl.classList.remove('is-focused');
                }
            });

            if (visibleCount === 0) {
                emptyMsg.classList.add('is-visible');
            } else {
                emptyMsg.classList.remove('is-visible');
            }

            focusedIndex = -1;
        }

        function removeAccents(str) {
            // Soporte para navegadores que no tienen normalize
            if (String.prototype.normalize) {
                return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
            }
            return str;
        }

        function getVisibleOptions() {
            return options.filter(function (o) {
                return !o.classList.contains('is-hidden');
            });
        }

        function setFocused(index) {
            var visible = getVisibleOptions();
            // Quitar focus previo
            visible.forEach(function (o) {
                o.classList.remove('is-focused');
            });
            if (index >= 0 && index < visible.length) {
                focusedIndex = index;
                visible[index].classList.add('is-focused');
                // Scroll into view
                visible[index].scrollIntoView({ block: 'nearest' });
            }
        }

        // --- Eventos ---

        // Toggle al hacer click en el trigger
        trigger.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (isOpen) {
                close();
            } else {
                open();
            }
        });

        // Click en una opción
        list.addEventListener('click', function (e) {
            var optEl = e.target.closest('.vly-cat-select__option');
            if (optEl && !optEl.classList.contains('is-hidden')) {
                selectOption(optEl);
            }
        });

        // Touch en opciones (prevenir problemas en iOS)
        list.addEventListener('touchend', function (e) {
            var optEl = e.target.closest('.vly-cat-select__option');
            if (optEl && !optEl.classList.contains('is-hidden')) {
                e.preventDefault();
                selectOption(optEl);
            }
        });

        // Filtrar mientras se escribe
        searchInput.addEventListener('input', function () {
            filterOptions(this.value);
        });

        // Navegación con teclado en el search input
        searchInput.addEventListener('keydown', function (e) {
            var visible = getVisibleOptions();

            if (e.key === 'ArrowDown' || e.keyCode === 40) {
                e.preventDefault();
                var next = focusedIndex + 1;
                if (next < visible.length) {
                    setFocused(next);
                }
            } else if (e.key === 'ArrowUp' || e.keyCode === 38) {
                e.preventDefault();
                var prev = focusedIndex - 1;
                if (prev >= 0) {
                    setFocused(prev);
                }
            } else if (e.key === 'Enter' || e.keyCode === 13) {
                e.preventDefault();
                if (focusedIndex >= 0 && focusedIndex < visible.length) {
                    selectOption(visible[focusedIndex]);
                }
            } else if (e.key === 'Escape' || e.keyCode === 27) {
                close();
                trigger.focus();
            }
        });

        // Teclado en el trigger
        trigger.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.keyCode === 13 ||
                e.key === ' ' || e.keyCode === 32 ||
                e.key === 'ArrowDown' || e.keyCode === 40) {
                e.preventDefault();
                open();
            }
        });

        // Cerrar al hacer click fuera
        document.addEventListener('click', function (e) {
            if (isOpen && !container.contains(e.target)) {
                close();
            }
        });

        // Cerrar al hacer touch fuera (para mobile)
        document.addEventListener('touchstart', function (e) {
            if (isOpen && !container.contains(e.target)) {
                close();
            }
        }, { passive: true });

        // --- Integración con botón "Limpiar" ---
        // Observar cambios en el select nativo para sincronizar
        // (cuando el clear button hace select.selectedIndex = 0)
        var observer = new MutationObserver(function () {
            updateDisplay();
            options.forEach(function (o) {
                o.classList.remove('is-selected');
            });
            var val = nativeSelect.value;
            options.forEach(function (o) {
                if (o.getAttribute('data-value') === val) {
                    o.classList.add('is-selected');
                }
            });
        });

        // Observar cambios en los option del select nativo no es directo,
        // mejor escuchar el evento change
        nativeSelect.addEventListener('change', function () {
            updateDisplay();
            var val = nativeSelect.value;
            options.forEach(function (o) {
                o.classList.remove('is-selected');
                if (o.getAttribute('data-value') === val) {
                    o.classList.add('is-selected');
                }
            });
        });

        // También interceptar reset del form
        var form = nativeSelect.closest('form');
        if (form) {
            form.addEventListener('reset', function () {
                setTimeout(function () {
                    updateDisplay();
                    options.forEach(function (o) {
                        o.classList.remove('is-selected');
                    });
                    if (options[0]) {
                        options[0].classList.add('is-selected');
                    }
                }, 10);
            });
        }

        // Exponer método para resetear externamente si necesario
        container.vlyCatReset = function () {
            nativeSelect.selectedIndex = 0;
            nativeSelect.dispatchEvent(new Event('change', { bubbles: true }));
        };
    });
})();