import React from 'react';
/**
 * Manages the accessibility behavior for avatar popovers, ensuring they are keyboard navigable
 *
 * @see https://procoretech.atlassian.net/browse/UXI-1632?focusedCommentId=6513946
 */
export var useAvatarPopover = function useAvatarPopover(props) {
  var focusableSelector = props.focusableSelector,
    overlayWrapperSelector = props.overlayWrapperSelector;
  var triggerRef = React.useRef(null);
  var openedByKeyboardRef = React.useRef(false);
  var popoverContentRef = React.useCallback(function (node) {
    if (node && openedByKeyboardRef.current) {
      var firstFocusable = node.querySelector(focusableSelector);
      firstFocusable === null || firstFocusable === void 0 ? void 0 : firstFocusable.focus();
    }
  }, [focusableSelector]);
  var beforeShow = React.useCallback(function (event) {
    // Block auto-open on keyboard focus alone - require Enter/Space
    if (event.type === 'focusin') {
      return false;
    }
    openedByKeyboardRef.current = event instanceof KeyboardEvent;
    return true;
  }, []);
  var beforeHide = React.useCallback(function (event) {
    if (event.type === 'focusout') {
      var relatedTarget = event.relatedTarget;
      // Keep open when focus moves into the overlay (e.g. auto-focus after keyboard open)
      if (relatedTarget !== null && relatedTarget !== void 0 && relatedTarget.closest(overlayWrapperSelector)) {
        return false;
      }
      // For hover-opened popovers, don't close on focus changes
      if (!openedByKeyboardRef.current) {
        return false;
      }
    }
    return true;
  }, [overlayWrapperSelector]);
  var afterHide = React.useCallback(function () {
    if (openedByKeyboardRef.current) {
      requestAnimationFrame(function () {
        var _triggerRef$current;
        return (_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 ? void 0 : _triggerRef$current.focus();
      });
    }
    openedByKeyboardRef.current = false;
  }, []);
  return {
    triggerRef: triggerRef,
    popoverContentRef: popoverContentRef,
    beforeShow: beforeShow,
    beforeHide: beforeHide,
    afterHide: afterHide
  };
};
//# sourceMappingURL=useAvatarPopover.js.map