import { jsxs, jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { createContext, forwardRef, useContext, useId, useRef, useState, useCallback, useLayoutEffect, useEffect, useMemo } from 'react';
import { c as cx } from './index-De1g9FRV.js';
import { S as SvgArrowDropDown } from './arrow_drop_down-ChAdBDux.js';
import { B as Button } from './Button-Bnt8XUI7.js';
import { D as DialogContext } from './DialogContext-DBgtApl9.js';
import { I as Icon } from './Icon-BMMbp40n.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { c as childrenToString } from './childrenToString-Bz9MqbHb.js';
import { useTrackingId } from './useTrackingId.js';
import { c as computePosition, o as offset, f as flip, d as shift, g as size, l as limitShift, a as autoUpdate, s as safeShowPopover, b as safeHidePopover } from './floating-ui.react-dom-CHrYz13o.js';
import { g as getActiveElement } from './getActiveElement-BcSyVE7S.js';

import './Menu.css';const SvgArrowDropUp = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "1em", height: "1em", viewBox: "0 0 24 24", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M8.71 12.29 11.3 9.7a.996.996 0 0 1 1.41 0l2.59 2.59c.63.63.18 1.71-.71 1.71H9.41c-.89 0-1.33-1.08-.7-1.71z" }));

const MenuContext = createContext(null);

const content = "_content_11i8b_1";
const scroller = "_scroller_11i8b_55";
const item = "_item_11i8b_69";
const styles = {
	content: content,
	scroller: scroller,
	item: item,
	"arrow-down": "_arrow-down_11i8b_118",
	"arrow-up": "_arrow-up_11i8b_119",
	"arrow-icon": "_arrow-icon_11i8b_133"};

const MenuItem = forwardRef((props, ref) => {
  const {
    label,
    disabled,
    icon,
    className,
    onClick,
    onMouseEnter,
    id: idProp,
    ...rest
  } = props;
  const menuContext = useContext(MenuContext);
  const uid = useId();
  const buttonRef = useRef(null);
  const combinedRef = useMergeRefs([buttonRef, ref]);
  const [tabIndex, setTabIndex] = useState(-1);
  const itemCx = cx([styles["item"]], className);
  const onClickHandler = (e) => {
    if (disabled) {
      e.preventDefault();
      e.stopPropagation();
      return;
    }
    onClick?.(e);
    menuContext?.closeRootMenu();
  };
  const onMouseEnterHandler = (e) => {
    onMouseEnter?.(e);
    buttonRef.current?.focus();
  };
  const onFocusHandler = () => {
    setTabIndex(0);
  };
  const onBlurHandler = () => {
    setTabIndex(-1);
  };
  const data = {
    label: childrenToString(props.label)
  };
  const trackingId = useTrackingId({
    name: "MenuItem",
    data,
    hasOverride: !!props["data-tracking-id"]
  });
  return /* @__PURE__ */ jsxs(
    "button",
    {
      "data-tracking-id": trackingId,
      ...rest,
      ref: combinedRef,
      type: "button",
      role: "menuitem",
      "data-anv": "menu-item",
      id: idProp ?? `menuitem-${uid.replace(/:/g, "")}`,
      className: itemCx,
      tabIndex,
      "aria-disabled": disabled,
      onClick: onClickHandler,
      onMouseEnter: onMouseEnterHandler,
      onFocus: onFocusHandler,
      onBlur: onBlurHandler,
      children: [
        icon ? /* @__PURE__ */ jsx(Icon, { inherit: true, "aria-hidden": true, svg: icon }) : null,
        label
      ]
    }
  );
});
MenuItem.displayName = "MenuItem";

const SvgNavigateNext = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "1em", height: "1em", viewBox: "0 0 24 24", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M9.31 6.71a.996.996 0 0 0 0 1.41L13.19 12l-3.88 3.88a.996.996 0 1 0 1.41 1.41l4.59-4.59a.996.996 0 0 0 0-1.41L10.72 6.7c-.38-.38-1.02-.38-1.41.01z" }));

const MenuNested = (props) => {
  const { children, open, defaultOpen = false, label, className, icon } = props;
  const uid = useId();
  const [tabIndex, setTabIndex] = useState(-1);
  const [openState, setOpenState] = useState(open ?? defaultOpen);
  const [scrollTop, setScrollTop] = useState(0);
  const [menuHeight, setMenuHeight] = useState(null);
  const [arrowStart, setArrowStart] = useState(false);
  const [arrowEnd, setArrowEnd] = useState(false);
  const invokerRef = useRef(null);
  const menuRef = useRef(null);
  const childrenRef = useRef(null);
  const containerRef = useRef(null);
  const [focusItems, setFocusItems] = useState();
  const menuContext = useContext(MenuContext);
  const fallbackArr = useCallback(() => {
    return menuContext?.disableAutoHeight ? ["right-start"] : ["right-start", "right-end", "left-start", "left-end"];
  }, [menuContext?.disableAutoHeight]);
  const updatePosition = useCallback(() => {
    if (!invokerRef.current || !menuRef.current) return;
    computePosition(invokerRef.current, menuRef.current, {
      placement: "right-start",
      middleware: [
        offset({
          mainAxis: 0,
          alignmentAxis: -4
        }),
        flip({
          fallbackStrategy: "bestFit",
          fallbackPlacements: fallbackArr()
        }),
        shift({
          mainAxis: !menuContext?.disableAutoHeight,
          crossAxis: false,
          limiter: limitShift({
            mainAxis: !menuContext?.disableAutoHeight
          })
        }),
        size({
          padding: 8,
          apply({ availableWidth, availableHeight, elements }) {
            if (menuContext?.disableAutoHeight) return;
            const newHeight = availableHeight - 16;
            if (Math.abs((menuHeight ?? 0) - newHeight) > 1) {
              setMenuHeight(newHeight);
              Object.assign(elements.floating.style, {
                maxWidth: `${availableWidth - 16}px`,
                maxHeight: `${newHeight}px`
              });
            }
          }
        })
      ]
    }).then(({ x, y }) => {
      if (!menuRef.current) return;
      Object.assign(menuRef.current.style, {
        left: `${x}px`,
        top: `${y + 8}px`
      });
    });
  }, [fallbackArr, menuContext?.disableAutoHeight, menuHeight]);
  const menuReference = useRef(null);
  useLayoutEffect(() => {
    if (!openState) {
      setMenuHeight(null);
      setScrollTop(0);
      return;
    }
    if (!menuRef.current) return;
    menuReference.current = menuRef.current;
    let resizeTimeout = null;
    ({
      height: menuReference.current.clientHeight,
      scrollHeight: childrenRef.current?.scrollHeight ?? 0
    });
    const updateArrows = (height, scrollHeight) => {
      if (!childrenRef.current) return;
      const isOverflow = scrollHeight > height;
      setArrowStart(isOverflow && childrenRef.current.scrollTop > 0);
      setArrowEnd(isOverflow && scrollHeight - height - scrollTop - 16 > 0);
    };
    const observer = new ResizeObserver(() => {
      if (!childrenRef.current || !menuReference.current) return;
      if (resizeTimeout) {
        window.clearTimeout(resizeTimeout);
      }
      resizeTimeout = window.setTimeout(() => {
        const newHeight = menuReference.current?.clientHeight ?? 0;
        const newScrollHeight = childrenRef.current?.scrollHeight ?? 0;
        if (!newHeight) return;
        updateArrows(newHeight, newScrollHeight);
      }, 100);
    });
    if (menuReference.current) {
      observer.observe(menuReference.current);
    }
    return () => {
      if (resizeTimeout) {
        window.clearTimeout(resizeTimeout);
      }
      if (menuReference.current) {
        observer.unobserve(menuReference.current);
      }
      observer.disconnect();
    };
  }, [openState, scrollTop]);
  useLayoutEffect(() => {
    if (!menuRef.current || !invokerRef.current) return;
    if (!openState) return;
    let requestID = null;
    const cleanup = autoUpdate(invokerRef.current, menuRef.current, () => {
      requestID = requestAnimationFrame(updatePosition);
    });
    return () => {
      if (requestID) cancelAnimationFrame(requestID);
      cleanup();
    };
  }, [updatePosition, openState]);
  const popoverHoverTriggered = useRef();
  const openMenu = useCallback(async () => {
    popoverHoverTriggered.current = true;
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (!popoverHoverTriggered.current || !menuRef.current || !childrenRef.current)
      return;
    menuRef.current.style.opacity = "0";
    safeShowPopover(menuRef.current);
    if (!invokerRef.current || !menuRef.current) return;
    await computePosition(invokerRef.current, menuRef.current, {
      placement: "right-start",
      middleware: [
        offset({
          mainAxis: 0,
          alignmentAxis: -4
        }),
        flip({
          fallbackStrategy: "bestFit",
          fallbackPlacements: fallbackArr()
        }),
        shift({
          mainAxis: !menuContext?.disableAutoHeight,
          crossAxis: false,
          limiter: limitShift({
            mainAxis: !menuContext?.disableAutoHeight
          })
        })
      ]
    }).then(({ x, y }) => {
      if (!menuRef.current) return;
      Object.assign(menuRef.current.style, {
        left: `${x}px`,
        top: `${y + 8}px`
      });
    });
    setOpenState(true);
    const focusables = Array.from(
      childrenRef.current.querySelectorAll(
        `#scroller-${uid.replace(/:/g, "")} > button, #scroller-${uid.replace(/:/g, "")} > div[data-nested="true"] > button, #scroller-${uid.replace(/:/g, "")} > a[href]`
      )
    );
    setFocusItems(focusables);
    requestAnimationFrame(() => {
      if (!menuRef.current) return;
      menuRef.current.style.opacity = "1";
    });
  }, [uid, fallbackArr, menuContext?.disableAutoHeight]);
  const closeMenu = useCallback(async (fn) => {
    popoverHoverTriggered.current = false;
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (popoverHoverTriggered.current || !menuRef.current) return;
    fn?.();
    safeHidePopover(menuRef.current);
    setOpenState(false);
  }, []);
  const isControlled = typeof open !== "undefined";
  const initialRender = useRef(true);
  useEffect(() => {
    if (!isControlled) return;
    if (initialRender.current === true) {
      if (open && menuRef.current) {
        openMenu();
      }
      initialRender.current = false;
      return;
    }
    setOpenState(open);
    if (open) {
      openMenu();
    } else {
      closeMenu();
    }
  }, [closeMenu, isControlled, open, openMenu]);
  useEffect(() => {
    if (!containerRef.current) return;
    const nestedContainer = containerRef.current;
    nestedContainer.addEventListener("focusin", (_e) => {
      openMenu();
    });
    nestedContainer.addEventListener("focusout", () => closeMenu());
    return () => {
      nestedContainer.removeEventListener("focusin", () => openMenu());
      nestedContainer.removeEventListener("focusout", () => closeMenu());
    };
  }, [closeMenu, openMenu]);
  const onKeyDownHandler = (e) => {
    if (!openState || !childrenRef.current) return;
    const currentActiveIndex = focusItems?.findIndex(
      (item) => item.id === getActiveElement(document)?.id
    );
    const firstItem = focusItems?.[0];
    const lastItem = focusItems?.[focusItems.length - 1];
    if (e.code === "Escape") {
      menuContext?.closeRootMenu();
    }
    if (e.code === "ArrowLeft") {
      e.stopPropagation();
      e.preventDefault();
      invokerRef.current?.focus();
      closeMenu();
    }
    if (e.code === "ArrowDown") {
      e.stopPropagation();
      if (currentActiveIndex === (focusItems?.length ?? 0) - 1) {
        firstItem.focus();
        return;
      }
      const nextItem = focusItems?.[(currentActiveIndex ?? 0) + 1];
      nextItem.focus();
      return;
    }
    if (e.code === "ArrowUp") {
      e.stopPropagation();
      e.preventDefault();
      if (currentActiveIndex === 0) {
        lastItem.focus();
        return;
      }
      const prevItem = focusItems?.[(currentActiveIndex ?? 0) - 1];
      prevItem.focus();
      return;
    }
  };
  const onFocusHandler = () => {
    setTabIndex(0);
  };
  const onBlurHandler = () => {
    setTabIndex(-1);
  };
  const MenuButtonOnKeyDownHandler = (e) => {
    if (e.code === "ArrowRight") {
      e.stopPropagation();
      e.preventDefault();
      openMenu();
      const firstItem = menuRef.current?.querySelectorAll(
        `#scroller-${uid.replace(/:/g, "")} > button, #scroller-${uid.replace(/:/g, "")} > a[href]`
      )[0];
      firstItem.focus();
    }
  };
  const MenuButtonOnClick = () => {
    if (isControlled) return;
    openMenu();
  };
  const itemCx = cx([styles["item"]], className);
  return /* @__PURE__ */ jsxs("div", { ref: containerRef, "data-nested": "true", children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        role: "menuitem",
        "data-anv": "menu-item",
        "data-state": openState ? "open" : "close",
        ref: invokerRef,
        id: `menuitem-${uid.replace(/:/g, "")}`,
        "aria-expanded": openState,
        onMouseEnter: (e) => {
          e.currentTarget.focus();
        },
        onKeyDown: MenuButtonOnKeyDownHandler,
        onFocus: onFocusHandler,
        onBlur: onBlurHandler,
        onClick: MenuButtonOnClick,
        "aria-haspopup": true,
        "aria-controls": `menu-${uid.replace(/:/g, "")}`,
        className: itemCx,
        tabIndex,
        children: [
          icon ? /* @__PURE__ */ jsx(Icon, { inherit: true, "aria-hidden": true, svg: icon }) : null,
          label,
          /* @__PURE__ */ jsx("div", { style: { flexGrow: 1 } }),
          /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, svg: SvgNavigateNext })
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "div",
      {
        popover: "auto",
        id: `menu-${uid.replace(/:/g, "")}`,
        "data-anv": "menu-content",
        className: styles.content,
        ref: menuRef,
        role: "presentation",
        onKeyDown: onKeyDownHandler,
        children: [
          arrowStart && /* @__PURE__ */ jsx("div", { className: styles["arrow-up"], "aria-hidden": true, children: /* @__PURE__ */ jsx(Icon, { svg: SvgArrowDropUp, size: "xlarge", className: styles["arrow-icon"] }) }),
          /* @__PURE__ */ jsx(
            "div",
            {
              className: styles.scroller,
              tabIndex: -1,
              ref: childrenRef,
              style: {
                position: "relative",
                maxHeight: menuHeight ?? "inherit"
              },
              onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
              role: "menu",
              id: `scroller-${uid.replace(/:/g, "")}`,
              children
            }
          ),
          arrowEnd && /* @__PURE__ */ jsx("div", { className: styles["arrow-down"], "aria-hidden": true, children: /* @__PURE__ */ jsx(Icon, { svg: SvgArrowDropDown, size: "xlarge", className: styles["arrow-icon"] }) })
        ]
      }
    )
  ] });
};

