import { useEffect, useState } from 'react';
import { inBrowser } from '../utils';
import { getTargetElement } from '../utils/dom/getTargetElement';

function isInViewPort(el) {
  if (!el) {
    return undefined;
  }

  var viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  var rect = el.getBoundingClientRect();

  if (rect) {
    var top = rect.top,
        bottom = rect.bottom,
        left = rect.left,
        right = rect.right;
    return bottom > 0 && top <= viewPortHeight && left <= viewPortWidth && right > 0;
  }

  return false;
}

function useInViewport(target) {
  var _useState = useState(function () {
    if (!inBrowser || !window.IntersectionObserver) return true;
    var el = getTargetElement(target);
    return isInViewPort(el);
  }),
      inViewPort = _useState[0],
      setInViewport = _useState[1];

  useEffect(function () {
    var el = getTargetElement(target); // compatibility: https://caniuse.com/#feat=intersectionobserver

    if (!el || !inBrowser || !window.IntersectionObserver) {
      return function () {};
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.some(function (entry) {
        if (entry.intersectionRatio > 0) {
          setInViewport(true);
          observer.disconnect();
          return true;
        }

        return false;
      });
    }, {
      threshold: [0.0001]
    });
    observer.observe(el);
    return function () {
      observer.disconnect();
    };
  }, [target]);
  return inViewPort;
}

export default useInViewport;