// resources/js/nit-typeahead.js
export function initSedeSearch(rootEl) {
  if (!rootEl) return;

  // Elementos
  const selMunicipio = rootEl.querySelector('#municipio');
  const nitInput     = rootEl.querySelector('#nitInput');
  const nitResults   = rootEl.querySelector('#nitResults');
  const nitHint      = rootEl.querySelector('#nitHint');
  const btnContinuar = document.getElementById('btnContinuar');

  const hdMun = document.getElementById('hd_municipio');
  const hdNit = document.getElementById('hd_nit');
  const form  = document.getElementById('formBuscar');

  // Endpoints
  const URL_NITS  = rootEl.dataset.urlNits;   // ?q=...&limit=20
  const URL_SEDES = rootEl.dataset.urlSedes;  // ?nit=...

  // Config
  const MIN_CHARS = 3;
  const LIMIT     = 20;

  // Estado
  let abortCtrl = null;
  let typingTimer = null;
  let items = [];        // [{ nit, label }]
  let activeIndex = -1;

  // Init UI
  selMunicipio.innerHTML = '<option value="">Seleccione...</option>';
  selMunicipio.disabled = true;
  btnContinuar.disabled = true;
  nitInput.disabled = false;
  nitResults.parentElement.style.position = 'relative';
  nitInput.setAttribute('role', 'combobox');
  nitInput.setAttribute('aria-autocomplete', 'list');
  nitInput.setAttribute('aria-controls', 'nitResults');
  nitResults.setAttribute('role', 'listbox');
  setHint(`Escribe al menos ${MIN_CHARS} caracteres para buscar.`);

  // Helpers
  function setHint(msg, tone = 'gray') {
    nitHint.textContent = msg;
    nitHint.className = `text-sm mt-2 text-${tone}-600`;
  }
  function toggleResults(show) {
    nitResults.classList.toggle('hidden', !show);
    nitInput.setAttribute('aria-expanded', String(show));
  }
  function readyToSubmit() {
    return !!(hdNit.value && hdMun.value);
  }
  const AUTO_SUBMIT = false; // Solo continuar desde el botón
  function maybeSubmit() {
    if (AUTO_SUBMIT && readyToSubmit()) form.requestSubmit();
  }
  function resetMunicipios() {
    selMunicipio.innerHTML = '<option value="">Seleccione...</option>';
    selMunicipio.disabled = true;
    hdMun.value = '';
  }

  // Render resultados NIT
  function renderNitResults(list, message = null) {
    items = Array.isArray(list) ? list : [];
    activeIndex = -1;
    nitResults.innerHTML = '';

    if (message) {
      const div = document.createElement('div');
      div.className = 'px-3 py-2 text-sm text-gray-600';
      div.textContent = message;
      nitResults.appendChild(div);
    }

    items.forEach((it, idx) => {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'nit-option w-full text-left px-3 py-2 hover:bg-gray-100';
      btn.id = `nit-opt-${idx}`;
      btn.setAttribute('role', 'option');
      btn.setAttribute('aria-selected', 'false');
      btn.textContent = it.label || it.nit;
      btn.addEventListener('mouseenter', () => setActiveIndex(idx));
      btn.addEventListener('click', () => selectNit(idx));
      nitResults.appendChild(btn);
    });

    toggleResults(nitResults.children.length > 0);
  }

  function setActiveIndex(idx) {
    const options = nitResults.querySelectorAll('.nit-option');
    options.forEach((el, i) => {
      const on = i === idx;
      el.classList.toggle('bg-blue-50', on);
      el.classList.toggle('ring-1', on);
      el.classList.toggle('ring-blue-300', on);
      el.setAttribute('aria-selected', on ? 'true' : 'false');
      if (on) {
        nitInput.setAttribute('aria-activedescendant', el.id);
        el.scrollIntoView({ block: 'nearest' });
      }
    });
    activeIndex = idx;
  }
  function moveActive(delta) {
    if (nitResults.classList.contains('hidden') || items.length === 0) return;
    if (activeIndex === -1) setActiveIndex(delta > 0 ? 0 : items.length - 1);
    else {
      let next = activeIndex + delta;
      if (next < 0) next = items.length - 1;
      if (next >= items.length) next = 0;
      setActiveIndex(next);
    }
  }

  // SelecciÃ³n de NIT â†’ cargar sedes (municipios)
  async function selectNit(idx) {
    if (idx < 0 || idx >= items.length) return;
    const it = items[idx];

    nitInput.value = it.label || it.nit;
    hdNit.value = it.nit;
    toggleResults(false);
    nitResults.innerHTML = '';
    setHint(`Seleccionado: ${it.label || it.nit}`);

    resetMunicipios();

    // 1) si el item ya trae sedes, Ãºsalas; si no, pide al backend
    let sedes = Array.isArray(it.sedes) ? it.sedes : [];
    if (!sedes.length) {
      if (!URL_SEDES) {
        setHint('No hay endpoint de sedes configurado.', 'red');
        return;
      }
      try {
        const u = new URL(URL_SEDES, window.location.origin);
        u.searchParams.set('nit', it.nit);
        const res = await fetch(u.toString());
        sedes = await res.json(); // [{ municipio_id, municipio_nombre }, ...]
      } catch {
        setHint('Error cargando sedes del NIT.', 'red');
        return;
      }
    }

    // 2) poblar select de municipio (sede)
    const seen = new Set();
    sedes.forEach(s => {
      const id = String(s.municipio_id);
      if (!id || seen.has(id)) return;
      seen.add(id);
      const opt = document.createElement('option');
      opt.value = id;
      opt.textContent = s.municipio_nombre || id;
      selMunicipio.appendChild(opt);
    });

    selMunicipio.disabled = seen.size === 0;

    // 3) si solo hay 1 sede â†’ selecciÃ³n automÃ¡tica + submit
    if (!selMunicipio.disabled && selMunicipio.options.length === 2) {
      selMunicipio.selectedIndex = 1;
      hdMun.value = selMunicipio.value;
      btnContinuar.disabled = !readyToSubmit();
      return; // no auto-submit
    }

    // 4) si hay varias, espera que el usuario elija
    btnContinuar.disabled = !readyToSubmit();
    if (!selMunicipio.disabled) selMunicipio.focus();
  }

  // BÃºsqueda NIT con debounce + abort
  const doSearch = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(fetchNitSuggestions, 300);
  };
  async function fetchNitSuggestions() {
    toggleResults(false);
    nitResults.innerHTML = '';

    const q = (nitInput.value || '').trim();
    if (q.length < MIN_CHARS) {
      setHint(`Escribe al menos ${MIN_CHARS} caracteres para buscar.`);
      return;
    }
    if (!URL_NITS) {
      setHint('Endpoint de NITs no configurado.', 'red');
      return;
    }
    if (abortCtrl) abortCtrl.abort();
    abortCtrl = new AbortController();

    setHint('Buscandoâ€¦');
    try {
      const url = new URL(URL_NITS, window.location.origin);
      url.searchParams.set('q', q);
      url.searchParams.set('limit', LIMIT);
      const res = await fetch(url.toString(), { signal: abortCtrl.signal });
      const data = await res.json();
      const list = Array.isArray(data.items) ? data.items : [];
      setHint(data.message ?? (list.length ? 'Resultados:' : 'Sin coincidencias.'));
      renderNitResults(list, list.length ? null : (data.message || 'Sin coincidencias.'));
    } catch (e) {
      if (e.name !== 'AbortError') {
        setHint('Error buscando NITs.', 'red');
        renderNitResults([], 'Error al buscar.');
      }
    }
  }

  // Eventos
  nitInput.addEventListener('input', doSearch);
  nitInput.addEventListener('focus', () => {
    if (nitResults.children.length) toggleResults(true);
  });
  nitInput.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); moveActive(1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); moveActive(-1); }
    else if (e.key === 'Enter') {
      if (!nitResults.classList.contains('hidden') && activeIndex >= 0) {
        e.preventDefault(); selectNit(activeIndex);
      }
    } else if (e.key === 'Escape') {
      toggleResults(false);
    }
  });
  document.addEventListener('click', (e) => {
    if (!nitResults.contains(e.target) && e.target !== nitInput) toggleResults(false);
  });

  selMunicipio.addEventListener('change', () => {
    hdMun.value = selMunicipio.value || '';
    btnContinuar.disabled = !readyToSubmit();
  });
}

