---
import { Icon } from "../../components/atoms/Icon";
---

<div class="max-h-[calc(100vh-2rem)] overflow-y-auto w-full max-w-80">
  <div
    class="flex items-center gap-3 px-4 lg:px-6 pb-4 lg:pb-6 text-muted-foreground"
  >
    <Icon name="BookOpenText" size={16} />
    <p class="text-sm text-foreground">On this page</p>
  </div>

  <div id="toc" class="px-4 lg:px-6 pb-4 lg:pb-6">
    <p class="text-sm">Loading...</p>
  </div>
</div>

<script is:inline>
  function buildToc() {
    const content = document.getElementById("rendered-content");
    const toc = document.getElementById("toc");

    if (!content || !toc) {
      return;
    }

    const headings = content.querySelectorAll("h2, h3, h4");

    if (headings.length === 0) {
      toc.innerHTML =
        '<p class="text-sm text-muted-foreground">No headings</p>';
      return;
    }

    let html = "";
    headings.forEach((heading) => {
      const text = heading.textContent?.trim() || "";
      const id = heading.id || text.toLowerCase().replace(/[^a-z0-9]+/g, "-");
      if (!heading.id) heading.id = id;

      const level = parseInt(heading.tagName.charAt(1));
      const padding = level === 3 ? "pl-9" : level === 4 ? "pl-16" : "pl-3";

      html += `
        <div class="py-2 ${padding} border-l border-border toc-item" data-id="${id}">
          <a href="#${id}" class="text-sm text-muted-foreground hover:text-foreground break-words block">
            ${text}
          </a>
        </div>
      `;
    });

    toc.innerHTML = html;

    // Add click handlers
    const links = toc.querySelectorAll("a");
    links.forEach((link) => {
      link.addEventListener("click", (e) => {
        e.preventDefault();

        // Remove all active classes and inline styles
        document.querySelectorAll(".toc-item").forEach((item) => {
          item.classList.remove("active");
          item.style.borderLeftColor = "";
          const link = item.querySelector("a");
          if (link) link.style.color = "";
        });

        // Add active to clicked item with inline styles
        const tocItem = link.closest(".toc-item");
        if (tocItem) {
          tocItem.classList.add("active");
          tocItem.style.borderLeftColor = "var(--color-primary)";
          link.style.color = "var(--color-primary)";
        }

        // Scroll to target - fixed selector issue
        const href = link.getAttribute("href");

        if (href) {
          const id = href.substring(1); // Remove the # from href
          const target = document.getElementById(id); // Use getElementById instead

          if (target) {
            target.scrollIntoView({ behavior: "smooth" });
          }
        }
      });
    });

    // Start scroll tracking
    startScrollTracking();
  }

  let _scrollCleanup = null;

  function startScrollTracking() {
    // Remove previous listener to avoid accumulation across navigations
    if (_scrollCleanup) {
      _scrollCleanup();
    }

    let scrollTimeout;
    const handler = () => {
      clearTimeout(scrollTimeout);
      scrollTimeout = setTimeout(updateActiveOnScroll, 100);
    };

    window.addEventListener("scroll", handler);
    _scrollCleanup = () => window.removeEventListener("scroll", handler);
  }

  function updateActiveOnScroll() {
    const headings = document.querySelectorAll("h2, h3, h4");
    const tocItems = document.querySelectorAll(".toc-item");

    if (headings.length === 0 || tocItems.length === 0) return;

    // Remove all active styles
    tocItems.forEach((item) => {
      item.classList.remove("active");
      item.style.borderLeftColor = "";
      const link = item.querySelector("a");
      if (link) link.style.color = "";
    });

    // Find which heading is currently at the top
    let activeId = "";
    const scrollTop = window.scrollY + 100;

    for (let i = headings.length - 1; i >= 0; i--) {
      const heading = headings[i];
      const rect = heading.getBoundingClientRect();

      if (rect.top <= scrollTop) {
        activeId = heading.id;
        break;
      }
    }

    // Set active styles
    if (activeId) {
      const activeItem = document.querySelector(`[data-id="${activeId}"]`);
      if (activeItem) {
        activeItem.classList.add("active");
        activeItem.style.borderLeftColor = "var(--color-primary)";
        const link = activeItem.querySelector("a");
        if (link) link.style.color = "var(--color-primary)";
      }
    }
  }

  // Run on initial load and after every client-side navigation
  document.addEventListener("astro:page-load", buildToc);
</script>

<style>
  .toc-item.active {
    border-left-color: var(--color-primary) !important;
  }
  .toc-item.active a {
    color: var(--color-primary) !important;
  }
</style>
