import { jsx, jsxs } from 'react/jsx-runtime';
import { createContext, useContext, useRef, useLayoutEffect, useEffect, forwardRef, useId, useState, useCallback, useImperativeHandle, useMemo } from 'react';
import { B as Button } from './Button-BNzCI47m.js';
import { t as tabbable, a as usePopoverTransitionStates } from './usePopoverTransitionStates-CDXCdyKa.js';
import { c as childrenToString } from './childrenToString-Bz9MqbHb.js';
import { useTrackingId } from './useTrackingId.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { c as cx } from './index-De1g9FRV.js';
import { p as portalScopeClassNames } from './portalScopeClassNames-BTyv0FY8.js';
import { u as useFocusWithin } from './useFocusWithin-hi77jsrB.js';
import { D as DialogContext } from './DialogContext-DBgtApl9.js';
import { c as computePosition, b as autoUpdate, d as safeShowPopover, e as safeHidePopover, o as offset, a as size, f as flip, s as shift, g as arrow$1, l as limitShift } from './floating-ui.react-dom-CyrxPiI-.js';
import { u as useOptionallyControlledState } from './useOptionallyControlledState-DbDuos5L.js';
import { a as useOnClickOutside } from './useOnClickOutside-Zw5vzxSq.js';

import './Popover.css';const PopoverContext = createContext(null);

function usePopoverContext() {
  const context = useContext(PopoverContext);
  const invokerRef = useRef(null);
  const popoverRef = useRef(null);
  const arrowRef = useRef(null);
  const { triggerHovered, setTriggerHovered, contentHovered } = context || {};
  useLayoutEffect(() => {
    if (!invokerRef.current) return;
    context?.setInvoker?.(invokerRef.current);
  }, [context, invokerRef]);
  useLayoutEffect(() => {
    if (!popoverRef.current) return;
    context?.setPopover?.(popoverRef.current);
    context?.setRootNode?.(popoverRef.current.getRootNode());
    if (!arrowRef.current) return;
    context?.setArrowElement?.(arrowRef.current);
  }, [context, popoverRef]);
  useEffect(() => {
    if (!context?.openOnHover) return;
    if (!triggerHovered && !contentHovered) {
      const closeTimeout = setTimeout(() => {
        context?.closePopover();
      }, 100);
      return () => {
        clearTimeout(closeTimeout);
      };
    }
    if (triggerHovered && !contentHovered) {
      if (context?.delay) {
        const openTimeout = setTimeout(() => {
          context?.openPopover();
        }, context.delay);
        return () => {
          clearTimeout(openTimeout);
        };
      } else {
        context?.openPopover();
      }
    }
  }, [context?.delay, context?.openOnHover, triggerHovered, contentHovered]);
  const onMouseEnterHandler = () => {
    if (!context?.openOnHover) return;
    setTriggerHovered?.(true);
  };
  const onMouseLeaveHandler = () => {
    if (!context?.openOnHover) return;
    setTriggerHovered?.(false);
  };
  const onFocusHandler = (_e) => {
    if (context?.openOnHover) {
      context?.openPopover();
    }
  };
  const onBlurHandler = (e) => {
    if (context?.popover?.contains(e.relatedTarget)) return;
    if (context?.modal && context.openState) {
      e.preventDefault();
      requestAnimationFrame(() => {
        context?.invoker?.focus();
        const focusables = tabbable(context?.popover);
        if (focusables.length > 0) {
          focusables[focusables.length - 1].focus();
        }
      });
      return;
    }
    if (!context?.disableCloseOnClickOutside) {
      context?.closePopover();
    }
  };
  const onKeyDownHandler = (e) => {
    if (!context?.openState) return;
    if (e.code === "Escape" && !context?.disableCloseOnEscape && !context?.controlled) {
      context?.closePopover();
      if (!context?.openOnHover) {
        const invoker = context?.invoker;
        requestAnimationFrame(() => {
          invoker?.blur();
          invoker?.focus({ focusVisible: true });
        });
      }
      return;
    }
  };
  const onClickHandler = () => {
    context?.invoker?.focus();
    if (context?.openOnHover) return;
    if (context?.controlled === false) {
      if (context?.openState) {
        context?.closePopover();
      } else {
        context?.openPopover();
      }
      return;
    }
  };
  if (!context || !invokerRef || !popoverRef) return;
  return {
    invoker: {
      ref: invokerRef,
      element: context.invoker,
      onMouseEnter: onMouseEnterHandler,
      onMouseLeave: onMouseLeaveHandler,
      onKeyDown: onKeyDownHandler,
      onClick: onClickHandler,
      onFocus: onFocusHandler,
      onBlur: onBlurHandler,
      "aria-haspopup": true,
      "aria-expanded": context.openState,
      "aria-details": context.popoverId,
      "data-state": context.openState ? "open" : "closed"
    },
    popover: {
      ref: popoverRef,
      element: context.popover,
      id: context.popoverId,
      onClose: context.onClose,
      show: context.openPopover,
      close: context.closePopover,
      noPadding: context.noPadding,
      style: context.popoverStyle,
      arrowRef
    },
    rootNode: context.rootNode,
    onClose: context.onClose,
    open: context.openState,
    openOnHover: context.openOnHover,
    controlled: context.controlled,
    disableCloseOnClickOutside: context.disableCloseOnClickOutside,
    disableCloseOnEscape: context.disableCloseOnEscape,
    modal: context.modal,
    placement: context.placement,
    actualPlacement: context.actualPlacement,
    disableCaret: context.disableCaret,
    noPadding: context.noPadding,
    fillAvailableHeight: context.fillAvailableHeight,
    maxHeight: context.maxHeight,
    matchReferenceWidth: context.matchReferenceWidth,
    fixedWidth: context.fixedWidth,
    disableFlipFallback: context.disableFlipFallback,
    disableTriggerFocus: context.disableTriggerFocus,
    triggerHovered: context.triggerHovered,
    setTriggerHovered: context.setTriggerHovered,
    contentHovered: context.contentHovered,
    setContentHovered: context.setContentHovered
  };
}

