---
// Table of Contents Component - Extracts headings from article content
import { getI18n } from '../lib/i18n';

const { t } = getI18n(Astro);
const hasBeforeNav = Astro.slots.has('before-nav');
---

<aside
  id="toc-container"
  class="hidden w-full shrink-0 lg:block lg:w-72"
  data-has-before-nav={hasBeforeNav ? 'true' : 'false'}
>
  <div class="sticky top-24 space-y-4">
    <slot name="before-nav" />

    <div id="toc-panel" class="terminal-panel-muted space-y-4">
      <div class="space-y-3">
        <span class="terminal-kicker">
          <i class="fas fa-terminal"></i>
          nav stack
        </span>
        <div class="terminal-section-title">
          <span class="terminal-section-icon">
            <i class="fas fa-list-ul"></i>
          </span>
          <div>
            <h3 class="text-base font-semibold text-[var(--title-color)]">{t('toc.title')}</h3>
            <p class="text-xs leading-6 text-[var(--text-secondary)]">
              {t('toc.intro')}
            </p>
          </div>
        </div>
      </div>

      <nav id="toc-nav" class="space-y-2 max-h-[calc(100vh-240px)] overflow-y-auto pr-1 text-sm">
        <!-- TOC items will be generated by JavaScript -->
      </nav>
    </div>
  </div>
</aside>

<script is:inline>
  (function() {
    function generateTOC() {
      const content = document.querySelector('.article-content');
      if (!content) return;

      const headings = content.querySelectorAll('h2, h3');
      const tocNav = document.getElementById('toc-nav');
      const tocPanel = document.getElementById('toc-panel');
      const container = document.getElementById('toc-container');
      const hasBeforeNav = container?.getAttribute('data-has-before-nav') === 'true';

      if (!tocNav || headings.length === 0) {
        if (tocPanel) tocPanel.style.display = 'none';
        if (container && !hasBeforeNav) container.style.display = 'none';
        return;
      }

      tocNav.innerHTML = '';

      headings.forEach((heading, index) => {
        if (!heading.id) {
          heading.id = `heading-${index}`;
        }

        const link = document.createElement('a');
        link.href = `#${heading.id}`;
        link.className = `terminal-nav-link flex w-full items-center justify-between ${
          heading.tagName === 'H3' ? 'pl-8 text-xs' : 'text-sm'
        }`;
        link.innerHTML = `
          <span class="truncate">${heading.textContent || ''}</span>
          <i class="fas fa-angle-right text-[10px] opacity-60"></i>
        `;

        link.addEventListener('click', (e) => {
          e.preventDefault();
          heading.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });

        tocNav.appendChild(link);
      });

      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              const links = tocNav.querySelectorAll('a');
              links.forEach(link => {
                link.classList.remove('is-active');
                if (link.getAttribute('href') === `#${entry.target.id}`) {
                  link.classList.add('is-active');
                }
              });
            }
          });
        },
        { rootMargin: '-20% 0px -75% 0px' }
      );

      headings.forEach(heading => observer.observe(heading));
    }

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', generateTOC);
    } else {
      generateTOC();
    }
  })();
</script>
