import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';

/**
 * Jump links for a long detail page, highlighting the section currently on
 * screen. Sections are identified by the `id` given to each SectionCard.
 */
export function SectionNav({
    sections,
    className,
}: {
    sections: Array<{ id: string; label: string }>;
    className?: string;
}) {
    const [active, setActive] = useState<string>(sections[0]?.id ?? '');

    useEffect(() => {
        const elements = sections
            .map((section) => document.getElementById(section.id))
            .filter((element): element is HTMLElement => element !== null);

        if (elements.length === 0) {
            return;
        }

        const observer = new IntersectionObserver(
            (entries) => {
                const visible = entries
                    .filter((entry) => entry.isIntersecting)
                    .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);

                if (visible.length > 0) {
                    setActive(visible[0].target.id);
                }
            },
            { rootMargin: '-88px 0px -65% 0px', threshold: 0 },
        );

        elements.forEach((element) => observer.observe(element));

        return () => observer.disconnect();
    }, [sections]);

    if (sections.length === 0) {
        return null;
    }

    return (
        <nav
            aria-label="On this page"
            className={cn('crm-scroll -mx-1 flex gap-1 overflow-x-auto px-1', className)}
        >
            {sections.map((section) => {
                const isActive = section.id === active;

                return (
                    <a
                        key={section.id}
                        href={`#${section.id}`}
                        className={cn(
                            'shrink-0 rounded-md px-2.5 py-1 text-xs font-medium whitespace-nowrap transition-colors',
                            isActive
                                ? 'bg-accent text-accent-foreground'
                                : 'text-muted-foreground hover:text-foreground',
                        )}
                    >
                        {section.label}
                    </a>
                );
            })}
        </nav>
    );
}
