import { useCallback, useEffect, useRef } from 'react';
import { isIntersectionObserverSupported } from '../../../utils';

// This property enables the intersection observer to be run once the
// HTML element being observed is within `X` px of the target container it is
// being compared to. Since the default container is the `document`, we set this
// up to check once a Smart Link is within `X` px from the bottom of the viewport.
const ROOT_MARGIN_VERTICAL = '360px';
const useIntersectionObserver = ({
  onIntersecting: onIntersectingCallback,
  onIntersection: onIntersectionCallback
}) => {
  const ref = useRef(null);
  const onIntersectingCallbackRef = useRef(onIntersectingCallback);
  const onIntersectionCallbackRef = useRef(onIntersectionCallback);
  useEffect(() => {
    onIntersectingCallbackRef.current = onIntersectingCallback;
    onIntersectionCallbackRef.current = onIntersectionCallback;
  }, [onIntersectingCallback, onIntersectionCallback]);
  const onIntersection = useCallback((entries, observer) => {
    var _onIntersectionCallba;
    const isIntersecting = entries.some(entry => entry.isIntersecting);
    (_onIntersectionCallba = onIntersectionCallbackRef.current) === null || _onIntersectionCallba === void 0 ? void 0 : _onIntersectionCallba.call(onIntersectionCallbackRef, isIntersecting);
    if (isIntersecting) {
      var _onIntersectingCallba;
      (_onIntersectingCallba = onIntersectingCallbackRef.current) === null || _onIntersectingCallba === void 0 ? void 0 : _onIntersectingCallba.call(onIntersectingCallbackRef);
      observer.disconnect();
    }
  }, []);
  useEffect(() => {
    if (!isIntersectionObserverSupported() || !ref.current) {
      return;
    }
    const intersectionObserver = new IntersectionObserver(onIntersection, {
      rootMargin: `${ROOT_MARGIN_VERTICAL} 0px ${ROOT_MARGIN_VERTICAL} 0px`
    });
    intersectionObserver.observe(ref.current);
    return () => intersectionObserver.disconnect();
  }, [ref, onIntersection]);
  return ref;
};
export default useIntersectionObserver;