const Menu = Object.assign(
  function MenuInner(props) {
    const {
      children,
      placement = "bottom-start",
      open,
      defaultOpen = false,
      disableAutoHeight,
      label,
      onOutsidePress,
      trigger,
      contentClassName,
      maxHeight,
      ...rest
    } = props;
    const uid = useId();
    const [openState, setOpenState] = useState(open ?? defaultOpen);
    const [scrollTop, setScrollTop] = useState(0);
    const [menuHeight, setMenuHeight] = useState(null);
    const [arrowStart, setArrowStart] = useState(false);
    const [arrowEnd, setArrowEnd] = useState(false);
    const invokerRef = useRef(null);
    const menuRef = useRef(null);
    const childrenRef = useRef(null);
    const [focusItems, setFocusItems] = useState();
    const dialogContext = useContext(DialogContext);
    const menuContext = useContext(MenuContext);
    const fallbackArr = useCallback(() => {
      if (placement.startsWith("top")) {
        return disableAutoHeight ? [placement] : ["top-start", "top-end", "bottom-start", "bottom-end"];
      }
      return disableAutoHeight ? [placement] : ["bottom-start", "bottom-end", "top-start", "top-end"];
    }, [disableAutoHeight, placement]);
    const updatePosition = useCallback(() => {
      if (!invokerRef.current || !menuRef.current) return;
      computePosition(invokerRef.current, menuRef.current, {
        placement,
        middleware: [
          offset({
            mainAxis: 5,
            alignmentAxis: 0
          }),
          flip({
            fallbackStrategy: "bestFit",
            fallbackPlacements: fallbackArr(),
            padding: 50
            // Setting to 50px as it is the size of menu with 1 item in it
          }),
          shift({
            mainAxis: !menuContext?.disableAutoHeight,
            crossAxis: false,
            limiter: limitShift({
              mainAxis: !menuContext?.disableAutoHeight
            })
          }),
          size({
            padding: 8,
            apply({ availableWidth, availableHeight, elements }) {
              if (disableAutoHeight ?? menuContext?.disableAutoHeight) return;
              const newHeight = availableHeight - 16;
              if (Math.abs((menuHeight ?? 0) - newHeight) > 1) {
                setMenuHeight(newHeight);
                Object.assign(elements.floating.style, {
                  maxWidth: `${availableWidth - 16}px`,
                  maxHeight: maxHeight ? `${Math.min(newHeight, typeof maxHeight === "number" ? maxHeight : parseInt(maxHeight.toString()))}px` : `${newHeight}px`
                });
              }
            }
          })
        ]
      }).then(({ x, y }) => {
        if (!menuRef.current) return;
        Object.assign(menuRef.current.style, {
          left: `${x}px`,
          top: `${y}px`
        });
        menuRef.current.dataset.positioned = "true";
      });
    }, [
      placement,
      fallbackArr,
      menuContext?.disableAutoHeight,
      disableAutoHeight,
      menuHeight,
      maxHeight
    ]);
    const menuReference = useRef(null);
    useLayoutEffect(() => {
      if (!openState) {
        setMenuHeight(null);
        setScrollTop(0);
        return;
      }
      if (!menuRef.current) return;
      menuReference.current = menuRef.current;
      let resizeTimeout = null;
      ({
        height: menuReference.current.clientHeight,
        scrollHeight: childrenRef.current?.scrollHeight ?? 0
      });
      const updateArrows = (height, scrollHeight) => {
        if (!childrenRef.current) return;
        const isOverflow = scrollHeight > height;
        setArrowStart(isOverflow && childrenRef.current.scrollTop > 0);
        setArrowEnd(isOverflow && scrollHeight - height - scrollTop - 16 > 0);
      };
      const observer = new ResizeObserver(() => {
        if (!childrenRef.current || !menuReference.current) return;
        if (resizeTimeout) {
          window.clearTimeout(resizeTimeout);
        }
        resizeTimeout = window.setTimeout(() => {
          const newHeight = menuReference.current?.clientHeight ?? 0;
          const newScrollHeight = childrenRef.current?.scrollHeight ?? 0;
          if (!newHeight) return;
          updateArrows(newHeight, newScrollHeight);
        }, 150);
      });
      if (menuReference.current) {
        observer.observe(menuReference.current);
      }
      return () => {
        if (resizeTimeout) {
          window.clearTimeout(resizeTimeout);
        }
        if (menuReference.current) {
          observer.unobserve(menuReference.current);
        }
        observer.disconnect();
      };
    }, [openState, scrollTop]);
    useLayoutEffect(() => {
      if (!menuRef.current || !invokerRef.current) return;
      if (!openState) return;
      let requestID = null;
      const cleanup = autoUpdate(invokerRef.current, menuRef.current, () => {
        requestID = requestAnimationFrame(updatePosition);
      });
      return () => {
        if (requestID) cancelAnimationFrame(requestID);
        cleanup();
      };
    }, [updatePosition, openState]);
    const openMenu = useCallback(async () => {
      if (!menuRef.current || !childrenRef.current) return;
      safeShowPopover(menuRef.current);
      if (!invokerRef.current || !menuRef.current) return;
      await computePosition(invokerRef.current, menuRef.current, {
        placement,
        middleware: [
          offset({
            mainAxis: 5,
            alignmentAxis: 0
          }),
          flip({
            fallbackStrategy: "bestFit",
            fallbackPlacements: fallbackArr(),
            padding: 50
            // Setting to 50px as it is the size of menu with 1 item in it
          }),
          shift({
            mainAxis: !menuContext?.disableAutoHeight,
            crossAxis: false,
            limiter: limitShift({
              mainAxis: !menuContext?.disableAutoHeight
            })
          })
        ]
      }).then(({ x, y }) => {
        if (!menuRef.current) return;
        Object.assign(menuRef.current.style, {
          left: `${x}px`,
          top: `${y}px`
        });
        menuRef.current.dataset.positioned = "true";
      });
      setOpenState(true);
      requestAnimationFrame(() => {
        if (!childrenRef.current) return;
        const focusables = Array.from(
          childrenRef.current.querySelectorAll(
            `#scroller-${uid.replace(/:/g, "")} > button, #scroller-${uid.replace(/:/g, "")} > div[data-nested="true"] > button, #scroller-${uid.replace(/:/g, "")} > a[href]`
          )
        );
        setFocusItems(focusables);
      });
      dialogContext?.setHasOpenPopover?.(true);
    }, [
      dialogContext,
      uid,
      placement,
      fallbackArr,
      menuContext?.disableAutoHeight
    ]);
    const closeMenu = useCallback(
      async (fn, options) => {
        if (!menuRef.current || !openState) return;
        fn?.();
        setOpenState(false);
        safeHidePopover(menuRef.current);
        dialogContext?.setHasOpenPopover?.(false);
        if (!options?.skipInvokerRefocus) {
          invokerRef.current?.focus();
        }
      },
      [openState, dialogContext]
    );
    const isControlled = typeof open !== "undefined";
    const initialRender = useRef(true);
    useEffect(() => {
      if (!isControlled) return;
      if (initialRender.current === true) {
        if (open && menuRef.current) {
          openMenu();
        }
        initialRender.current = false;
        return;
      }
      if (open) {
        openMenu();
      } else {
        closeMenu(void 0, { skipInvokerRefocus: true });
      }
    }, [closeMenu, isControlled, open, openMenu, dialogContext]);
    useEffect(() => {
      if (typeof document === "undefined") return;
      let isClosable = false;
      const onMouseDownHandler = (e) => {
        if (!invokerRef.current || !menuRef.current) return;
        const isInvoker = e.composedPath().includes(invokerRef.current);
        const isPopover = e.composedPath().includes(menuRef.current);
        if (!isInvoker && !isPopover && openState) {
          onOutsidePress?.(e);
          isClosable = true;
        }
      };
      const onMouseUpHandler = (e) => {
        if (!invokerRef.current || !menuRef.current) return;
        const isInvoker = e.composedPath().includes(invokerRef.current);
        const isPopover = e.composedPath().includes(menuRef.current);
        if (!isInvoker && !isPopover && openState) {
          if (isControlled || !isClosable || !openState) return;
          closeMenu(void 0, { skipInvokerRefocus: true });
        }
      };
      document.addEventListener("mousedown", onMouseDownHandler);
      document.addEventListener("mouseup", onMouseUpHandler);
      return () => {
        document.removeEventListener("mousedown", onMouseDownHandler);
        document.removeEventListener("mouseup", onMouseUpHandler);
      };
    }, [isControlled, openState, onOutsidePress, closeMenu]);
    const onKeyDownHandler = (e) => {
      if (!openState || !childrenRef.current || menuContext) return;
      if (e.code === "Escape") {
        e.stopPropagation();
        e.preventDefault();
        closeMenu();
      }
      const currentActiveIndex = focusItems?.findIndex(
        (item) => item.id === getActiveElement(document)?.id
      );
      const firstItem = focusItems?.[0];
      const lastItem = focusItems?.[focusItems.length - 1];
      if (e.code === "ArrowDown") {
        e.stopPropagation();
        e.preventDefault();
        if (currentActiveIndex === (focusItems?.length ?? 0) - 1) {
          firstItem.focus();
          return;
        }
        const nextItem = focusItems?.[(currentActiveIndex ?? 0) + 1];
        nextItem.focus();
        return;
      }
      if (e.code === "ArrowUp") {
        e.stopPropagation();
        e.preventDefault();
        if (currentActiveIndex === 0) {
          lastItem.focus();
          return;
        }
        const prevItem = focusItems?.[(currentActiveIndex ?? 0) - 1];
        prevItem.focus();
        return;
      }
    };
    const value = useMemo(() => {
      return {
        disableAutoHeight,
        closeRootMenu: menuContext?.closeRootMenu ?? closeMenu
      };
    }, [disableAutoHeight, menuContext, closeMenu]);
    const MenuButtonOnKeyDownHandler = (e) => {
      if (e.code === "ArrowDown") {
        focusItems?.[0].focus();
        e.stopPropagation();
        e.preventDefault();
      }
    };
    const MenuButtonOnClick = () => {
      if (isControlled) return;
      if (openState) {
        closeMenu();
        return;
      }
      openMenu();
    };
    const data = {
      label: childrenToString(props.label)
    };
    const trackingId = useTrackingId({
      name: "Menu",
      data,
      hasOverride: !!props["data-tracking-id"]
    });
    if (menuContext) {
      return /* @__PURE__ */ jsx(MenuContext.Provider, { value, children: /* @__PURE__ */ jsx(
        MenuNested,
        {
          "data-tracking-id": trackingId,
          open,
          defaultOpen,
          className: props.className,
          icon: props.icon,
          label,
          children
        }
      ) });
    }
    return /* @__PURE__ */ jsxs(MenuContext.Provider, { value, children: [
      trigger ? trigger({
        ref: invokerRef,
        onClick: () => MenuButtonOnClick(),
        onKeyDown: MenuButtonOnKeyDownHandler,
        "aria-haspopup": true,
        "aria-controls": `menu-${uid.replace(/:/g, "")}`,
        "aria-expanded": openState,
        "data-state": openState ? "open" : "close"
      }) : /* @__PURE__ */ jsx(
        Button,
        {
          ref: invokerRef,
          onClick: MenuButtonOnClick,
          onKeyDown: MenuButtonOnKeyDownHandler,
          "aria-haspopup": true,
          "aria-controls": `menu-${uid.replace(/:/g, "")}`,
          "data-state": openState ? "open" : "close",
          "aria-expanded": openState,
          ...rest,
          children: label
        }
      ),
      /* @__PURE__ */ jsxs(
        "div",
        {
          popover: "manual",
          id: `menu-${uid.replace(/:/g, "")}`,
          "data-anv": "menu-content",
          className: cx(styles.content, contentClassName),
          onKeyDown: onKeyDownHandler,
          ref: menuRef,
          role: "presentation",
          children: [
            arrowStart && /* @__PURE__ */ jsx("div", { className: styles["arrow-up"], "aria-hidden": true, children: /* @__PURE__ */ jsx(Icon, { svg: SvgArrowDropUp, size: "xlarge", className: styles["arrow-icon"] }) }),
            /* @__PURE__ */ jsx(
              "div",
              {
                className: styles.scroller,
                tabIndex: -1,
                ref: childrenRef,
                style: {
                  position: "relative",
                  maxHeight: maxHeight ? `${Math.min(menuHeight ?? Infinity, typeof maxHeight === "number" ? maxHeight : parseInt(maxHeight.toString()))}px` : menuHeight ?? "inherit"
                },
                onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
                role: "menu",
                id: `scroller-${uid.replace(/:/g, "")}`,
                children
              }
            ),
            arrowEnd && /* @__PURE__ */ jsx("div", { className: styles["arrow-down"], "aria-hidden": true, children: /* @__PURE__ */ jsx(Icon, { svg: SvgArrowDropDown, size: "xlarge", className: styles["arrow-icon"] }) })
          ]
        }
      )
    ] });
  },
  {
    /**
     * MenuItem component for individual menu options.
     *
     * Features:
     * - Supports icons and labels
     * - Keyboard navigation support
     * - Disabled state handling
     * - Automatic menu closing on selection
     * - Fully accessible with proper ARIA attributes
     * - Focus management and tab index handling
     * - Click and mouse enter event handling
     *
     * @example
     * <Menu.Item
     *   label="Edit Profile"
     *   icon={EditIcon}
     *   onClick={() => console.log('Edit profile clicked')}
     * />
     */
    Item: MenuItem
  }
);

export { Menu as M };
//# sourceMappingURL=Menu-wpTyUDac.js.map
