"use client";

import { useEffect, useState } from "react";

export interface TOCItem {
  id: string;
  label: string;
}

interface BlogTOCProps {
  items: TOCItem[];
}

export function BlogTOC({ items }: BlogTOCProps) {
  const [active, setActive] = useState(items[0]?.id ?? "");

  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActive(e.target.id);
        });
      },
      { rootMargin: "-120px 0px -65% 0px", threshold: 0 }
    );
    items.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, [items]);

  const scrollTo = (id: string) => (e: React.MouseEvent) => {
    e.preventDefault();
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <nav className="b-toc" aria-label="On this page">
      <span className="b-kicker" style={{ fontSize: 11.5 }}>On this page</span>
      <div className="b-toc-links">
        {items.map(({ id, label }) => (
          <a
            key={id}
            href={`#${id}`}
            onClick={scrollTo(id)}
            className={`b-toc-link${active === id ? " active" : ""}`}
          >
            <span className="b-toc-bar" />
            {label}
          </a>
        ))}
      </div>
    </nav>
  );
}
