import { useEffect } from 'react';
import Events from '../utils/events';
import { getTargetElement } from '../utils/getTargetElement';
import { useLatest } from '../utils/hooks';
export default function useClickAway(target, onClickAway) {
  var eventName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'click';
  var onClickAwayRef = useLatest(onClickAway);
  var eventNameRef = useLatest(eventName);
  var targetRef = useLatest(target);
  useEffect(function () {
    var handler = function handler(event) {
      var _onClickAwayRef$curre;

      var currentTarget = targetRef.current;
      var targets = Array.isArray(currentTarget) ? currentTarget : [currentTarget];

      if (targets.some(function (targetItem) {
        var targetElement = getTargetElement(targetItem);
        return !targetElement || targetElement.contains && targetElement.contains(event.target);
      })) {
        return;
      }

      (_onClickAwayRef$curre = onClickAwayRef.current) === null || _onClickAwayRef$curre === void 0 ? void 0 : _onClickAwayRef$curre.call(onClickAwayRef, event);
    };

    Events.on(document, eventNameRef.current, handler);
    return function () {
      Events.off(document, eventNameRef.current, handler);
    };
  }, []);
}