const PopoverClose = forwardRef(
  function PopoverClose2(props, ref) {
    const { onClick, ...rest } = props;
    const context = usePopoverContext();
    const data = {
      children: childrenToString(props.children)
    };
    const trackingId = useTrackingId({
      name: "PopoverClose",
      data,
      hasOverride: !!props["data-tracking-id"]
    });
    return /* @__PURE__ */ jsx(
      Button,
      {
        ref,
        "data-tracking-id": trackingId,
        "data-anv": "popover-close",
        ...rest,
        onClick: (event) => {
          context?.popover.close();
          context?.onClose?.();
          onClick?.(event);
        }
      }
    );
  }
);
PopoverClose.displayName = "PopoverClose";

const PopoverButton = forwardRef(
  function PopoverButton2(props, ref) {
    const {
      children,
      size,
      onMouseEnter,
      onMouseLeave,
      onClick,
      onKeyDown,
      onFocus,
      onBlur,
      ...rest
    } = props;
    const context = usePopoverContext();
    const data = {
      children: childrenToString(props.children),
      appearance: props.appearance,
      icon: props.icon,
      size: props.size,
      type: props.type
    };
    const trackingId = useTrackingId({
      name: "PopoverButton",
      data,
      hasOverride: !!props["data-tracking-id"]
    });
    const onMouseEnterHandler = (e) => {
      onMouseEnter?.(e);
      context?.invoker.onMouseEnter();
    };
    const onMouseLeaveHandler = (e) => {
      onMouseLeave?.(e);
      context?.invoker.onMouseLeave();
    };
    const onFocusHandler = (e) => {
      onFocus?.(e);
      context?.invoker.onFocus(e);
    };
    const onBlurHandler = (e) => {
      onBlur?.(e);
      context?.invoker.onBlur(e);
    };
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      context?.invoker.onKeyDown(e);
    };
    const onClickHandler = (e) => {
      onClick?.(e);
      context?.invoker.onClick();
    };
    const buttonRef = useMergeRefs([context?.invoker.ref, ref]);
    return /* @__PURE__ */ jsx(
      Button,
      {
        ref: buttonRef,
        size,
        onClick: onClickHandler,
        onKeyDown: onKeyDownHandler,
        onMouseEnter: onMouseEnterHandler,
        onMouseLeave: onMouseLeaveHandler,
        onFocus: onFocusHandler,
        onBlur: onBlurHandler,
        "data-anv": "popover-button",
        "data-tracking-id": trackingId,
        "aria-haspopup": context?.invoker["aria-haspopup"],
        "aria-expanded": context?.invoker["aria-expanded"],
        "aria-details": context?.invoker["aria-details"],
        "data-state": context?.invoker["data-state"],
        ...rest,
        children
      }
    );
  }
);
PopoverButton.displayName = "PopoverButton";

