import { useEffect, useRef } from "react";
function getTargetElement(target, defaultElement) {
  if (!target) {
    return defaultElement;
  }
  let targetElement;
  if (typeof target === "function") {
    targetElement = target();
  } else if ("current" in target) {
    targetElement = target.current;
  } else {
    targetElement = target;
  }
  return targetElement;
}
const defaultEvent = "click";
function useClickAway(target, onClickAway, eventName = defaultEvent, isEmit = true) {
  const onClickAwayRef = useRef(onClickAway);
  onClickAwayRef.current = onClickAway;
  useEffect(() => {
    const handler = (event) => {
      const targets = Array.isArray(target) ? target : [target];
      if (targets.some((targetItem) => {
        const targetElement = getTargetElement(targetItem);
        return !targetElement || (targetElement == null ? void 0 : targetElement.contains(event.target));
      })) {
        return;
      }
      onClickAwayRef.current(event);
    };
    if (isEmit) {
      document.addEventListener(eventName, handler);
    }
    return () => {
      if (isEmit) {
        document.removeEventListener(eventName, handler);
      }
    };
  }, [target, eventName, isEmit]);
}
export {
  useClickAway as default,
  getTargetElement
};
