"use client";

import { useEffect, useState } from "react";
import type { LegalSection } from "@/lib/content";

/** Side navigation that highlights the section currently in view. */
export function LegalContents({ sections }: { sections: readonly LegalSection[] }) {
  const [activeId, setActiveId] = useState(sections[0]?.id ?? "");

  useEffect(() => {
    const targets = sections
      .map((s) => document.getElementById(s.id))
      .filter((el): el is HTMLElement => el !== null);
    if (!targets.length) return;

    const io = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
        if (visible) setActiveId(visible.target.id);
      },
      { rootMargin: "-20% 0px -65% 0px", threshold: 0 },
    );

    targets.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [sections]);

  return (
    <nav className="legal-contents" aria-label="Contents">
      <span className="text-xs fw-600 text-uppercase color-golden">Contents</span>
      <ul className="legal-contents-list list-style-none pt-2 mb-0">
        {sections.map((s, i) => (
          <li key={s.id}>
            <a
              href={`#${s.id}`}
              className={activeId === s.id ? "active" : undefined}
              aria-current={activeId === s.id ? "true" : undefined}
            >
              <span className="faq-n mt-1">
                {String(i + 1).padStart(2, "0")}
              </span>
              <span className="legal-contents-text text-sm fw-400">
                {s.heading}
              </span>
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}
