import { useCallback, useEffect } from 'react';
import { find } from 'lodash';

/**
 * Handle document click
 * @param nodes - if the click is inside a node then document click event will
 * not be raised
 *
 * @param onDocumentClick - if the click is outside of nodes then the callback
 * will be raised. Use useCallback for this to avoid the event listener being
 * reattached unnecessarily
 *
 * @param isEnabled - whether the on click handler is enabled. Can be set
 * to false if the hook needs to be enabled or disabled dynamically
 */
export function useDocumentClick(nodes, onDocumentClick) {
  var isEnabled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var handleDocumentClick = useCallback(function (event) {
    var nonClickableRefs = Array.isArray(nodes) ? nodes : [nodes];
    var nonClickableRef = find(nonClickableRefs, function (node) {
      var _node$current;
      return (_node$current = node.current) === null || _node$current === void 0 ? void 0 : _node$current.contains(event.target);
    });
    if (!nonClickableRef) {
      onDocumentClick(event);
    }
  }, [nodes, onDocumentClick]);
  useEffect(function () {
    if (!isEnabled) {
      return undefined;
    }
    document.addEventListener('mousedown', handleDocumentClick);
    return function () {
      document.removeEventListener('mousedown', handleDocumentClick);
    };
  }, [handleDocumentClick, isEnabled]);
}