import { useCallback, useEffect, useState } from 'react';
import { useLatest } from 'react-use';
import { useRAF } from "../../../../react-utils/hooks/useRAF.js";
import { REFLOW_EVENTS, areElementsIntersecting } from "../../../../utils/dom.js";
export function useObserveIntersection({ floatingRef, container, selector, observerOptions, }) {
    const [intersection, setIntersection] = useState(false);
    const intersectionRef = useLatest(intersection);
    const updateFunction = useCallback(() => {
        const floating = floatingRef.current;
        const element = container.querySelector(selector);
        if (!element || !floating) {
            if (intersectionRef.current)
                setIntersection(false);
            return;
        }
        const isIntersecting = areElementsIntersecting(element, floating);
        if (isIntersecting !== intersectionRef.current)
            setIntersection(isIntersecting);
    }, [container, floatingRef, intersectionRef, selector]);
    const observer = useRAF(updateFunction);
    useEffect(() => {
        observer();
        const containerObserver = new MutationObserver(observer);
        containerObserver.observe(container, observerOptions ?? {
            childList: true,
            subtree: true,
            attributes: true,
        });
        for (const event of REFLOW_EVENTS) {
            window.addEventListener(event, observer);
        }
        return () => {
            containerObserver.disconnect();
            for (const event of REFLOW_EVENTS) {
                window.removeEventListener(event, observer);
            }
        };
    }, [container, observer, observerOptions]);
    return { intersection };
}
//# sourceMappingURL=useObserveIntersection.js.map