const content = "_content_1k6kw_1";
const scroller = "_scroller_1k6kw_78";
const arrow = "_arrow_1k6kw_94";
const styles = {
	content: content,
	scroller: scroller,
	"no-padding": "_no-padding_1k6kw_88",
	arrow: arrow
};

const PopoverContent = forwardRef(
  function PopoverContent2(props, ref) {
    const {
      children,
      className,
      style,
      onMouseEnter,
      onMouseLeave,
      onKeyDown,
      onFocus,
      onBlur,
      onScroll,
      onScrollCapture,
      scrollerRef,
      hideWhileClosed = false,
      ...rest
    } = props;
    const context = usePopoverContext();
    const popoverClassNames = cx(
      className,
      styles["content"],
      portalScopeClassNames,
      {
        [styles["no-padding"]]: context?.noPadding
      }
    );
    const childrenRef = useRef(null);
    const combinedStyles = {
      ...style,
      ...context?.popover.style
    };
    const { props: wrapperProps } = useFocusWithin({
      otherRelatedElements: context?.invoker.element ? [context?.invoker.element] : [],
      onBlur: (e) => {
        if (context?.modal) {
          e.preventDefault();
          requestAnimationFrame(() => {
            context?.invoker.element?.focus();
          });
          return;
        }
        onBlur?.(e);
        context?.popover.close();
      },
      onFocus: (e) => {
        onFocus?.(e);
        context?.popover.show();
      }
    });
    const onMouseEnterHandler = (e) => {
      onMouseEnter?.(e);
      if (!context?.openOnHover) return;
      if (!context?.open) return;
      context.setContentHovered(true);
    };
    const onMouseLeaveHandler = (e) => {
      onMouseLeave?.(e);
      if (!context?.openOnHover) return;
      context.setContentHovered(false);
    };
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      if (e.code === "Escape" && !context?.disableCloseOnEscape) {
        context?.popover.close();
        if (!context?.openOnHover) {
          const invoker = context?.invoker.element;
          requestAnimationFrame(() => {
            invoker?.focus({ focusVisible: true });
          });
        }
      }
    };
    const popoverContentRef = useMergeRefs([context?.popover.ref, ref]);
    const popoverScrollerRef = useMergeRefs([childrenRef, scrollerRef]);
    useLayoutEffect(() => {
      if (context?.open && childrenRef.current) {
        childrenRef.current.scrollTop = 0;
        childrenRef.current.scrollLeft = 0;
      }
    }, [context?.open]);
    const bridgeSide = context?.openOnHover && context?.actualPlacement ? context.actualPlacement.split("-")[0] : void 0;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        popover: "manual",
        id: context?.popover.id,
        "data-anv": "popover-content",
        "data-position": bridgeSide,
        className: popoverClassNames,
        ref: popoverContentRef,
        style: combinedStyles,
        onMouseEnter: onMouseEnterHandler,
        onMouseLeave: onMouseLeaveHandler,
        role: "region",
        ...rest,
        onFocus: wrapperProps.onFocus,
        onBlur: wrapperProps.onBlur,
        children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: styles.scroller,
              role: "presentation",
              tabIndex: -1,
              ref: popoverScrollerRef,
              onKeyDown: onKeyDownHandler,
              onScroll,
              onScrollCapture,
              children: hideWhileClosed ? context?.open ? children : null : children
            }
          ),
          !context?.disableCaret && /* @__PURE__ */ jsx("span", { className: styles["arrow"], ref: context?.popover.arrowRef, children: /* @__PURE__ */ jsxs("svg", { "aria-hidden": "true", width: "14", height: "14", viewBox: "0 0 14 14", children: [
            /* @__PURE__ */ jsx("path", { stroke: "none", d: "M0,0 H14 L7,7 Q7,7 7,7 Z" }),
            /* @__PURE__ */ jsx("clipPath", { id: ":r9:", children: /* @__PURE__ */ jsx("rect", { x: "0", y: "0", width: "14", height: "14" }) })
          ] }) })
        ]
      }
    );
  }
);
PopoverContent.displayName = "PopoverContent";

