import { useRef, useEffect } from 'react';

const WINDOW_PROPERTY_LAYER_STACK = "__ANVIL_LAYER_MANAGER__";
const getGlobalLayers = () => {
  if (typeof window === "undefined") {
    return [];
  }
  if (!window[WINDOW_PROPERTY_LAYER_STACK]) {
    window[WINDOW_PROPERTY_LAYER_STACK] = [];
  }
  return window[WINDOW_PROPERTY_LAYER_STACK];
};
const registerLayer = (id) => {
  const layers = getGlobalLayers();
  if (!layers.includes(id)) {
    layers.push(id);
  }
};
const unregisterLayer = (id) => {
  const layers = getGlobalLayers();
  const index = layers.indexOf(id);
  if (index !== -1) {
    layers.splice(index, 1);
  }
};
const isTopLayer = (id) => {
  const layers = getGlobalLayers();
  return layers[layers.length - 1] === id;
};

const useOnClickOutside = ({
  onClickOutsideBegin,
  targets,
  onClickOutside,
  disable,
  layerId
}) => {
  const pressStartedOutsideRef = useRef(false);
  useEffect(() => {
    if (disable || typeof document === "undefined") return;
    const isOutsideTargets = (e) => {
      const path = e.composedPath();
      return !targets.some((el) => el && path.includes(el));
    };
    const handlePointerDown = (e) => {
      const isOutside = isOutsideTargets(e);
      pressStartedOutsideRef.current = isOutside;
      if (isOutside && (!layerId || isTopLayer(layerId))) {
        onClickOutsideBegin?.(e);
      }
    };
    const handlePointerUp = (e) => {
      const startedOutside = pressStartedOutsideRef.current;
      pressStartedOutsideRef.current = false;
      if (startedOutside && isOutsideTargets(e)) {
        if (!layerId || isTopLayer(layerId)) {
          onClickOutside?.(e);
        }
      }
    };
    document.addEventListener("pointerdown", handlePointerDown);
    document.addEventListener("pointerup", handlePointerUp);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown);
      document.removeEventListener("pointerup", handlePointerUp);
    };
  }, [onClickOutside, onClickOutsideBegin, targets, disable, layerId]);
};

export { useOnClickOutside as a, registerLayer as r, unregisterLayer as u };
//# sourceMappingURL=useOnClickOutside-Zw5vzxSq.js.map
