import { jsx, jsxs } from 'react/jsx-runtime';
import { forwardRef, useId, useState, useEffect, useContext, useMemo, useRef, useCallback } from 'react';
import { B as Button } from './Button-BNzCI47m.js';
import { c as useOverFlowItemContext, u as useToolbarSize, s as styles$2, d as ToolbarItemWrapper, b as ToolbarContext, O as OverflowItemContext, e as handleMenuKeyboardNavigation, T as ToolbarButtonToggle, a as updateToolbarItemsTabIndex, h as handleToolbarKeyDown } from './ToolbarButtonToggle-3xbnm1Qr.js';
import { T as Tooltip } from './Tooltip-BC8lnFhe.js';
import { c as cx } from './index-De1g9FRV.js';
import { useTrackingId } from './useTrackingId.js';
import { B as ButtonLink } from './ButtonLink-PlW08u41.js';
import { S as SvgArrowDropDown } from './arrow_drop_down-ChAdBDux.js';
import { L as Listbox } from './Listbox-Cdwaofd2.js';
import { P as Popover } from './AiMark-voHPSerQ.js';
import { F as Flex } from './Flex-Bb3iHExM.js';
import { S as SvgMoreHoriz } from './more_horiz-DJgdQiy0.js';
import { S as SvgMoreVert } from './more_vert-C_lJSyxt.js';
import { I as Icon } from './Icon-B4uCvMU9.js';
import { S as SearchField } from './SearchField-X4B7f23E.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-DjqeAJZ9.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';

import './Toolbar.css';const ToolbarButton = forwardRef(
  (props, _ref) => {
    const { appearance = "ghost", className, children, ...rest } = props;
    const { isInOverflowMenu = false } = useOverFlowItemContext?.() || {};
    const size = useToolbarSize();
    const trackingId = useTrackingId({
      name: "ToolbarButton",
      data: {
        disabled: props.disabled,
        "aria-label": props["aria-label"],
        children: props.children
      },
      hasOverride: !!props["data-tracking-id"]
    });
    const buttonClassNames = cx(className, styles$2["toolbar-button-item"]);
    const item = children ? /* @__PURE__ */ jsx(
      Button,
      {
        "data-tracking-id": trackingId,
        appearance,
        size,
        "data-anv": "toolbar-button",
        className: buttonClassNames,
        ...rest,
        children
      }
    ) : /* @__PURE__ */ jsxs(Tooltip, { children: [
      /* @__PURE__ */ jsx(Tooltip.Trigger, { children: /* @__PURE__ */ jsx(
        Button,
        {
          "data-tracking-id": trackingId,
          appearance,
          size,
          "data-anv": "toolbar-button",
          className: buttonClassNames,
          ...rest
        }
      ) }),
      /* @__PURE__ */ jsx(Tooltip.Content, { children: rest["aria-label"] })
    ] });
    if (isInOverflowMenu) {
      return item;
    }
    return /* @__PURE__ */ jsx(ToolbarItemWrapper, { item: { itemProps: props, itemType: "button" }, children: item });
  }
);
ToolbarButton.displayName = "ToolbarButton";

const ToolbarButtonLink = forwardRef((props, _ref) => {
  const { appearance = "ghost", className, children, ...rest } = props;
  const { isInOverflowMenu = false } = useOverFlowItemContext?.() || {};
  const size = useToolbarSize();
  const trackingId = useTrackingId({
    name: "ToolbarButtonLink",
    data: {
      href: props.href,
      disabled: props.disabled,
      "aria-label": props["aria-label"],
      children: props.children,
      target: props.target
    },
    hasOverride: !!props["data-tracking-id"]
  });
  const buttonLinkClassNames = cx(className, styles$2["toolbar-button-item"]);
  const item = children ? /* @__PURE__ */ jsx(
    ButtonLink,
    {
      "data-tracking-id": trackingId,
      appearance,
      size,
      "data-anv": "toolbar-button-link",
      className: buttonLinkClassNames,
      ...rest,
      children
    }
  ) : /* @__PURE__ */ jsxs(Tooltip, { children: [
    /* @__PURE__ */ jsx(Tooltip.Trigger, { children: /* @__PURE__ */ jsx(
      ButtonLink,
      {
        "data-tracking-id": trackingId,
        appearance,
        size,
        "data-anv": "toolbar-button-link",
        className: buttonLinkClassNames,
        ...rest
      }
    ) }),
    /* @__PURE__ */ jsx(Tooltip.Content, { children: rest["aria-label"] })
  ] });
  if (isInOverflowMenu) {
    return item;
  }
  return /* @__PURE__ */ jsx(ToolbarItemWrapper, { item: { itemProps: props, itemType: "buttonLink" }, children: item });
});
ToolbarButtonLink.displayName = "ToolbarButtonLink";

