import { useEffect } from 'react';
import { inBrowser } from '../utils'; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types

export default function useVisibilityChange(target, onChange) {
  useEffect(function () {
    // compatibility: https://caniuse.com/#feat=intersectionobserver
    if (!inBrowser || !window.IntersectionObserver) {
      return null;
    }

    var observer = new IntersectionObserver(function (entries) {
      // visibility changed
      onChange(entries[0].intersectionRatio > 0);
    }, {
      root: document.body
    });

    var observe = function observe() {
      if (target.current) {
        observer.observe(target.current);
      }
    };

    var unobserve = function unobserve() {
      if (target.current) {
        observer.unobserve(target.current);
      }
    };

    observe();
    return unobserve;
  }, [target.current]);
}