import { useEffect, useState } from "react";

export function useIntersectObserver(element, offset, once) {
  const [isInViewport, setIsInViewport] = useState(false);

  useEffect(() => {
    const current = element?.current;
    const observer = new IntersectionObserver(([entry]) => {
      setIsInViewport(entry.isIntersecting);
      if (entry.isIntersecting && once) {
        observer.unobserve(current);
      }
    }, { rootMargin: offset });

    current && observer.observe(current);

    return () => current && observer.unobserve(current);
  }, [element, offset, once]);

  return isInViewport;
}