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

// 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.
var ROOT_MARGIN_VERTICAL = '360px';
var useIntersectionObserver = function useIntersectionObserver(_ref) {
  var onIntersectingCallback = _ref.onIntersecting,
    onIntersectionCallback = _ref.onIntersection;
  var ref = useRef(null);
  var onIntersectingCallbackRef = useRef(onIntersectingCallback);
  var onIntersectionCallbackRef = useRef(onIntersectionCallback);
  useEffect(function () {
    onIntersectingCallbackRef.current = onIntersectingCallback;
    onIntersectionCallbackRef.current = onIntersectionCallback;
  }, [onIntersectingCallback, onIntersectionCallback]);
  var onIntersection = useCallback(function (entries, observer) {
    var _onIntersectionCallba;
    var isIntersecting = entries.some(function (entry) {
      return entry.isIntersecting;
    });
    (_onIntersectionCallba = onIntersectionCallbackRef.current) === null || _onIntersectionCallba === void 0 || _onIntersectionCallba.call(onIntersectionCallbackRef, isIntersecting);
    if (isIntersecting) {
      var _onIntersectingCallba;
      (_onIntersectingCallba = onIntersectingCallbackRef.current) === null || _onIntersectingCallba === void 0 || _onIntersectingCallba.call(onIntersectingCallbackRef);
      observer.disconnect();
    }
  }, []);
  useEffect(function () {
    if (!ref.current) {
      return;
    }
    var intersectionObserver = new IntersectionObserver(onIntersection, {
      rootMargin: "".concat(ROOT_MARGIN_VERTICAL, " 0px ").concat(ROOT_MARGIN_VERTICAL, " 0px")
    });
    intersectionObserver.observe(ref.current);
    return function () {
      return intersectionObserver.disconnect();
    };
  }, [ref, onIntersection]);
  return ref;
};
export default useIntersectionObserver;