(function () {
  function items() {
    return Array.from(document.querySelectorAll('[data-nav-item]')).filter(function (el) {
      return !el.hasAttribute('disabled') && el.offsetParent !== null;
    });
  }

  function move(delta) {
    var all = items();
    if (all.length === 0) return;
    var active = document.activeElement;
    var index = all.indexOf(active);
    if (index < 0) index = delta > 0 ? -1 : 0;
    var next = all[(index + delta + all.length) % all.length];
    next.focus();
  }

  function first(selector) {
    var el = document.querySelector(selector);
    if (el) el.focus();
  }

  function activateHotkey(key) {
    var el = document.querySelector('[data-hotkey="' + key.toLowerCase() + '"]');
    if (!el) return false;
    el.click();
    return true;
  }

  document.addEventListener('keydown', function (event) {
    if (event.altKey || event.ctrlKey || event.metaKey) return;
    if (event.key === 'ArrowDown' || event.key === 'j') {
      event.preventDefault();
      move(1);
    } else if (event.key === 'ArrowUp' || event.key === 'k') {
      event.preventDefault();
      move(-1);
    } else if (activateHotkey(event.key)) {
      event.preventDefault();
    } else if (event.key === 'g') {
      event.preventDefault();
      first('[data-nav-target="guide"]');
    } else if (event.key === 'i') {
      event.preventDefault();
      first('[data-nav-target="install"]');
    } else if (event.key === 'h') {
      event.preventDefault();
      first('[data-nav-target="home"]');
    } else if (event.key === 'l') {
      event.preventDefault();
      first('[data-nav-target="llms"]');
    } else if (event.key === 'Escape') {
      if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
    }
  });
})();
