<script>
// Type-to-search account picker. Mirrors item_autocomplete.php but keyed to
// window.ACCOUNTS_DATA (array of {id, code, name}) and separate class names
// so both can appear on the same page without clashing.
//
// Uses a single shared dropdown attached to <body> with `position: fixed`,
// positioned from the active input's live screen coordinates - this is
// deliberate (see item_autocomplete.php for the full explanation): a
// per-row `position: absolute` dropdown gets silently clipped whenever its
// row lives inside a horizontally-scrollable table wrapper.
(function () {
  let activeWrapper = null;
  let activeInput = null;

  const dd = document.createElement('div');
  dd.id = 'sharedAccountDropdown';
  dd.style.cssText = 'display:none;position:fixed;z-index:9999;background:#fff;border:1px solid #e2e8f0;border-radius:0.5rem;margin-top:4px;max-height:220px;overflow-y:auto;box-shadow:0 10px 25px rgba(0,0,0,.15);font-size:0.875rem;';
  document.addEventListener('DOMContentLoaded', () => document.body.appendChild(dd));
  if (document.readyState !== 'loading') document.body.appendChild(dd);

  function positionDropdown(input) {
    const rect = input.getBoundingClientRect();
    dd.style.left = rect.left + 'px';
    dd.style.top = rect.bottom + 'px';
    dd.style.width = Math.max(rect.width, 240) + 'px';
  }

  function renderDropdown(wrapper, input, query) {
    const q = query.trim().toLowerCase();
    if (!q) { hideDropdown(); return; }

    const matches = (window.ACCOUNTS_DATA || [])
      .filter(a => a.name.toLowerCase().includes(q) || a.code.toLowerCase().includes(q))
      .slice(0, 25);
    if (matches.length === 0) {
      dd.innerHTML = '<div class="px-3 py-2 text-slate-400">No matching accounts</div>';
    } else {
      dd.innerHTML = matches.map(a =>
        `<div class="account-option px-3 py-2 hover:bg-blue-50 cursor-pointer" data-id="${a.id}" data-label="${a.code} - ${a.name.replace(/"/g,'&quot;')}">${a.code} - ${a.name}</div>`
      ).join('');
    }
    activeWrapper = wrapper;
    activeInput = input;
    positionDropdown(input);
    dd.style.display = 'block';
  }

  function hideDropdown() {
    dd.style.display = 'none';
    activeWrapper = null;
    activeInput = null;
  }

  document.addEventListener('input', function (e) {
    if (!e.target.matches('.account-search')) return;
    const wrapper = e.target.closest('.account-autocomplete');
    wrapper.querySelector('.account-id-input').value = '';
    renderDropdown(wrapper, e.target, e.target.value);
  });

  document.addEventListener('focus', function (e) {
    if (!e.target.matches('.account-search')) return;
    const wrapper = e.target.closest('.account-autocomplete');
    if (e.target.value) renderDropdown(wrapper, e.target, e.target.value);
  }, true);

  window.addEventListener('scroll', function () { if (activeInput && dd.style.display === 'block') positionDropdown(activeInput); }, true);
  window.addEventListener('resize', function () { if (activeInput && dd.style.display === 'block') positionDropdown(activeInput); });

  document.addEventListener('click', function (e) {
    const option = e.target.closest('.account-option');
    if (option && dd.contains(option)) {
      if (activeWrapper) {
        activeWrapper.querySelector('.account-search').value = option.dataset.label;
        activeWrapper.querySelector('.account-id-input').value = option.dataset.id;
      }
      hideDropdown();
      return;
    }
    if (!e.target.matches('.account-search')) hideDropdown();
  });
})();
</script>
