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

export function useIntersectionObserver(
  callback: () => void,
  threshold: number = 0.9,
) {
  const elementRef = useRef<HTMLElement | null>(null);
  const [intersectionObserver] = useState(() => {
    // in jsdom, IntersectionObserver is not implemeted
    if (typeof IntersectionObserver === 'undefined') {
      return null;
    }

    return new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          callback();
          intersectionObserver?.disconnect();
        }
      },
      {
        threshold,
      },
    );
  });

  useEffect(() => {
    const element = elementRef.current;

    if (!element || !intersectionObserver) {
      return;
    }

    intersectionObserver.observe(element);

    return () => {
      intersectionObserver.disconnect();
    };
  }, []);

  return {
    elementRef,
  };
}