const ToolbarSelect = forwardRef(
  (props, _ref) => {
    const {
      appearance = "ghost",
      onChange,
      selected: selectedItemId,
      accessibleLabel,
      className,
      items,
      ...rest
    } = props;
    const selectId = useId();
    const [isPopoverOpen, setIsPopoverOpen] = useState(false);
    const defaultId = items.length > 0 ? items[0].id : "";
    const [internalSelectedId, setInternalSelectedId] = useState(defaultId);
    const selectedId = selectedItemId ?? internalSelectedId;
    const selectedItem = items.find((item2) => item2.id === selectedId) || items.find((item2) => item2.id === defaultId);
    useEffect(() => {
      if (!selectedItemId && items.length > 0 && !items.some((item2) => item2.id === internalSelectedId)) {
        setInternalSelectedId(items[0].id);
      }
    }, [items, selectedItemId, internalSelectedId]);
    const handleSelectionChange = (selected) => {
      if (selected?.id) {
        if (selectedItemId === void 0) {
          setInternalSelectedId(selected.id);
        }
        onChange?.(selected.id);
        setIsPopoverOpen(false);
      }
    };
    const { isInOverflowMenu = false } = useOverFlowItemContext?.() || {};
    const toolbarSize = useToolbarSize();
    const trackingId = useTrackingId({
      name: "ToolbarSelect",
      data: {
        selected: props.selected,
        disabled: props.disabled,
        "aria-label": props["aria-label"],
        items: props.items
      },
      hasOverride: !!props["data-tracking-id"]
    });
    const buttonClassNames = cx(className, styles$2["toolbar-button-item"]);
    const item = /* @__PURE__ */ jsxs(
      Popover,
      {
        noPadding: true,
        open: isPopoverOpen,
        onClickOutside: () => {
          setIsPopoverOpen(false);
        },
        onClose: () => {
          setIsPopoverOpen(false);
        },
        children: [
          /* @__PURE__ */ jsx(
            Popover.Button,
            {
              "data-tracking-id": trackingId,
              appearance,
              size: toolbarSize,
              icon: { after: SvgArrowDropDown },
              className: buttonClassNames,
              id: selectId,
              "data-anv": "toolbar-select",
              onClick: () => {
                setIsPopoverOpen(!isPopoverOpen);
              },
              ...rest,
              children: selectedItem?.label
            }
          ),
          /* @__PURE__ */ jsx(
            Popover.Content,
            {
              className: styles$2["toolbar-select-content"],
              "aria-label": accessibleLabel,
              children: /* @__PURE__ */ jsx(
                Listbox,
                {
                  selected: selectedItem,
                  onSelectionChange: handleSelectionChange,
                  items,
                  "aria-labelledby": selectId,
                  disableAutoSelectOnFocus: true,
                  children: ({ items: items2 }) => items2.map((item2) => /* @__PURE__ */ jsx(Listbox.Option, { item: item2, children: item2.label }, item2.label))
                }
              )
            }
          )
        ]
      }
    );
    if (isInOverflowMenu) {
      return item;
    }
    return /* @__PURE__ */ jsx(ToolbarItemWrapper, { item: { itemProps: props, itemType: "select" }, children: item });
  }
);
ToolbarSelect.displayName = "ToolbarSelect";

