var Autocomplete = (function() {

    var items = [];

    function crear(inputId, opts) {
        opts = opts || {};
        var input = document.getElementById(inputId);
        if (!input) {
            console.warn('[AUTO] Input not found:', inputId);
            return null;
        }

        if (document.getElementById(inputId + '_autodd')) {
            return null; // ya inicializado
        }

        var dd = document.createElement('div');
        dd.className = 'prov-ubigeo-dropdown';
        dd.id = inputId + '_autodd';
        dd.style.position = 'fixed';
        dd.style.zIndex = '9999';
        dd.style.display = 'none';

        document.body.appendChild(dd);

        var timer = null;
        var selected = null;
        var fetchedData = [];

        function ocultar() {
            dd.style.display = 'none';
            dd.innerHTML = '';
        }

        function posicionar() {
            var rect = input.getBoundingClientRect();
            dd.style.position = 'fixed';
            dd.style.top = (rect.bottom) + 'px';
            dd.style.left = rect.left + 'px';
            dd.style.width = rect.width + 'px';
            dd.style.maxHeight = '220px';
            dd.style.zIndex = '9999';
        }

        function buscar(valor) {
            if (timer) clearTimeout(timer);
            if (!valor || valor.length < 1) {
                ocultar();
                return;
            }
            timer = setTimeout(function() {
                var url = opts.url + '?q=' + encodeURIComponent(valor);
                if (opts.params) {
                    for (var k in opts.params) {
                        if (opts.params[k]) url += '&' + k + '=' + encodeURIComponent(opts.params[k]);
                    }
                }
                fetch(url)
                    .then(function(r) { return r.json(); })
                    .then(function(res) {
                        posicionar();
                        if (!res.ok || !res.data || res.data.length === 0) {
                            dd.innerHTML = '<div class="prov-ubigeo-dd-empty">Sin resultados</div>';
                            dd.style.display = 'block';
                            return;
                        }
                        fetchedData = res.data;
                        var html = '';
                        fetchedData.forEach(function(item, idx) {
                            var label = typeof item === 'string' ? item : (item[opts.labelField || 'nombre'] || '');
                            var val = typeof item === 'string' ? item : (item[opts.valueField || 'codigo'] || label);
                            html += '<div class="prov-ubigeo-dd-item" data-index="' + idx + '" data-value="' + val.replace(/"/g, '&quot;') + '" data-label="' + label.replace(/"/g, '&quot;') + '">' + label + '</div>';
                        });
                        dd.innerHTML = html;
                        dd.style.display = 'block';

                        dd.querySelectorAll('.prov-ubigeo-dd-item').forEach(function(el) {
                            el.addEventListener('click', function() {
                                var idx = parseInt(this.dataset.index);
                                var item = fetchedData[idx];
                                var label = this.dataset.label;
                                input.value = label;
                                selected = item;
                                ocultar();
                                if (opts.onSelect) opts.onSelect(item, input);
                            });
                        });
                    })
                    .catch(function(err) {
                        posicionar();
                        dd.innerHTML = '<div class="prov-ubigeo-dd-empty" style="color:#e53e3e">Error de conexión</div>';
                        dd.style.display = 'block';
                        console.error('[AUTO] Fetch error:', err);
                    });
            }, 250);
        }

        input.addEventListener('input', function() {
            selected = null;
            buscar(this.value);
        });

        input.addEventListener('blur', function() {
            setTimeout(ocultar, 200);
        });

        input.addEventListener('focus', function() {
            if (fetchedData.length > 0 && this.value) {
                posicionar();
                dd.style.display = 'block';
            }
        });

        input.addEventListener('keydown', function(e) {
            var items = dd.querySelectorAll('.prov-ubigeo-dd-item');
            var active = dd.querySelector('.prov-ubigeo-dd-item.hover');
            var idx = -1;
            if (active) idx = Array.prototype.indexOf.call(items, active);

            if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (items.length === 0) return;
                var next = (idx + 1) % items.length;
                if (active) active.classList.remove('hover');
                items[next].classList.add('hover');
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (items.length === 0) return;
                var prev = (idx - 1 + items.length) % items.length;
                if (active) active.classList.remove('hover');
                items[prev].classList.add('hover');
            } else if (e.key === 'Enter') {
                if (active) {
                    e.preventDefault();
                    active.click();
                }
            } else if (e.key === 'Escape') {
                ocultar();
            }
        });

        var obj = {
            input: input,
            dd: dd,
            obtenerSeleccion: function() { return selected; },
            limpiar: function() {
                input.value = '';
                selected = null;
                fetchedData = [];
                ocultar();
            },
            actualizarParams: function(nuevosParams) {
                opts.params = nuevosParams || {};
            },
            destruir: function() {
                if (dd.parentNode) dd.parentNode.removeChild(dd);
            }
        };

        items.push(obj);
        return obj;
    }

    return { crear: crear };
})();
