import { a as IconSize, c as ZIndex, n as AnalyticsId, o as KeyboardEventKey, s as LanguageLocales } from "../../constants2.js";
import { t as usePseudoClasses } from "../../usePseudoClasses.js";
import { n as mergeRefs } from "../../refs.js";
import { t as Icon_default } from "../../Icon.js";
import { n as useLanguage } from "../../useLanguage.js";
import { t as LazyIcon_default } from "../../LazyIcon.js";
import { t as isComponent } from "../../component.js";
import { t as useIsMobileBreakpoint } from "../../useIsMobileBreakpoint.js";
import { t as Button_default } from "../../Button.js";
import { t as useToggle } from "../../useToggle.js";
import { t as useKeyboardEvent } from "../../useKeyboardEvent.js";
import { t as useOutsideEvent } from "../../useOutsideEvent.js";
import { t as Checkbox_default } from "../../Checkbox2.js";
import { _ as autoUpdate, f as flip, g as size, h as shift, m as offset, o as useFloating } from "../../floating-ui.react.js";
import { n as HN_Designsystem_Dropdown_en_GB_default, t as HN_Designsystem_Dropdown_nb_NO_default } from "../../HN.Designsystem.Dropdown.nb-NO.js";
import { r as SingleSelectContext, t as SingleSelectItem } from "../../SingleSelectItem.js";
import { t as ChevronDown_default } from "../../ChevronDown.js";
import { t as ChevronUp_default } from "../../ChevronUp.js";
import { t as PlusSmall_default } from "../../PlusSmall.js";
import { t as Label_default } from "../../Label.js";
import classNames from "classnames";
import React, { useEffect, useId, useRef } from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { clamp } from "motion/react";
import styles from "./styles.module.scss";
const getResources = (language) => {
	switch (language) {
		case LanguageLocales.ENGLISH: return HN_Designsystem_Dropdown_en_GB_default;
		case LanguageLocales.NORWEGIAN:
		default: return HN_Designsystem_Dropdown_nb_NO_default;
	}
};
const SingleSelect = ({ name, disabled, defaultValue, onValueChange, children }) => {
	const [selected, setSelected] = React.useState(defaultValue);
	const context = React.useMemo(() => ({
		name,
		disabled,
		value: selected,
		onValueChange: (v, e) => {
			setSelected(v);
			onValueChange?.(v, e);
		}
	}), [
		name,
		disabled,
		selected,
		onValueChange
	]);
	return /* @__PURE__ */ jsx(SingleSelectContext.Provider, {
		value: context,
		children
	});
};
const DropdownBase = (props) => {
	const { triggerText, noCloseButton = false, onToggle, dropdownMinWidth, triggerMinWidth, open = false, children, testId, disabled, zIndex = ZIndex.PopOver, resources, svgIcon, variant = "fill" } = props;
	const dropdownRef = useRef(null);
	const optionsRef = useRef(null);
	const childrenRefList = useRef(React.Children.map(children, () => React.createRef()));
	const buttonRef = React.useRef(null);
	const { isHovered } = usePseudoClasses(buttonRef);
	const openedByKeyboard = useRef(false);
	const { value: isOpen, toggleValue: toggleIsOpen } = useToggle(!disabled && open, onToggle);
	const isMobile = useIsMobileBreakpoint();
	const triggerActualMinWidth = variant !== "borderless" && typeof triggerMinWidth != "undefined" ? `${triggerMinWidth}px` : "auto";
	const triggerMinWidthLimit = isMobile ? 96 : 112;
	const dropdownFloatingPadding = 15;
	const maxWidth = isMobile ? 384 : 400;
	const maxHeight = isMobile ? 384 : 464;
	const toggleTextId = useId();
	const optionIdPrefix = useId();
	const contentId = useId();
	const leftIconProps = {
		className: styles["dropdown__left-icon"],
		size: IconSize.XSmall,
		isHovered: !disabled && isHovered
	};
	const isSingleSelect = React.Children.toArray(children).every((child) => React.isValidElement(child) && isComponent(child, SingleSelectItem));
	const isMultiSelect = React.Children.toArray(children).every((child) => React.isValidElement(child) && isComponent(child, Checkbox_default));
	const { language } = useLanguage(LanguageLocales.NORWEGIAN);
	const mergedResources = {
		...getResources(language),
		...resources
	};
	const toggleClasses = classNames(styles.dropdown__toggle, {
		[styles["dropdown__toggle--open"]]: isOpen && !disabled,
		[styles["dropdown__toggle--with-icon"]]: typeof svgIcon !== "undefined",
		[styles["dropdown__toggle--transparent"]]: variant === "transparent",
		[styles["dropdown__toggle--borderless"]]: variant === "borderless"
	});
	const contentClasses = classNames(styles.dropdown__content, isOpen && styles["dropdown__content--open"]);
	const listItemClasses = classNames(styles["dropdown__list-item"], { [styles["dropdown__list-item--single-select"]]: isSingleSelect });
	const { refs, floatingStyles } = useFloating({
		strategy: "fixed",
		placement: "bottom-start",
		middleware: [
			offset(8),
			flip({
				mainAxis: false,
				fallbackPlacements: ["bottom-end"],
				padding: dropdownFloatingPadding
			}),
			shift({ padding: dropdownFloatingPadding }),
			size({
				padding: dropdownFloatingPadding,
				apply({ availableWidth, availableHeight, elements, rects }) {
					const triggerW = rects.reference.width;
					const minProp = typeof dropdownMinWidth !== "undefined" ? clamp(0, maxWidth, dropdownMinWidth) : 0;
					const targetW = Math.max(triggerW, minProp);
					Object.assign(elements.floating.style, {
						maxWidth: `${Math.min(targetW, availableWidth)}px`,
						maxHeight: `${Math.min(maxHeight, availableHeight)}px`,
						overflowY: "auto",
						overflowX: "hidden"
					});
				}
			})
		],
		whileElementsMounted: isOpen ? autoUpdate : void 0
	});
	const handleOpen = (isKeyboard) => {
		openedByKeyboard.current = isKeyboard;
		toggleIsOpen();
	};
	const handleClose = () => {
		if (!isOpen) return;
		toggleIsOpen();
		buttonRef.current?.focus();
	};
	useEffect(() => {
		if (isOpen && openedByKeyboard.current) {
			(childrenRefList.current?.find((r) => r.current && !r.current.hasAttribute("disabled")))?.current?.focus();
			openedByKeyboard.current = false;
		}
	}, [isOpen]);
	const focusByIndex = (nextIndex) => {
		childrenRefList.current?.[nextIndex]?.current?.focus();
	};
	const isListNavKey = (key) => key === KeyboardEventKey.ArrowDown || key === KeyboardEventKey.ArrowUp || key === KeyboardEventKey.Home || key === KeyboardEventKey.End;
	const handleKeyboardNavigation = (event) => {
		if (!childrenRefList.current) return;
		const key = event.key;
		if (key === KeyboardEventKey.Escape) {
			if (isOpen) {
				event.preventDefault();
				handleClose();
			}
			return;
		}
		if (!isOpen) {
			if (isListNavKey(key)) {
				event.preventDefault();
				handleOpen(true);
			}
			return;
		}
		if (!isListNavKey(key)) return;
		const index = childrenRefList.current.findIndex((x) => x.current === event.target);
		let nextIndex = index;
		if (key === KeyboardEventKey.Home) nextIndex = 0;
		else if (key === KeyboardEventKey.End) nextIndex = childrenRefList.current.length - 1;
		else if (key === KeyboardEventKey.ArrowDown && index < childrenRefList.current.length - 1) nextIndex = index + 1;
		else if (key === KeyboardEventKey.ArrowUp && index > 0) nextIndex = index - 1;
		if (nextIndex !== -1) {
			event.preventDefault();
			focusByIndex(nextIndex);
		}
	};
	useKeyboardEvent(dropdownRef, handleKeyboardNavigation, [
		KeyboardEventKey.ArrowDown,
		KeyboardEventKey.ArrowUp,
		KeyboardEventKey.End,
		KeyboardEventKey.Enter,
		KeyboardEventKey.Escape,
		KeyboardEventKey.Home,
		KeyboardEventKey.Space
	]);
	useOutsideEvent(dropdownRef, () => isOpen && handleClose());
	const renderChildren = React.Children.map(children, (child, index) => {
		const element = child;
		return /* @__PURE__ */ jsx("li", {
			className: listItemClasses,
			id: `${optionIdPrefix}-${index}`,
			children: React.isValidElement(element) && childrenRefList.current && childrenRefList.current[index] ? (() => {
				if (isMultiSelect && isComponent(element, Checkbox_default)) {
					const label = element.props.label;
					if (React.isValidElement(label) && isComponent(label, Label_default)) return React.cloneElement(element, {
						ref: mergeRefs([element.props.ref, childrenRefList.current[index]]),
						label: React.cloneElement(label, { labelClassName: classNames(label.props?.labelClassName, styles["dropdown__multiselect-item"]) })
					});
				}
				return React.cloneElement(child, { ref: mergeRefs([element.props.ref, childrenRefList.current[index]]) });
			})() : child
		});
	});
	return /* @__PURE__ */ jsxs("div", {
		className: styles.dropdown,
		ref: dropdownRef,
		children: [/* @__PURE__ */ jsxs("button", {
			type: "button",
			onClick: () => handleOpen(false),
			className: toggleClasses,
			ref: mergeRefs([buttonRef, refs.setReference]),
			"data-testid": testId,
			"data-analyticsid": AnalyticsId.Dropdown,
			disabled,
			"aria-labelledby": toggleTextId,
			"aria-haspopup": true,
			"aria-controls": contentId,
			"aria-expanded": isOpen,
			style: {
				width: triggerActualMinWidth,
				maxWidth: "100%",
				minWidth: `${triggerMinWidthLimit}px`
			},
			children: [
				svgIcon && /* @__PURE__ */ jsx(Fragment, { children: typeof svgIcon === "string" ? /* @__PURE__ */ jsx(LazyIcon_default, {
					...leftIconProps,
					iconName: svgIcon
				}) : /* @__PURE__ */ jsx(Icon_default, {
					...leftIconProps,
					svgIcon
				}) }),
				/* @__PURE__ */ jsx("span", {
					id: toggleTextId,
					className: styles.dropdown__toggle__text,
					children: triggerText
				}),
				/* @__PURE__ */ jsx(Icon_default, {
					svgIcon: !isSingleSelect ? PlusSmall_default : isOpen ? ChevronUp_default : ChevronDown_default,
					className: styles["dropdown__right-icon"],
					isHovered: !disabled && isHovered,
					size: IconSize.XSmall
				})
			]
		}), /* @__PURE__ */ jsxs("div", {
			id: contentId,
			className: contentClasses,
			ref: refs.setFloating,
			style: {
				...floatingStyles,
				zIndex
			},
			children: [/* @__PURE__ */ jsxs("ul", {
				className: styles.dropdown__options,
				role: "group",
				"aria-labelledby": toggleTextId,
				tabIndex: -1,
				ref: optionsRef,
				children: [isSingleSelect && /* @__PURE__ */ jsx(SingleSelect, {
					onValueChange: () => handleClose(),
					children: renderChildren
				}), isMultiSelect && renderChildren]
			}), !isSingleSelect && !noCloseButton && /* @__PURE__ */ jsx("div", {
				className: styles.dropdown__close,
				children: /* @__PURE__ */ jsx(Button_default, {
					onClick: handleClose,
					children: mergedResources.closeText
				})
			})]
		}, dropdownMinWidth ?? "auto")]
	});
};
var Dropdown = DropdownBase;
Dropdown.SingleSelectItem = SingleSelectItem;
DropdownBase.displayName = "Dropdown";
var Dropdown_default = Dropdown;
export { DropdownBase, Dropdown_default as default };

//# sourceMappingURL=index.js.map