function PopoverTrigger(props) {
  const { children } = props;
  const context = usePopoverContext();
  if (!context) return;
  const { element, ...rest } = context.invoker;
  return children(rest);
}
PopoverTrigger.displayName = "PopoverTrigger";

const Popover = Object.assign(
  forwardRef(function PopoverInner(props, ref) {
    const {
      children,
      openOnHover = false,
      delay = 100,
      placement = "bottom",
      minHeight = "2.875rem",
      open,
      defaultOpen = false,
      disableShift,
      disableFlip,
      disableFlipFallback,
      matchReferenceWidth,
      id,
      disableCaret,
      fixedWidth,
      fillAvailableHeight,
      maxHeight,
      disableCloseOnClickOutside,
      disableCloseOnEscape,
      fitScreen,
      disableTriggerFocus,
      modal,
      noPadding,
      onClickOutside,
      onClose,
      onOpenAnimationStart,
      onOpenAnimationComplete,
      onCloseAnimationStart,
      onCloseAnimationComplete
    } = props;
    const uid = useId();
    const [invoker, setInvoker] = useState(void 0);
    const [popover, setPopover] = useState(void 0);
    const [rootNode, setRootNode] = useState();
    const [arrowElement, setArrowElement] = useState(void 0);
    const [openState, setOpenState] = useOptionallyControlledState({
      controlledValue: open,
      defaultValue: defaultOpen
    });
    const arrowRef = useRef(null);
    const dialogContext = useContext(DialogContext);
    const [triggerHovered, setTriggerHovered] = useState(false);
    const [contentHovered, setContentHovered] = useState(false);
    const [actualPlacement, setActualPlacement] = useState(placement);
    const processMinHeight = typeof minHeight === "string" ? minHeight : `${minHeight}px`;
    usePopoverTransitionStates(popover, openState, {
      onOpenAnimationStart: useCallback(() => {
        onOpenAnimationStart?.();
      }, [onOpenAnimationStart]),
      onOpenAnimationComplete: useCallback(() => {
        onOpenAnimationComplete?.();
      }, [onOpenAnimationComplete]),
      onCloseAnimationStart: useCallback(() => {
        onCloseAnimationStart?.();
      }, [onCloseAnimationStart]),
      onCloseAnimationComplete: useCallback(() => {
        onCloseAnimationComplete?.();
      }, [onCloseAnimationComplete])
    });
    const updatePosition = useCallback(() => {
      if (!invoker || !popover) return;
      if (!openState) return;
      computePosition(invoker, popover, {
        placement,
        middleware: [
          offset(8),
          size({
            padding: 5,
            apply({ rects, availableHeight, elements }) {
              Object.assign(elements.floating.style, {
                ...matchReferenceWidth ? { width: `${rects.reference.width}px` } : fixedWidth ? { width: "40dvw" } : {},
                ...fillAvailableHeight ? {
                  height: `${availableHeight - 20}px`,
                  minHeight: processMinHeight
                } : {},
                ...maxHeight ? {
                  minHeight: processMinHeight,
                  height: fitScreen ? typeof maxHeight === "string" ? maxHeight : `${maxHeight}px` : void 0,
                  maxHeight: fitScreen ? `${availableHeight - 20}px` : typeof maxHeight === "string" ? maxHeight : `${maxHeight}px`
                } : {},
                ...fitScreen && !maxHeight ? {
                  minHeight: processMinHeight,
                  maxHeight: `${availableHeight - 20}px`
                } : {},
                zIndex: 1
              });
            }
          }),
          flip({
            mainAxis: !disableFlip,
            crossAxis: false,
            fallbackAxisSideDirection: disableFlipFallback ? "none" : "end",
            padding: 5
          }),
          shift({
            padding: 5,
            mainAxis: !disableShift,
            crossAxis: false,
            limiter: limitShift({
              mainAxis: !disableShift
            })
          }),
          arrow$1({
            element: !disableCaret && arrowElement ? arrowElement : null,
            padding: 5
          })
        ]
      }).then(({ x, y, placement: placement2, middlewareData }) => {
        setActualPlacement(placement2);
        const side = placement2.split("-")[0];
        const staticSide = {
          top: "bottom",
          right: "left",
          bottom: "top",
          left: "right"
        }[side];
        const arrowDeg = () => {
          if (staticSide === "top") return 180;
          if (staticSide === "bottom") return 0;
          if (staticSide === "left") return 90;
          return 270;
        };
        Object.assign(popover.style, {
          left: `${x}px`,
          top: `${y}px`
        });
        if (middlewareData.arrow && arrowElement) {
          const { x: x2, y: y2 } = middlewareData.arrow;
          Object.assign(arrowElement.style, {
            left: x2 != null ? `${x2}px` : "",
            top: y2 != null ? `${y2}px` : "",
            right: "",
            bottom: "",
            [staticSide]: `${-arrowElement.offsetWidth + 2}px`,
            transform: `rotate(${arrowDeg()}deg)`
          });
        }
      });
    }, [
      arrowElement,
      disableCaret,
      disableFlip,
      disableFlipFallback,
      disableShift,
      fillAvailableHeight,
      fitScreen,
      fixedWidth,
      invoker,
      matchReferenceWidth,
      maxHeight,
      openState,
      placement,
      popover,
      processMinHeight
    ]);
    useLayoutEffect(() => {
      if (!popover || !invoker) return;
      if (!openState) {
        return;
      }
      let requestID = null;
      const cleanup = autoUpdate(invoker, popover, () => {
        requestID = requestAnimationFrame(updatePosition);
      });
      return () => {
        if (requestID) cancelAnimationFrame(requestID);
        cleanup();
      };
    }, [invoker, popover, updatePosition, openState]);
    popover?.getRootNode();
    const popoverId = id ?? `popover-${uid.replace(/:/g, "")}`;
    const isControlled = typeof open !== "undefined";
    const openPopover = useCallback(() => {
      if (!popover || !rootNode?.querySelector(`#${popoverId}`))
        return;
      setOpenState(true);
    }, [popover, rootNode, popoverId, setOpenState]);
    const closePopover = useCallback(
      (fn) => {
        if (!popover || !openState) return;
        if (!openOnHover) onClose?.();
        setOpenState(false);
        setTriggerHovered(false);
        setContentHovered(false);
        fn?.();
      },
      [
        popover,
        openState,
        openOnHover,
        onClose,
        setOpenState,
        setTriggerHovered,
        setContentHovered
      ]
    );
    useImperativeHandle(
      ref,
      () => ({
        openPopover,
        closePopover
      }),
      [openPopover, closePopover]
    );
    useEffect(() => {
      if (typeof openState === "undefined") return;
      if (openState) {
        if (dialogContext) {
          if (dialogContext?.ref?.current?.open) {
            safeShowPopover(popover);
            dialogContext?.setHasOpenPopover?.(true);
          }
          return;
        }
        safeShowPopover(popover);
      } else {
        safeHidePopover(popover);
        dialogContext?.setHasOpenPopover?.(false);
      }
    }, [openState, openPopover, closePopover, dialogContext, popover]);
    useOnClickOutside({
      disable: disableCloseOnClickOutside || !openState,
      onClickOutsideBegin: (e) => {
        if (!openState) return;
        onClickOutside?.(e);
      },
      targets: [invoker, popover],
      onClickOutside: () => {
        if (openOnHover || isControlled) return;
        closePopover();
      }
    });
    const value = useMemo(() => {
      return {
        popoverId,
        invoker,
        setInvoker,
        popover,
        setPopover,
        arrowElement,
        setArrowElement,
        openPopover,
        closePopover,
        placement,
        actualPlacement,
        onClose,
        openOnHover,
        openState,
        setOpenState,
        disableCloseOnClickOutside,
        fillAvailableHeight,
        maxHeight,
        matchReferenceWidth,
        fixedWidth,
        disableCaret,
        disableFlipFallback,
        disableTriggerFocus,
        disableCloseOnEscape,
        noPadding,
        controlled: isControlled,
        modal,
        arrowRef,
        rootNode,
        setRootNode,
        delay,
        triggerHovered,
        setTriggerHovered,
        contentHovered,
        setContentHovered
      };
    }, [
      popoverId,
      invoker,
      popover,
      arrowElement,
      openPopover,
      closePopover,
      placement,
      actualPlacement,
      onClose,
      openOnHover,
      openState,
      setOpenState,
      disableCloseOnClickOutside,
      fillAvailableHeight,
      maxHeight,
      matchReferenceWidth,
      fixedWidth,
      disableCaret,
      disableFlipFallback,
      disableTriggerFocus,
      disableCloseOnEscape,
      noPadding,
      isControlled,
      modal,
      rootNode,
      delay,
      triggerHovered,
      setTriggerHovered,
      contentHovered,
      setContentHovered
    ]);
    return /* @__PURE__ */ jsx(PopoverContext.Provider, { value, children });
  }),
  {
    /**
     * PopoverTrigger component for creating custom trigger elements.
     *
     * Features:
     * - Supports custom trigger elements via render prop pattern
     * - Automatic focus management and keyboard interaction
     * - Hover and click event handling
     * - Accessibility attributes (aria-haspopup, aria-expanded, aria-details)
     * - Context integration with parent popover
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Popover.Trigger>
     *   {(props) => (
     *     <button {...props}>
     *       Click to open popover
     *     </button>
     *   )}
     * </Popover.Trigger>
     */
    Trigger: PopoverTrigger,
    /**
     * PopoverContent component for the main popover content area.
     *
     * Features:
     * - Automatic positioning and sizing based on trigger
     * - Screen boundary detection and fitting
     * - Scroll handling with custom scroller reference
     * - Focus management and keyboard navigation
     * - Hover interaction support for tooltip mode
     * - Escape key handling for closing
     * - Tab key trapping for modal popovers
     * - Arrow/caret indicator with automatic positioning
     * - Context integration with parent popover
     * - Accessibility support with proper ARIA roles
     *
     * @example
     * <Popover.Content>
     *   <p>This is the popover content</p>
     *   <Popover.Close>Close</Popover.Close>
     * </Popover.Content>
     */
    Content: PopoverContent,
    /**
     * PopoverClose component for closing the popover.
     *
     * Features:
     * - Automatic popover closing on click
     * - Supports all Button component props and styling
     * - Controlled and uncontrolled mode support
     * - Context integration with parent popover
     * - Accessibility support with proper button semantics
     * - Delayed closing for controlled mode
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Popover.Close>Close</Popover.Close>
     */
    Close: PopoverClose,
    /**
     * PopoverButton component for creating button-style triggers.
     *
     * Features:
     * - Button styling and behavior with all Button props
     * - Automatic popover opening on click
     * - Hover interaction support for tooltip mode
     * - Focus management and keyboard navigation
     * - Accessibility attributes (aria-haspopup, aria-expanded, aria-details)
     * - Context integration with parent popover
     * - Event handling for mouse, keyboard, and focus events
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Popover.Button>Click to open</Popover.Button>
     */
    Button: PopoverButton
  }
);
Popover.displayName = "Popover";

export { Popover as P, usePopoverContext as u };
//# sourceMappingURL=Popover-CdRuNv3C.js.map