const OverflowItem = ({ itemType, itemProps }) => {
  switch (itemType) {
    case "button":
      return /* @__PURE__ */ jsx(ToolbarButton, { ...itemProps });
    case "buttonToggle":
      return /* @__PURE__ */ jsx(ToolbarButtonToggle, { ...itemProps });
    case "buttonLink":
      return /* @__PURE__ */ jsx(ToolbarButtonLink, { ...itemProps });
    case "select":
      return /* @__PURE__ */ jsx(ToolbarSelect, { ...itemProps });
    default:
      return null;
  }
};
const ToolbarOverflowMenu = ({
  additionalItems,
  direction
}) => {
  const { overflowItems, orderedIds } = useContext(ToolbarContext);
  const menuTriggerId = useId();
  const size = useToolbarSize();
  const orderedItems = useMemo(() => {
    const allElements = orderedIds?.map((id) => {
      return overflowItems.find((item) => item.id === id);
    });
    return allElements?.filter((item) => item !== void 0) || [];
  }, [orderedIds, overflowItems]);
  const popoverButtonClassNames = cx(
    styles$2["toolbar-button-item"],
    styles$2["toolbar-overflow-trigger"]
  );
  const overflowIcon = direction === "horizontal" ? SvgMoreHoriz : SvgMoreVert;
  return /* @__PURE__ */ jsxs(Popover, { noPadding: true, children: [
    /* @__PURE__ */ jsx(
      Popover.Button,
      {
        size,
        appearance: "ghost",
        id: menuTriggerId,
        className: popoverButtonClassNames,
        "data-anv": "toolbar-overflow-trigger",
        "aria-label": "Additional toolbar options",
        children: /* @__PURE__ */ jsx(Icon, { svg: overflowIcon, size: size === "xsmall" ? "small" : size })
      }
    ),
    /* @__PURE__ */ jsx(Popover.Content, { children: /* @__PURE__ */ jsx(OverflowItemContext.Provider, { value: { isInOverflowMenu: true }, children: /* @__PURE__ */ jsxs(
      "ul",
      {
        role: "menu",
        className: styles$2["toolbar-overflow-content"],
        "data-anv": "toolbar-overflow-menu",
        "aria-labelledby": menuTriggerId,
        onKeyDown: handleMenuKeyboardNavigation,
        children: [
          orderedItems.map((item) => {
            const { itemType, itemProps, id } = item;
            return /* @__PURE__ */ jsx(
              "li",
              {
                role: "menuitem",
                "data-anv": "toolbar-overflow-item",
                children: /* @__PURE__ */ jsx(
                  OverflowItem,
                  {
                    itemType,
                    itemProps,
                    id
                  }
                )
              },
              `${itemType}-${id}`
            );
          }),
          additionalItems?.map((item, index) => /* @__PURE__ */ jsx(
            "li",
            {
              role: "menuitem",
              "data-anv": "toolbar-overflow-item",
              children: item
            },
            `additional-item-${index}`
          ))
        ]
      }
    ) }) })
  ] });
};

const styles$1 = {
	"toolbar-control-group": "_toolbar-control-group_th00x_1"
};

const ToolbarControlGroupElement = forwardRef((props, ref) => {
  const { children, "aria-label": ariaLabel, ...rest } = props;
  const { overflow } = useContext(ToolbarContext);
  return /* @__PURE__ */ jsx(
    Flex,
    {
      ref,
      alignItems: "center",
      gap: 1,
      wrap: overflow === "collapse" ? "nowrap" : "wrap",
      "data-anv": "toolbar-control-group",
      role: "group",
      "aria-label": ariaLabel ? ariaLabel : "Toolbar controls",
      className: styles$1["toolbar-control-group"],
      ...rest,
      children
    }
  );
});
ToolbarControlGroupElement.displayName = "ToolbarControlGroup";
const ToolbarControlGroup = ToolbarControlGroupElement;

const styles = {
	"toolbar-search-field-container": "_toolbar-search-field-container_1kk8y_1",
	"toolbar-search-field": "_toolbar-search-field_1kk8y_1"
};

