import { usePopover } from "../hooks/usePopover.js";
import { colors } from "../utils/colors/index.js";
import { animations } from "../styledSystem/animations.js";
import { descriptors } from "../customizables/elementDescriptors.js";
import { withFloatingTree } from "./contexts/index.js";
import { Col, SimpleButton } from "../customizables/index.js";
import { Popover } from "./Popover.js";
import React, { cloneElement, isValidElement, useRef } from "react";
import { createContextAndHook } from "@clerk/shared/react";
import { jsx } from "@emotion/react/jsx-runtime";
import { useMergeRefs } from "@floating-ui/react";

//#region src/elements/Menu.tsx
const [MenuStateCtx, useMenuState] = createContextAndHook("MenuState");
const Menu = withFloatingTree((props) => {
	const { popoverPlacement = "bottom-end", elementId,...rest } = props;
	const popoverCtx = usePopover({
		placement: popoverPlacement,
		offset: 8,
		shoudFlip: true
	});
	const value = React.useMemo(() => ({ value: {
		popoverCtx,
		elementId
	} }), [{ ...popoverCtx }, elementId]);
	return /* @__PURE__ */ jsx(MenuStateCtx.Provider, {
		value,
		...rest
	});
});
const MenuTrigger = (props) => {
	const { children, ariaLabel } = props;
	const { popoverCtx, elementId } = useMenuState();
	const { reference, toggle, isOpen } = popoverCtx;
	const normalizedAriaLabel = typeof ariaLabel === "function" ? ariaLabel(isOpen) : ariaLabel;
	if (!isValidElement(children)) return null;
	return cloneElement(children, {
		ref: reference,
		elementDescriptor: children.props.elementDescriptor || descriptors.menuButton,
		elementId: children.props.elementId || descriptors.menuButton.setId(elementId),
		"aria-label": normalizedAriaLabel,
		"aria-expanded": isOpen,
		"aria-haspopup": "menu",
		onClick: (e) => {
			children.props?.onClick?.(e);
			toggle();
		}
	});
};
const findMenuItem = (el, siblingType, options) => {
	let tagName = options?.countSelf ? el.tagName : "";
	let sibling = el;
	while (sibling && tagName.toUpperCase() !== "BUTTON") {
		sibling = sibling[siblingType === "prev" ? "previousElementSibling" : "nextElementSibling"];
		tagName = sibling?.tagName ?? "";
	}
	return sibling;
};
const MenuList = (props) => {
	const { sx, asPortal,...rest } = props;
	const { popoverCtx, elementId } = useMenuState();
	const { floating, styles, isOpen, context, nodeId } = popoverCtx;
	const containerRef = useRef(null);
	const mergedRef = useMergeRefs([containerRef, floating]);
	const onKeyDown = (e) => {
		const current = containerRef.current;
		if (!current) return;
		if (current !== document.activeElement) return;
		if (e.key === "ArrowDown") {
			e.preventDefault();
			return findMenuItem(current.children[0], "next", { countSelf: true })?.focus();
		}
	};
	return /* @__PURE__ */ jsx(Popover, {
		context,
		nodeId,
		isOpen,
		portal: asPortal,
		children: /* @__PURE__ */ jsx(Col, {
			elementDescriptor: descriptors.menuList,
			elementId: descriptors.menuList.setId(elementId),
			ref: mergedRef,
			role: "menu",
			onKeyDown,
			sx: [(t) => ({
				backgroundColor: colors.makeSolid(t.colors.$colorBackground),
				borderWidth: t.borderWidths.$normal,
				borderStyle: t.borderStyles.$solid,
				borderColor: t.colors.$borderAlpha150,
				outline: "none",
				borderRadius: t.radii.$md,
				padding: t.space.$0x5,
				overflow: "hidden",
				top: `calc(100% + ${t.space.$2})`,
				animation: `${animations.dropdownSlideInScaleAndFade} ${t.transitionDuration.$slower} ${t.transitionTiming.$slowBezier}`,
				transformOrigin: "top center",
				zIndex: t.zIndices.$dropdown,
				gap: t.space.$0x5
			}), sx],
			style: styles,
			...rest
		})
	});
};
const MenuItem = (props) => {
	const { sx, onClick, destructive, closeAfterClick = true,...rest } = props;
	const { popoverCtx, elementId } = useMenuState();
	const { toggle } = popoverCtx;
	const buttonRef = useRef(null);
	const onKeyDown = (e) => {
		const current = buttonRef.current;
		if (!current) return;
		const key = e.key;
		if (key !== "ArrowUp" && key !== "ArrowDown") return;
		e.preventDefault();
		findMenuItem(current, key === "ArrowUp" ? "prev" : "next")?.focus();
	};
	return /* @__PURE__ */ jsx(SimpleButton, {
		ref: buttonRef,
		elementDescriptor: descriptors.menuItem,
		elementId: descriptors.menuItem.setId(elementId),
		hoverAsFocus: true,
		variant: "ghost",
		colorScheme: destructive ? "danger" : "neutral",
		role: "menuitem",
		onKeyDown,
		focusRing: false,
		onClick: (e) => {
			onClick?.(e);
			if (closeAfterClick) toggle();
		},
		sx: [(theme) => ({
			justifyContent: "start",
			borderRadius: theme.radii.$sm,
			padding: `${theme.space.$1} ${theme.space.$3}`,
			whiteSpace: "nowrap"
		}), sx],
		...rest
	});
};

//#endregion
export { Menu, MenuItem, MenuList, MenuTrigger };
//# sourceMappingURL=Menu.js.map