"use client";

import { useEffect, useState } from "react";

import styles from "../blog.module.css";

export type TocItem = { id: string; text: string; level: 2 | 3 };

/** Sticky table of contents with scrollspy + smooth jump (design `.toc`). */
export function Toc({ items, label }: { items: TocItem[]; label: string }) {
  const [active, setActive] = useState<string>(items[0]?.id ?? "");

  useEffect(() => {
    const targets = items
      .map((i) => document.getElementById(i.id))
      .filter((el): el is HTMLElement => Boolean(el));
    if (targets.length === 0) return;

    const spy = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) setActive(e.target.id);
        }
      },
      { rootMargin: "-80px 0px -70% 0px", threshold: 0 },
    );
    targets.forEach((t) => spy.observe(t));
    return () => spy.disconnect();
  }, [items]);

  if (items.length === 0) return null;

  return (
    <div className={styles.tocBox}>
      <div className={styles.tocH}>{label}</div>
      <ul className={styles.toc}>
        {items.map((i) => (
          <li key={i.id}>
            <a
              href={`#${i.id}`}
              className={`${i.level === 3 ? styles.tocSub : ""} ${
                active === i.id ? styles.tocActive : ""
              }`}
            >
              {i.text}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}
