import { useRef, useCallback, useState, useEffect } from 'react';
const useIntersectionObserver = function useIntersectionObserver(opts = {}) {
  const defaultRef = useRef();
  const {
    ref = defaultRef,
    callback,
    root,
    threshold = 0,
    rootMargin = '0px',
    active = true
  } = opts;

  // We keep track of when the ref is reattached with a dummy piece of state
  const [refReattached, setRefReattached] = useState({});

  // Reobserve our node every time React swaps it out for a new one
  useEffect(() => {
    if (!active) return undefined;
    const options = {
      root,
      threshold,
      rootMargin
    };
    const handler = entries => {
      const [entry] = entries;
      callback(entry);
    };
    const observer = new window.IntersectionObserver(handler, options);
    if (ref.current) {
      observer.observe(ref.current);
    }
    return () => {
      observer.disconnect();
    };
  }, [refReattached, callback, threshold, rootMargin, active]);

  // Callback ref to monitor when the DOM node changes
  const refCallback = useCallback(node => {
    ref.current = node;
    setRefReattached(() => ({}));
  }, []);
  return refCallback;
};
export default useIntersectionObserver;