(function () {
  'use strict';

  var searchInput = document.getElementById('api-search');
  if (searchInput) {
    searchInput.addEventListener('input', function () {
      var q = this.value.toLowerCase().trim();
      var cards = document.querySelectorAll('.api-endpoint-card[data-search]');
      cards.forEach(function (card) {
        var text = card.getAttribute('data-search') || '';
        card.style.display = !q || text.indexOf(q) !== -1 ? '' : 'none';
      });
    });
  }

  var sidebar = document.querySelector('.menu-vertical.js-menu-vertical');
  if (!sidebar) {
    return;
  }

  var links = Array.prototype.slice.call(sidebar.querySelectorAll('a[href^="#"]'));
  if (!links.length) {
    return;
  }

  var sectionIds = links.map(function (link) {
    return link.getAttribute('href').slice(1);
  });

  var sections = sectionIds.map(function (id) {
    return document.getElementById(id);
  }).filter(Boolean);

  function setActive(id) {
    links.forEach(function (link) {
      var match = link.getAttribute('href') === '#' + id;
      link.classList.toggle('active', match);
    });
  }

  links.forEach(function (link) {
    link.addEventListener('click', function (e) {
      var id = this.getAttribute('href').slice(1);
      var target = document.getElementById(id);
      if (target) {
        e.preventDefault();
        var top = target.getBoundingClientRect().top + window.pageYOffset - 100;
        window.scrollTo({ top: top, behavior: 'smooth' });
        setActive(id);
      }
    });
  });

  function onScroll() {
    var scrollPos = window.pageYOffset + 140;
    var current = sectionIds[0];

    for (var i = 0; i < sections.length; i++) {
      var section = sections[i];
      if (section.offsetTop <= scrollPos) {
        current = sectionIds[i];
      }
    }

    setActive(current);
  }

  var scrollTimer;
  window.addEventListener('scroll', function () {
    if (scrollTimer) {
      window.cancelAnimationFrame(scrollTimer);
    }
    scrollTimer = window.requestAnimationFrame(onScroll);
  }, { passive: true });

  onScroll();
})();
