import { useEffect, useRef, useState } from 'react';
import { useSectionSpy } from '@/site/hooks/use-section-spy';
import { subscribeScroll } from '@/site/lib/scroll-engine';

type Section = { id: string; label: string };

type SectionNavProps = {
    sections: Section[];
    /** Name of the navigation ("On this page"). */
    label: string;
    className?: string;
};

/**
 * "On this page": links to the sections of a long page. They stand where
 * they are placed and — once that place has scrolled away — follow the
 * reader as a slim bar under the header, the section being read marked in
 * it (`.section-nav` in site.css). The bar leaves when the last section
 * ends.
 *
 * The links in place are the real navigation; the bar repeats them as a
 * pointer shortcut and is hidden from assistive technology and the
 * keyboard. Positions are measured when the page changes size, never
 * while scrolling.
 */
export function SectionNav({ sections, label, className }: SectionNavProps) {
    const nav = useRef<HTMLElement>(null);
    const bar = useRef<HTMLDivElement>(null);
    const [shown, setShown] = useState(false);
    const active = useSectionSpy(sections.map((section) => section.id));
    const lastId = sections.at(-1)?.id;

    // The bar is out between the links in place and the end of the last section.
    useEffect(() => {
        const place = nav.current;

        if (!place) {
            return;
        }

        let from = 0;
        let until = 0;

        const measure = () => {
            const scroll = window.scrollY;
            const last = lastId ? document.getElementById(lastId) : null;
            const end = last?.closest('section') ?? last;

            from = place.getBoundingClientRect().bottom + scroll;
            until = end
                ? end.getBoundingClientRect().bottom + scroll
                : Infinity;
        };

        const observer = new ResizeObserver(measure);

        observer.observe(document.body);
        measure();

        const stop = subscribeScroll((y) => {
            setShown(y > from && y + window.innerHeight * 0.5 < until);
        });

        return () => {
            observer.disconnect();
            stop();
        };
    }, [lastId]);

    // Keep the marked link in sight when the bar scrolls sideways (phones).
    useEffect(() => {
        if (!shown) {
            return;
        }

        const link = bar.current?.querySelector<HTMLElement>('[data-active]');
        const track = link?.closest('ul');

        if (link && track) {
            track.scrollTo({
                left:
                    link.offsetLeft -
                    (track.clientWidth - link.offsetWidth) / 2,
                behavior: 'smooth',
            });
        }
    }, [active, shown]);

    return (
        <>
            <nav ref={nav} aria-label={label} className={className}>
                <ul className="flex flex-wrap gap-2.5">
                    {sections.map((section) => (
                        <li key={section.id}>
                            <a
                                href={`#${section.id}`}
                                className="border-line text-soft inline-flex h-9 items-center rounded-full border px-4 text-sm transition-colors duration-300 hover:border-accent hover:text-accent"
                            >
                                {section.label}
                            </a>
                        </li>
                    ))}
                </ul>
            </nav>

            <div
                ref={bar}
                aria-hidden="true"
                data-shown={shown ? '' : undefined}
                className="section-nav stage-light"
            >
                <ul className="section-nav-track shell">
                    {sections.map((section, index) => (
                        <li key={section.id}>
                            <a
                                href={`#${section.id}`}
                                tabIndex={-1}
                                data-active={index === active ? '' : undefined}
                                className="section-nav-link"
                            >
                                {section.label}
                            </a>
                        </li>
                    ))}
                </ul>
            </div>
        </>
    );
}
