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

const DEFAULT_IS_VISIBLE = false;
const DEFAULT_OFFSET = "0px";

const useOnScreen = (offset = DEFAULT_OFFSET) => {
  const ref = useRef(null);
  const [isOnScreen, setIsOnScreen] = useState(DEFAULT_IS_VISIBLE);
  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setIsOnScreen(entry.isIntersecting);
      }
    }, {
      offset
    });

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (ref.current) {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        observer.unobserve(ref.current);
      }
    }; // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return [isOnScreen, ref];
};

export { useOnScreen as default };
