import { useEffect, useState, type Ref } from "preact/hooks";

export const useIsVisible = (ref: Ref<HTMLElement>, onlyFirst = false) => {
    const [isVisible, setVisible] = useState(false);

    useEffect(() => {
        if (ref.current) {
            const observer = new IntersectionObserver(([entry]) => {
                setVisible(entry.isIntersecting);
                if (entry.isIntersecting && onlyFirst) {
                    observer.disconnect();
                }
            });

            observer.observe(ref.current);

            return () => observer.disconnect();
        }
    }, [ref.current, onlyFirst]);

    return isVisible;
}