import { useEffect, useState } from 'react';

export function useDocsScrollSpy(sectionIds: string[]): string {
    const [activeId, setActiveId] = useState(sectionIds[0] ?? '');

    useEffect(() => {
        if (sectionIds.length === 0) {
            return;
        }

        const sectionElements = sectionIds
            .map((id) => document.getElementById(id))
            .filter((element): element is HTMLElement => element !== null);

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

        const updateActiveSection = (): void => {
            const offset = 120;
            let currentId = sectionIds[0];

            for (const element of sectionElements) {
                const top = element.getBoundingClientRect().top;

                if (top <= offset) {
                    currentId = element.id;
                } else {
                    break;
                }
            }

            setActiveId(currentId);
        };

        updateActiveSection();

        window.addEventListener('scroll', updateActiveSection, { passive: true });

        return () => {
            window.removeEventListener('scroll', updateActiveSection);
        };
    }, [sectionIds]);

    return activeId;
}
