export const useOutsideClick = () => {
  const root = typeof document !== 'undefined' ? document.body : null;
  let handleClickOutside = null;
  let handleKeydown = null;

  return {
    bind(element, onOutsideClick) {
      handleClickOutside = (e) => {
        if (element && !element.contains(e.target)) {
          onOutsideClick();
        }
      };
      handleKeydown = (e) => {
        if (e.key === 'Escape') {
          onOutsideClick();
        }
      };
      if (root) {
        root.addEventListener(
          'mousedown',
          handleClickOutside,
        );
        root.addEventListener('keydown', handleKeydown);
      }
    },
    unbind() {
      if (root) {
        root.removeEventListener(
          'mousedown',
          handleClickOutside,
        );
        root.removeEventListener('keydown', handleKeydown);
      }
    }
  };
};
