---
export interface Props {
  class?: string;
  gap?: string;
}

const { class: className = '', gap = '2rem' } = Astro.props;
---

<div
  class={`scroll-sidebar-root flex flex-row ${className}`}
  data-scroll-sidebar
  style={`gap: ${gap};`}
>
  <slot />
</div>

<style>
  .scroll-sidebar-root {
    position: relative;
  }
</style>

<script>
  function initScrollSidebar() {
    const containers = document.querySelectorAll("[data-scroll-sidebar]");

    containers.forEach((container) => {
      if (!(container instanceof HTMLElement)) return;

      const navItems = container.querySelectorAll(
        "[data-scroll-sidebar-nav-item]",
      );
      const sections = container.querySelectorAll(
        "[data-scroll-sidebar-section]",
      );

      // Function to update active state
      const updateActiveState = (activeId: string) => {
        navItems.forEach((item) => {
          const itemId = item.getAttribute("data-scroll-sidebar-nav-item");
          if (itemId === activeId) {
            item.setAttribute("data-state", "active");
          } else {
            item.setAttribute("data-state", "inactive");
          }
        });
      };

      // Click handler for manual navigation
      navItems.forEach((item) => {
        item.addEventListener("click", () => {
          const itemId = item.getAttribute("data-scroll-sidebar-nav-item");
          if (!itemId) return;

          // Find corresponding section and scroll to it
          const targetSection = container.querySelector(
            `[data-scroll-sidebar-section="${itemId}"]`,
          );
          if (targetSection) {
            targetSection.scrollIntoView({
              behavior: "smooth",
              block: "center",
            });
          }
        });
      });

      // Intersection Observer for scroll-based activation
      const observerOptions = {
        root: null,
        rootMargin: "-40% 0px -40% 0px", // Activate when section is in middle 20% of viewport
        threshold: 0,
      };

      const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const sectionElement = entry.target;
            const sectionId = sectionElement.getAttribute(
              "data-scroll-sidebar-section",
            );
            if (sectionId) {
              updateActiveState(sectionId);
            }
          }
        });
      }, observerOptions);

      // Observe all sections
      sections.forEach((section) => {
        observer.observe(section);
      });
    });
  }

  // Initialize on load
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initScrollSidebar);
  } else {
    initScrollSidebar();
  }

  // Re-initialize after navigation (for view transitions)
  document.addEventListener("astro:after-swap", initScrollSidebar);
</script>
