import { useEffect, useRef, useState } from "react";
import { debounce as debounceFunc, DEFAULT_EVENTS, throttle as throttleFunc } from ".";
let passiveEventSupported = false;
try {
  const opts = Object.defineProperty({}, "passive", {
    get() {
      passiveEventSupported = true;
    }
  });
  window.addEventListener("test", null, opts);
} catch (e) {
}
const passiveEvent = passiveEventSupported ? { capture: false, passive: true } : false;
const useEventVisible = (eventOptions) => {
  const {
    listenEvents = DEFAULT_EVENTS,
    offset,
    scrollContainer,
    debounce,
    throttle
  } = eventOptions;
  const [visible, setVisible] = useState(false);
  const containerRef = useRef(null);
  useEffect(() => {
    let checkVisible = () => {
      var _a;
      if (!containerRef.current)
        return;
      const { top, left, width, height } = (_a = containerRef.current) == null ? void 0 : _a.getBoundingClientRect();
      const {
        top: parentTop,
        left: parentLeft,
        width: parentWidth,
        height: parentHeight
      } = scrollContainer.getBoundingClientRect();
      const windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
      const windowInnerWidth = window.innerWidth || document.documentElement.clientWidth;
      const intersectionTop = Math.min(parentTop, 0);
      const intersectionLeft = Math.min(parentLeft, 0);
      const intersectionHeight = Math.min(windowInnerHeight, parentTop + parentHeight) - intersectionTop;
      const intersectionWidth = Math.min(windowInnerWidth, parentLeft + parentWidth) - intersectionLeft;
      const offsetTop = top - intersectionTop;
      const offsetLeft = left - intersectionLeft;
      const offsets = Array.isArray(offset) ? offset : [offset, offset];
      const isVisible = offsetTop - offsets[0] <= intersectionHeight && offsetTop + height + offsets[0] >= 0 && offsetLeft - offsets[1] <= intersectionWidth && offsetLeft + width + offsets[1] >= 0;
      setVisible(isVisible);
      if (isVisible) {
        listenEvents.forEach((event) => {
          scrollContainer == null ? void 0 : scrollContainer.removeEventListener(event, checkVisible);
        });
      }
    };
    if (debounce) {
      checkVisible = debounceFunc(checkVisible, debounce);
    } else if (throttle) {
      checkVisible = throttleFunc(checkVisible, throttle);
    }
    listenEvents.forEach((event) => {
      scrollContainer == null ? void 0 : scrollContainer.addEventListener(event, checkVisible, passiveEvent);
    });
    checkVisible();
    return () => {
      listenEvents.forEach((event) => {
        scrollContainer == null ? void 0 : scrollContainer.removeEventListener(event, checkVisible, passiveEvent);
      });
    };
  }, [scrollContainer]);
  return [containerRef, visible];
};
var stdin_default = useEventVisible;
export {
  stdin_default as default
};