const ToolbarSearchField = forwardRef(
  (props, ref) => {
    const { className, ...rest } = props;
    const size = useToolbarSize();
    const searchFieldStyles = cx(styles["toolbar-search-field"], className);
    return /* @__PURE__ */ jsx("div", { className: styles["toolbar-search-field-container"], children: /* @__PURE__ */ jsx(
      SearchField,
      {
        ref,
        className: searchFieldStyles,
        size,
        "data-anv": "toolbar-search-field",
        ...rest
      }
    ) });
  }
);
ToolbarSearchField.displayName = "ToolbarSearchField";

const Toolbar = Object.assign(
  forwardRef(function ToolbarInner(props, ref) {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const {
      associatedContent,
      className,
      children,
      style,
      direction = "horizontal",
      overflow = "wrap",
      onKeyDown,
      additionalItems,
      size = "xsmall",
      ...rest
    } = componentProps;
    const [overflowItems, setOverflowItems] = useState([]);
    const toolbarItemsRef = useRef(null);
    const toolbarRef = useRef(null);
    const [orderedIds, setOrderedIds] = useState([]);
    useEffect(() => {
      const newOrderedIds = Array.from(
        toolbarItemsRef.current?.querySelectorAll("[data-id]") || []
      ).map((el) => {
        return el.getAttribute("data-id");
      });
      setOrderedIds(newOrderedIds);
    }, [children]);
    const addItem = useCallback((item) => {
      setOverflowItems((prev) => [...prev, item]);
    }, []);
    const removeItem = useCallback((item) => {
      setOverflowItems(
        (prev) => prev.filter((component) => component.id !== item.id)
      );
    }, []);
    useEffect(() => {
      if (toolbarRef.current) {
        updateToolbarItemsTabIndex(toolbarRef.current);
      }
    }, [children]);
    const handleKeyDown = useCallback(
      (event) => {
        if (toolbarRef.current) {
          handleToolbarKeyDown(event, toolbarRef.current);
        }
        onKeyDown?.(event);
      },
      [onKeyDown]
    );
    const showOverflowMenu = overflow === "collapse" && overflowItems.length > 0 || !!additionalItems;
    const value = useMemo(
      () => ({
        overflowItems,
        addItem,
        removeItem,
        toolbarRef,
        orderedIds,
        overflow,
        size
      }),
      [
        overflowItems,
        addItem,
        removeItem,
        toolbarRef,
        orderedIds,
        overflow,
        size
      ]
    );
    const styleCombined = {
      ...style,
      ...layoutStyles
    };
    const toolbarClassNames = cx(styles$2["toolbar"], className);
    const toolbarContentClassNames = cx(styles$2["toolbar-content"], {
      [styles$2[`overflow-${overflow}`]]: overflow
    });
    return /* @__PURE__ */ jsx(ToolbarContext.Provider, { value, children: /* @__PURE__ */ jsxs(
      Flex,
      {
        direction: direction === "horizontal" ? "row" : "column",
        wrap: overflow === "wrap" ? "wrap" : "nowrap",
        alignItems: "center",
        className: toolbarClassNames,
        style: styleCombined,
        ref: useMergeRefs([toolbarRef, ref]),
        role: "toolbar",
        "data-anv": "toolbar",
        "aria-orientation": direction,
        "aria-label": `Toolbar for ${associatedContent}. Use arrow keys to navigate through toolbar controls.`,
        tabIndex: -1,
        onKeyDown: handleKeyDown,
        ...rest,
        children: [
          /* @__PURE__ */ jsx(
            Flex,
            {
              ref: useMergeRefs([toolbarItemsRef, ref]),
              className: toolbarContentClassNames,
              direction: direction === "horizontal" ? "row" : "column",
              wrap: overflow === "wrap" ? "wrap" : "nowrap",
              alignItems: "center",
              grow: 1,
              "data-anv": "toolbar-content",
              "data-overflow": overflow,
              children
            }
          ),
          showOverflowMenu && /* @__PURE__ */ jsx(
            ToolbarOverflowMenu,
            {
              direction,
              additionalItems
            }
          )
        ]
      }
    ) });
  }),
  {
    /**
     * ToolbarButton component for standard clickable actions within a toolbar with anvil2 tracking.
     *
     * Features:
     * - Designed specifically for toolbar integration
     * - Consistent styling with other toolbar items
     * - Automatic tooltip for icon-only buttons
     * - Overflow menu support
     * - Accessibility enforcement for aria-labels
     * - Ghost and primary appearance options
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Toolbar.Button icon={BoldIcon} aria-label="Bold text" />
     *
     * @example
     * <Toolbar.Button appearance="primary">
     *   Save
     * </Toolbar.Button>
     */
    Button: ToolbarButton,
    /**
     * ToolbarButtonToggle component for toggleable actions within a toolbar with anvil2 tracking.
     *
     * Features:
     * - Toggle state management
     * - Designed specifically for toolbar integration
     * - Consistent styling with other toolbar items
     * - Overflow menu support
     * - Accessibility enforcement for aria-labels
     * - Ghost and primary appearance options
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Toolbar.ButtonToggle icon={BoldIcon} aria-label="Bold" checked={isBold} />
     */
    ButtonToggle: ToolbarButtonToggle,
    /**
     * ToolbarButtonLink component for link actions within a toolbar with anvil2 tracking.
     *
     * Features:
     * - Link functionality with href support
     * - Designed specifically for toolbar integration
     * - Consistent styling with other toolbar items
     * - Overflow menu support
     * - Accessibility enforcement for aria-labels
     * - Ghost and primary appearance options
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Toolbar.ButtonLink href="/help">
     *   Help
     * </Toolbar.ButtonLink>
     */
    ButtonLink: ToolbarButtonLink,
    /**
     * ToolbarSelect component provides a dropdown selector within a toolbar with anvil2 tracking.
     *
     * Features:
     * - Dropdown menu with selectable options
     * - Controlled and uncontrolled usage patterns
     * - Automatic overflow menu integration
     * - Accessibility support with proper ARIA labels
     * - Ghost and primary appearance options
     * - Dropdown arrow icon indicator
     * - Listbox integration for keyboard navigation
     * - Automatic tracking ID generation for analytics
     *
     * @example
     * <Toolbar.Select
     *   items={fontOptions}
     *   selected="arial"
     *   accessibleLabel="Font family"
     *   onChange={(id) => setFont(id)}
     * />
     */
    Select: ToolbarSelect,
    /**
     * ToolbarControlGroup component provides a flex container for grouping related toolbar controls.
     * Can be used for filters, buttons, or other toolbar items.
     *
     * Features:
     * - Groups related toolbar controls in a flex container
     * - Supports accessibility with aria-label
     * - Handles overflow and wrapping based on toolbar context
     * - Integrates with layout utilities for spacing and alignment
     *
     * @example
     * <Toolbar.ControlGroup aria-label="Formatting controls">
     *   <Toolbar.Button icon={BoldIcon} aria-label="Bold" />
     *   <Toolbar.Button icon={ItalicIcon} aria-label="Italic" />
     * </Toolbar.ControlGroup>
     */
    ControlGroup: ToolbarControlGroup,
    /**
     * ToolbarSearchField component renders a search field for use in toolbars.
     *
     * Features:
     * - Renders a search field styled for toolbar usage
     * - Supports all SearchField props except size
     * - Integrates with toolbar layouts and accessibility
     *
     * @example
     * <Toolbar.Search placeholder="Search..." />
     */
    Search: ToolbarSearchField
  }
);
Toolbar.displayName = "Toolbar";
const ToolbarElement = Toolbar;

export { Toolbar as T, ToolbarButton as a, ToolbarButtonLink as b, ToolbarSelect as c, ToolbarControlGroup as d, ToolbarSearchField as e, ToolbarElement as f };
//# sourceMappingURL=Toolbar-BfGcDXgC.js.map
