/* global React */

const { useState, useEffect } = React;

// Fires once when the ref enters the viewport, then disconnects.
function useInView(ref, opts = {}) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (seen || !ref.current) return;
    const obs = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setSeen(true);
          obs.disconnect();
        }
      },
      { rootMargin: "0px 0px -10% 0px", threshold: 0.05, ...opts }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [ref, seen]);
  return seen;
}

Object.assign(window, { useInView });
