// Navbar scroll effect for Decoda Documentation
(function () {
  "use strict";

  let navbar;
  let scrollTimer = null;
  let isScrolling = false;

  function initNavbarScrollEffect() {
    navbar = document.querySelector(".navbar");
    if (!navbar) return;

    // Add scroll event listener with throttling
    window.addEventListener("scroll", handleScroll, { passive: true });

    // Initial check
    handleScroll();
  }

  function handleScroll() {
    if (!navbar) return;

    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const threshold = 50; // Pixels to scroll before effect kicks in

    // Clear existing timer
    if (scrollTimer) {
      clearTimeout(scrollTimer);
    }

    // Add scrolling class immediately
    if (scrollTop > threshold && !isScrolling) {
      navbar.classList.add("navbar--scrolled");
      isScrolling = true;
    } else if (scrollTop <= threshold && isScrolling) {
      navbar.classList.remove("navbar--scrolled");
      isScrolling = false;
    }

    // Debounce for performance
    scrollTimer = setTimeout(() => {
      const currentScrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      if (
        currentScrollTop > threshold &&
        !navbar.classList.contains("navbar--scrolled")
      ) {
        navbar.classList.add("navbar--scrolled");
        isScrolling = true;
      } else if (
        currentScrollTop <= threshold &&
        navbar.classList.contains("navbar--scrolled")
      ) {
        navbar.classList.remove("navbar--scrolled");
        isScrolling = false;
      }
    }, 10);
  }

  // Initialize when DOM is ready
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initNavbarScrollEffect);
  } else {
    initNavbarScrollEffect();
  }

  // Re-initialize on route changes (for SPA navigation)
  window.addEventListener("popstate", () => {
    setTimeout(initNavbarScrollEffect, 100);
  });

  // Observer for dynamic content loading
  if (typeof MutationObserver !== "undefined") {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === "childList" && !navbar) {
          initNavbarScrollEffect();
        }
      });
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  }
})();
