import { useCallback, useEffect, useState } from 'react';

export function useInView(options?: IntersectionObserverInit) {
    const [inView, setInView] = useState(false);
    const [node, setNode] = useState<Element | null>(null);

    const ref = useCallback((element: Element | null) => {
        setNode(element);
    }, []);

    useEffect(() => {
        if (!node) return;

        const observer = new IntersectionObserver(([entry]) => {
            setInView(entry.isIntersecting);
        }, options);

        observer.observe(node);

        return () => {
            observer.disconnect();
        };
    }, [node, options]);

    return { ref, inView };
}
