"use client";

import * as React from "react";

/** Links to every Section on the page, read from the DOM so it never drifts from the page. */
export function OnThisPage() {
  const ref = React.useRef<HTMLElement>(null);
  const [items, setItems] = React.useState<{ id: string; title: string }[]>([]);

  React.useEffect(() => {
    const root = ref.current?.parentElement;
    if (!root) return;
    const found = [...root.querySelectorAll<HTMLElement>(":scope > section[id]")]
      .map((s) => ({ id: s.id, title: s.querySelector(":scope > div > h2")?.textContent ?? s.id }))
      .filter((s, i, all) => all.findIndex((x) => x.id === s.id) === i);
    // Read once after mount: the sections are static markup rendered with the page.
    setItems(found);
  }, []);

  return (
    <nav ref={ref} aria-label="On this page" className="border-b border-border py-4">
      <p className="mb-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">On this page</p>
      <ul className="flex flex-wrap gap-x-4 gap-y-1.5 text-sm">
        {items.map((s) => (
          <li key={s.id}>
            <a href={`#${s.id}`} className="text-primary underline-offset-4 hover:underline">
              {s.title}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}
