import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import * as React from 'react';
import { useState, useEffect, useContext, createContext, useId, useRef, useCallback, forwardRef, useMemo } from 'react';
import { B as Button } from './Button-Bnt8XUI7.js';
import { T as Tooltip } from './Tooltip-BlStOXN3.js';
import { g as getKeyboardFocusableElements } from './getKeyboardFocusableElements-QqcABz0D.js';
import { c as cx } from './index-De1g9FRV.js';
import { u as useIntersectionObserver } from './useIntersectionObserver-BEmMDO3P.js';
import { useTrackingId } from './useTrackingId.js';
import { B as ButtonToggle } from './ButtonToggle-Ct9_5bhC.js';
import { B as ButtonLink } from './ButtonLink-j3h_wRNi.js';
import { S as SvgArrowDropDown } from './arrow_drop_down-ChAdBDux.js';
import { L as Listbox } from './Listbox-DDlxpVu9.js';
import { P as Popover } from './AiMark-B1-M3ZgP.js';
import { F as Flex } from './Flex-DOUtHiPi.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-BMMbp40n.js';
import { S as SvgClose } from './close-DZj38AEh.js';
import { S as SvgKeyboardArrowDown } from './keyboard_arrow_down-C8WQ38p1.js';
import { S as SvgEvent } from './TimezoneMessage-BrKB_psP.js';
import { D as DateTime } from './luxon-wpz4A-OQ.js';
import { C as Chip } from './Chip-CR5i8mQW.js';
import { t as tabbable } from './usePopoverTransitionStates-CDXCdyKa.js';
import { L as ListView } from './ListView-DBO9Bl1H.js';
import { S as SearchField, a as SvgSearch, b as SearchField$1 } from './SearchField-CsRGYZx3.js';
import { u as useDateFieldSingleConversion, a as useDateFieldSingleState, M as MaskedDateInput, b as DateFieldSingleCalendar, D as DateFieldSingle } from './DateFieldSingle-w1G-zd9G.js';
import { u as useDateFieldRangeConversion, a as useDateFieldRangeState, M as MaskedDateRangeInput, b as DateFieldRangeCalendar, D as DateFieldRange } from './DateFieldRange-DPTC3EZz.js';
import { C as Checkbox } from './Checkbox-Ckl8EFpF.js';
import { R as Radio } from './Radio-CQaXJ72d.js';
import { C as Combobox } from './Combobox-BffGTugd.js';
import { D as Drawer } from './Drawer-iewBy1DW.js';
import { d as BreakpointSm, c as BreakpointMd, b as BreakpointLg, a as BreakpointXl, B as BreakpointXxl } from './primitive-DXlHdTFb.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-CB_zHDbW.js';

import './Toolbar.css';function containerBreakpoint(containerWidth, name, min, max) {
  if ((min == null || containerWidth >= min) && (max == null || containerWidth < max)) {
    return {
      name,
      min,
      max,
      containerWidth,
      containerHeight: 0
      // Will be updated with actual height
    };
  }
  return void 0;
}
const getContainerBreakpoint = (containerWidth, containerHeight) => {
  if (!BreakpointSm) return;
  if (!BreakpointMd) return;
  if (!BreakpointLg) return;
  if (!BreakpointXl) return;
  if (!BreakpointXxl) return;
  const sm = parseInt(BreakpointSm.value);
  const md = parseInt(BreakpointMd.value);
  const lg = parseInt(BreakpointLg.value);
  const xl = parseInt(BreakpointXl.value);
  const xxl = parseInt(BreakpointXxl.value);
  const result = containerBreakpoint(containerWidth, "xs", void 0, sm) ?? containerBreakpoint(containerWidth, "sm", sm, md) ?? containerBreakpoint(containerWidth, "md", md, lg) ?? containerBreakpoint(containerWidth, "lg", lg, xl) ?? containerBreakpoint(containerWidth, "xl", xl, xxl) ?? containerBreakpoint(containerWidth, "xxl", xxl, void 0);
  return result ? { ...result, containerHeight } : void 0;
};
const useContainerQuery = (containerRef, props) => {
  const [size, setSize] = useState(
    void 0
  );
  useEffect(() => {
    if (!containerRef.current) return;
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        const breakpoint = getContainerBreakpoint(width, height);
        setSize(breakpoint);
      }
    });
    resizeObserver.observe(containerRef.current);
    const rect = containerRef.current.getBoundingClientRect();
    setSize(getContainerBreakpoint(rect.width, rect.height));
    return () => {
      resizeObserver.disconnect();
    };
  }, [containerRef, props?.disable]);
  return size;
};

const OverflowItemContext = createContext({
  isInOverflowMenu: false
});
const useOverFlowItemContext = () => useContext(OverflowItemContext);

const ToolbarContext = createContext({
  overflowItems: [],
  addItem: () => {
    return;
  },
  removeItem: () => {
    return;
  },
  toolbarRef: { current: null },
  orderedIds: [],
  overflow: "wrap",
  size: "xsmall"
});
const useToolbarSize = () => useContext(ToolbarContext).size;

function getToolbarElements(toolbarElement) {
  const toolbarContent = toolbarElement.querySelector(
    '[data-anv="toolbar-content"]'
  );
  const mainItems = getKeyboardFocusableElements(toolbarContent).filter(
    (item) => {
      const isHidden = !item.closest('[aria-hidden="true"]');
      const isInDrawer = !item.closest('[data-anv="filter-group-drawer"]');
      const isInPopover = !item.closest('[data-anv="popover-content"]');
      return isHidden && isInDrawer && isInPopover;
    }
  );
  const overflowTrigger = toolbarElement.querySelector(
    '[data-anv="toolbar-overflow-trigger"]'
  );
  return overflowTrigger ? [...mainItems, overflowTrigger] : mainItems;
}
function updateToolbarItemsTabIndex(toolbarElement, activeItem) {
  if (!toolbarElement) return;
  const items = getToolbarElements(toolbarElement);
  if (!items.length) return;
  let activeIndex = 0;
  if (typeof activeItem === "number") {
    activeIndex = Math.max(0, Math.min(activeItem, items.length - 1));
  } else if (activeItem instanceof Element) {
    const foundIndex = items.indexOf(activeItem);
    if (foundIndex !== -1) {
      activeIndex = foundIndex;
    }
  }
  items.forEach((item, index) => {
    item.setAttribute("tabindex", index === activeIndex ? "0" : "-1");
  });
  return items[activeIndex];
}
function handleToolbarKeyDown(event, toolbarElement) {
  if (!toolbarElement || event.altKey || event.ctrlKey || event.metaKey) return;
  const items = getToolbarElements(toolbarElement);
  if (!items.length) return;
  const activeElement = event.target;
  if (!toolbarElement.contains(activeElement)) return;
  const activeItem = items.find(
    (item) => item === activeElement || Array.from(item.children).some((child) => child === activeElement)
  );
  const activeIndex = activeItem ? items.indexOf(activeItem) : -1;
  if (activeIndex === -1) return;
  let nextIndex = activeIndex;
  const isVertical = toolbarElement.getAttribute("aria-orientation") === "vertical";
  switch (event.key) {
    case "ArrowLeft":
    case "ArrowUp":
      event.preventDefault();
      if (isVertical && event.key === "ArrowUp" || !isVertical && event.key === "ArrowLeft") {
        nextIndex = activeIndex <= 0 ? items.length - 1 : activeIndex - 1;
      }
      break;
    case "ArrowRight":
    case "ArrowDown":
      event.preventDefault();
      if (isVertical && event.key === "ArrowDown" || !isVertical && event.key === "ArrowRight") {
        nextIndex = activeIndex >= items.length - 1 ? 0 : activeIndex + 1;
      }
      break;
    case "Home":
      event.preventDefault();
      nextIndex = 0;
      break;
    case "End":
      event.preventDefault();
      nextIndex = items.length - 1;
      break;
    default:
      return;
  }
  updateToolbarItemsTabIndex(toolbarElement, nextIndex);
  items[nextIndex]?.focus();
}
const handleMenuKeyboardNavigation = (event) => {
  const menuItems = Array.from(
    event.currentTarget.querySelectorAll('[role="menuitem"]')
  ).map((menuItem) => {
    return getKeyboardFocusableElements(menuItem)[0] || menuItem;
  });
  if (!menuItems.length) return;
  const currentIndex = menuItems.indexOf(document.activeElement);
  if (currentIndex === -1) return;
  let nextIndex = currentIndex;
  const isModifierKey = event.altKey || event.ctrlKey || event.metaKey;
  if (isModifierKey) return;
  switch (event.key) {
    case "ArrowDown":
    case "ArrowUp": {
      event.preventDefault();
      const direction = event.key === "ArrowDown" ? 1 : -1;
      nextIndex = (currentIndex + direction + menuItems.length) % menuItems.length;
      break;
    }
    case "Home":
      event.preventDefault();
      nextIndex = 0;
      break;
    case "End":
      event.preventDefault();
      nextIndex = menuItems.length - 1;
      break;
    default:
      return;
  }
  menuItems[nextIndex]?.focus();
};

const toolbar = "_toolbar_t4zws_1";
const styles$3 = {
	toolbar: toolbar,
	"toolbar-item": "_toolbar-item_t4zws_8",
	"toolbar-button-item": "_toolbar-button-item_t4zws_9",
	"toolbar-overflow-trigger": "_toolbar-overflow-trigger_t4zws_10",
	"toolbar-content": "_toolbar-content_t4zws_14",
	"overflow-wrap": "_overflow-wrap_t4zws_20",
	"overflow-collapse": "_overflow-collapse_t4zws_24",
	"toolbar-overflow-content": "_toolbar-overflow-content_t4zws_32",
	"toolbar-button-toggle-item": "_toolbar-button-toggle-item_t4zws_49"
};

const ToolbarItemWrapper = ({
  item,
  children,
  observerRoot,
  onVisibilityChange,
  rootMargin,
  className
}) => {
  const { addItem, removeItem, toolbarRef, overflow } = useContext(ToolbarContext);
  const itemId = useId();
  const elementRef = useRef(null);
  const isCollapseMode = overflow === "collapse";
  const prevIntersectingRef = useRef(true);
  const handleVisibilityChange = useCallback(
    (isVisible) => {
      if (!isCollapseMode || prevIntersectingRef.current === isVisible) return;
      if (onVisibilityChange) {
        onVisibilityChange(isVisible);
      } else if (item) {
        const itemWithId = { ...item, id: itemId };
        if (isVisible) {
          removeItem(itemWithId);
        } else {
          addItem(itemWithId);
        }
      }
      prevIntersectingRef.current = isVisible;
    },
    [isCollapseMode, onVisibilityChange, item, itemId, addItem, removeItem]
  );
  const { isIntersecting, ref } = useIntersectionObserver({
    root: isCollapseMode ? observerRoot ?? toolbarRef.current : null,
    threshold: 1,
    initialIsIntersecting: true,
    // Start as visible
    onChange: handleVisibilityChange,
    rootMargin
  });
  const setRefCallback = useCallback(
    (node) => {
      elementRef.current = node;
      if (isCollapseMode) {
        ref(node);
      }
    },
    [ref, isCollapseMode]
  );
  const handleFocusOrClick = useCallback(() => {
    if (!toolbarRef.current || !elementRef.current) return;
    const currentElement = elementRef.current.querySelector("button, a, input");
    if (!currentElement) return;
    updateToolbarItemsTabIndex(toolbarRef.current, currentElement);
  }, [toolbarRef]);
  useEffect(() => {
    const interactiveEl = elementRef.current?.querySelector("button, a, input");
    if (!interactiveEl) return;
    interactiveEl.addEventListener("focus", handleFocusOrClick);
    interactiveEl.addEventListener("click", handleFocusOrClick);
    return () => {
      interactiveEl.removeEventListener("focus", handleFocusOrClick);
      interactiveEl.removeEventListener("click", handleFocusOrClick);
    };
  }, [handleFocusOrClick]);
  const toolbarItemClassName = cx(styles$3["toolbar-item"], className);
  const isHidden = isCollapseMode && !isIntersecting;
  return /* @__PURE__ */ jsx(
    "div",
    {
      ref: setRefCallback,
      className: toolbarItemClassName,
      style: { visibility: isHidden ? "hidden" : "visible" },
      "aria-hidden": isHidden,
      ...{ inert: isHidden ? "" : void 0 },
      "data-id": itemId,
      "data-anv": "toolbar-item",
      children
    }
  );
};

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$3["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 ToolbarButtonToggle = forwardRef((props, _ref) => {
  const { className, children, isFilter, ...rest } = props;
  const { isInOverflowMenu = false } = useOverFlowItemContext?.() || {};
  const size = useToolbarSize();
  const trackingId = useTrackingId({
    name: "ToolbarButtonToggle",
    data: {
      checked: props.checked,
      disabled: props.disabled,
      "aria-label": props["aria-label"],
      children: props.children
    },
    hasOverride: !!props["data-tracking-id"]
  });
  const buttonToggleClassNames = cx(
    className,
    styles$3["toolbar-button-item"],
    styles$3["toolbar-button-toggle-item"]
  );
  const item = children ? /* @__PURE__ */ jsx(
    ButtonToggle,
    {
      "data-tracking-id": trackingId,
      size,
      "data-anv": "toolbar-button-toggle",
      className: buttonToggleClassNames,
      ...rest,
      children
    }
  ) : /* @__PURE__ */ jsxs(Tooltip, { children: [
    /* @__PURE__ */ jsx(Tooltip.Trigger, { children: /* @__PURE__ */ jsx(
      ButtonToggle,
      {
        "data-tracking-id": trackingId,
        size,
        "data-anv": "toolbar-button-toggle",
        className: buttonToggleClassNames,
        ...rest
      }
    ) }),
    /* @__PURE__ */ jsx(Tooltip.Content, { children: rest["aria-label"] })
  ] });
  if (isInOverflowMenu || isFilter) {
    return item;
  }
  return /* @__PURE__ */ jsx(ToolbarItemWrapper, { item: { itemProps: props, itemType: "buttonToggle" }, children: item });
});
ToolbarButtonToggle.displayName = "ToolbarButtonToggle";

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$3["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$3["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$3["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$3["toolbar-button-item"],
    styles$3["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$3["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 FilterGroupContext = createContext({
  filterGroupRef: { current: null },
  filters: [],
  updateFilter: () => {
  },
  controlledFiltering: false,
  hiddenFilters: [],
  addHiddenFilter: () => {
  },
  removeHiddenFilter: () => {
  }
});

const styles$2 = {
	"filter-button-trigger": "_filter-button-trigger_1192s_1",
	"filter-button-trigger--selected": "_filter-button-trigger--selected_1192s_5",
	"filter-button-content": "_filter-button-content_1192s_14",
	"filter-select-content": "_filter-select-content_1192s_19",
	"filter-button-buttons": "_filter-button-buttons_1192s_25",
	"filter-drawer-trigger": "_filter-drawer-trigger_1192s_29",
	"filter-drawer-trigger--chipped": "_filter-drawer-trigger--chipped_1192s_41",
	"filter-item": "_filter-item_1192s_61",
	"filter-select-search": "_filter-select-search_1192s_66"
};

const FilterItemWrapper = ({
  filter,
  children
}) => {
  const { addHiddenFilter, removeHiddenFilter, filterGroupRef } = useContext(FilterGroupContext);
  const handleVisibilityChange = useCallback(
    (isVisible) => {
      if (filter) {
        if (isVisible) {
          removeHiddenFilter?.(filter);
        } else {
          addHiddenFilter?.(filter);
        }
      }
    },
    [filter, addHiddenFilter, removeHiddenFilter]
  );
  const props = useMemo(
    () => ({
      item: {
        itemType: "button",
        itemProps: {
          children: null,
          "aria-hidden": true
        }
      },
      children,
      className: styles$2["filter-item"],
      observerRoot: filterGroupRef.current,
      onVisibilityChange: handleVisibilityChange,
      rootMargin: "0px -80px 0px 0px"
    }),
    [children, filterGroupRef, handleVisibilityChange]
  );
  return /* @__PURE__ */ jsx(ToolbarItemWrapper, { ...props });
};

const getActiveFilters = (filters) => {
  return filters.filter((filter) => {
    switch (filter.type) {
      case "boolean":
        return filter.checked;
      case "custom":
        return filter.value !== void 0;
      case "singleSelect":
        return filter.selectedItem !== void 0;
      case "multiSelect":
        return filter.selectedItems && filter.selectedItems.length > 0;
      case "date":
        return filter.value !== null && filter.value !== void 0;
      case "dateRange":
        return filter.value !== null && filter.value !== void 0 && filter.value.startDate !== null && filter.value.endDate !== null;
      default:
        return false;
    }
  });
};
const checkActiveFilters = (filters) => {
  return getActiveFilters(filters).length > 0;
};
const resetFilters = (filters) => {
  return filters.map((filter) => {
    switch (filter.type) {
      case "boolean":
        return {
          ...filter,
          checked: false
        };
      case "custom":
        return {
          ...filter,
          value: void 0
        };
      case "singleSelect":
        return {
          ...filter,
          selectedItem: void 0
        };
      case "multiSelect":
        return {
          ...filter,
          selectedItems: []
        };
      case "date":
      case "dateRange":
        return {
          ...filter,
          value: null
        };
      default:
        return filter;
    }
  });
};
const updateSingleFilter = (filters, filterId, value) => {
  return filters.map((filter) => {
    if (filter.id !== filterId) return filter;
    switch (filter.type) {
      case "boolean":
        return {
          ...filter,
          checked: value
        };
      case "singleSelect":
        return {
          ...filter,
          selectedItem: value
        };
      case "multiSelect":
        return {
          ...filter,
          selectedItems: value
        };
      case "date":
        return {
          ...filter,
          value
        };
      case "dateRange":
        return {
          ...filter,
          value
        };
      case "custom":
        return {
          ...filter,
          value
        };
      default:
        return filter;
    }
  });
};
const hasChangedFilter = (a, b) => {
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return true;
    if (a.length === 0) return false;
    const aItems = a;
    const bItems = b;
    if (aItems[0] && "id" in aItems[0]) {
      const aIds = new Set(aItems.map((item) => item.id));
      return bItems.some(
        (item) => !aIds.has(item.id)
      );
    }
    return JSON.stringify(a) !== JSON.stringify(b);
  }
  if (a && b && typeof a === "object" && typeof b === "object" && "id" in a && "id" in b) {
    return a.id !== b.id;
  }
  return a !== b;
};
const getFilterSelectionValue = (filter) => {
  switch (filter.type) {
    case "boolean":
      return filter.checked;
    case "singleSelect":
      return filter.selectedItem;
    case "multiSelect":
      return filter.selectedItems;
    case "date":
    case "dateRange":
    case "custom":
      return filter.value;
    default:
      return void 0;
  }
};
const hasFilterSelectionChanged = (existingFilter, newFilter) => {
  const existingValue = getFilterSelectionValue(existingFilter);
  const newValue = getFilterSelectionValue(newFilter);
  return existingValue !== newValue;
};
const preserveFilterState = (newFilter, existingFilter) => {
  switch (newFilter.type) {
    case "boolean":
      return {
        ...newFilter,
        checked: existingFilter.checked
      };
    case "singleSelect":
      return {
        ...newFilter,
        selectedItem: existingFilter.selectedItem
      };
    case "multiSelect":
      return {
        ...newFilter,
        selectedItems: existingFilter.selectedItems
      };
    case "date":
      return {
        ...newFilter,
        value: existingFilter.value
      };
    case "dateRange":
      return {
        ...newFilter,
        value: existingFilter.value
      };
    case "custom":
      return {
        ...newFilter,
        value: existingFilter.value
      };
    default:
      return newFilter;
  }
};
const cloneFiltersWithItemRefs = (filters) => {
  return filters.map((filter) => {
    switch (filter.type) {
      case "singleSelect":
        return {
          ...filter,
          selectedItem: filter.selectedItem ? filter.items.find(
            (item) => item.id === filter.selectedItem?.id
          ) || filter.selectedItem : void 0
        };
      case "multiSelect":
        return {
          ...filter,
          selectedItems: filter.selectedItems ? filter.selectedItems.map(
            (selectedItem) => filter.items.find((item) => item.id === selectedItem.id) || selectedItem
          ) : []
        };
      case "date":
        return {
          ...filter,
          value: filter.value
        };
      case "dateRange":
        return {
          ...filter,
          value: filter.value
        };
      case "custom": {
        const { value } = filter;
        if (value === void 0) {
          return { ...filter, value: void 0 };
        }
        if (Array.isArray(value)) {
          return { ...filter, value: [...value] };
        }
        if (typeof value === "object" && value !== null) {
          return { ...filter, value: { ...value } };
        }
        return { ...filter, value };
      }
      default:
        return { ...filter };
    }
  });
};

const FilterToggleButton = ({
  id,
  checked,
  children,
  ...props
}) => {
  const filter = {
    id,
    type: "boolean",
    checked,
    label: typeof children === "string" ? children : id
  };
  return /* @__PURE__ */ jsx(FilterItemWrapper, { filter, children: /* @__PURE__ */ jsx(
    ToolbarButtonToggle,
    {
      checked,
      isFilter: true,
      ...props,
      className: styles$2["filter-button-trigger"],
      "data-anv": "toolbar-boolean-filter",
      children
    }
  ) });
};

const FilterSelect = ({
  filter,
  draftValue,
  onDraftChange
}) => {
  const isMultiSelect = filter.type === "multiSelect";
  const listRef = useRef(null);
  const shouldStabilizeItems = isMultiSelect && filter.hasSearch;
  const [stableItems, setStableItems] = useState(filter.items);
  const isSearchActiveRef = useRef(false);
  const expectingSearchUpdate = useRef(false);
  const displayItems = shouldStabilizeItems ? stableItems : filter.items;
  useEffect(() => {
    if (!shouldStabilizeItems) return;
    if (expectingSearchUpdate.current) {
      setStableItems(filter.items);
      expectingSearchUpdate.current = false;
    } else if (!isSearchActiveRef.current) {
      setStableItems(filter.items);
    }
  }, [filter.items, shouldStabilizeItems]);
  const handleSearch = useCallback(
    (e) => {
      const { value } = e.target;
      filter.onSearch?.(value);
      if (shouldStabilizeItems) {
        if (value.length > 0) {
          isSearchActiveRef.current = true;
          expectingSearchUpdate.current = true;
        } else {
          isSearchActiveRef.current = false;
        }
      }
    },
    [filter, shouldStabilizeItems]
  );
  const handleSearchClear = useCallback(() => {
    filter.onSearchClear?.();
    if (shouldStabilizeItems) {
      isSearchActiveRef.current = false;
    }
  }, [filter, shouldStabilizeItems]);
  const handleSearchKeyDown = useCallback(
    (e) => {
      if (e.key === "ArrowDown" && listRef.current) {
        e.preventDefault();
        const focusableElements = tabbable(listRef.current);
        if (focusableElements.length > 0) {
          focusableElements[0].focus();
        }
      }
    },
    []
  );
  const singleSelectList = useMemo(
    () => /* @__PURE__ */ jsx("div", { ref: listRef, children: /* @__PURE__ */ jsx(
      Listbox,
      {
        items: filter.items,
        selected: draftValue,
        onSelectionChange: (selected) => {
          onDraftChange(selected);
        },
        disableAutoSelectOnFocus: true,
        style: { paddingInline: "1rem", paddingBlockStart: "1rem" },
        children: ({ items }) => items.map((item) => /* @__PURE__ */ jsx(
          Listbox.Option,
          {
            item,
            disabled: item.disabled,
            children: item.label
          },
          item.id
        ))
      },
      filter.id
    ) }),
    [filter.id, filter.items, draftValue, onDraftChange]
  );
  const multiSelectList = useMemo(
    () => /* @__PURE__ */ jsx("div", { ref: listRef, children: /* @__PURE__ */ jsx(
      ListView,
      {
        items: displayItems,
        selected: Array.isArray(draftValue) ? draftValue : [],
        onSelectionChange: (selectedItems) => {
          const items = selectedItems;
          onDraftChange(items);
        },
        style: { paddingInline: "1rem", paddingBlockStart: "1rem" },
        children: ({ items }) => items.map((item) => /* @__PURE__ */ jsx(ListView.Option, { item, children: item.label }, item.id))
      },
      filter.id
    ) }),
    [filter.id, displayItems, draftValue, onDraftChange]
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    filter.hasSearch && /* @__PURE__ */ jsx(
      SearchField,
      {
        size: "small",
        className: styles$2["filter-select-search"],
        onChange: handleSearch,
        onClear: handleSearchClear,
        onKeyDown: handleSearchKeyDown,
        "data-anv": "filter-select-search"
      }
    ),
    isMultiSelect ? multiSelectList : singleSelectList
  ] });
};

const FilterDateSingle = ({
  filter,
  draftValue,
  onDraftChange
}) => {
  const maskedDateInputRef = useRef(null);
  const handleChange = (change) => {
    onDraftChange(change.date);
  };
  const { value, onChange } = useDateFieldSingleConversion({
    value: draftValue,
    onChange: handleChange
  });
  const { handleInputChange, handleCalendarSelection } = useDateFieldSingleState({
    valueProp: value,
    onChange: (change) => onChange({ ...change, isDateValid: true })
  });
  return /* @__PURE__ */ jsxs(Flex, { gap: 4, direction: "column", children: [
    /* @__PURE__ */ jsx(
      MaskedDateInput,
      {
        mode: filter.mode,
        ref: maskedDateInputRef,
        onChange: handleInputChange,
        lastValidDate: value ?? null,
        autoComplete: "off"
      }
    ),
    /* @__PURE__ */ jsx(
      DateFieldSingleCalendar,
      {
        value: value ?? null,
        onSelection: handleCalendarSelection
      }
    )
  ] });
};

const FilterDateRange = ({
  filter,
  draftValue,
  onDraftChange
}) => {
  const maskedDateRangeInputRef = useRef(null);
  const handleChange = (change) => {
    const hasCompleteRange = change.startDate && change.endDate;
    const isClearingRange = !change.startDate && !change.endDate;
    if (hasCompleteRange || isClearingRange) {
      onDraftChange({
        startDate: change.startDate,
        endDate: change.endDate
      });
    }
  };
  const { value, onChange } = useDateFieldRangeConversion({
    value: draftValue,
    onChange: handleChange
  });
  const { handleInputChange, handleCalendarSelection } = useDateFieldRangeState(
    {
      valueProp: value,
      onChange: (change) => {
        const hasCompleteRange = change.startDate && change.endDate;
        const isClearingRange = change.isInputEmpty;
        if (change.isInputValid && hasCompleteRange || isClearingRange) {
          onChange({ ...change, isDateRangeValid: true });
        }
      }
    }
  );
  return /* @__PURE__ */ jsxs(Flex, { gap: 4, direction: "column", children: [
    /* @__PURE__ */ jsx(
      MaskedDateRangeInput,
      {
        mode: filter.mode,
        ref: maskedDateRangeInputRef,
        onChange: handleInputChange,
        startDate: value?.startDate ?? null,
        endDate: value?.endDate ?? null,
        autoComplete: "off"
      }
    ),
    /* @__PURE__ */ jsx(
      DateFieldRangeCalendar,
      {
        startDate: value?.startDate ?? null,
        endDate: value?.endDate ?? null,
        onSelection: handleCalendarSelection
      }
    )
  ] });
};

const FilterButton = ({
  filter,
  children,
  className
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const { updateFilter, controlledFiltering } = useContext(FilterGroupContext);
  const toolbarSize = useToolbarSize();
  const [draftValue, setDraftValue] = useState(
    filter.type === "multiSelect" ? [] : void 0
  );
  const draftValueRef = useRef(draftValue);
  useEffect(() => {
    draftValueRef.current = draftValue;
  }, [draftValue]);
  const getCurrentFilterValue = useCallback(() => {
    switch (filter.type) {
      case "singleSelect":
        return filter.selectedItem;
      case "multiSelect":
        return filter.selectedItems || [];
      case "date":
      case "dateRange":
        return filter.value;
      case "custom":
        return filter.value;
      default:
        return void 0;
    }
  }, [filter]);
  const prevIsOpenRef = useRef(isOpen);
  const prevFilterRef = useRef(filter);
  useEffect(() => {
    const justOpened = isOpen && !prevIsOpenRef.current;
    prevIsOpenRef.current = isOpen;
    if (isOpen) {
      const shouldSync = justOpened || prevFilterRef.current && hasFilterSelectionChanged(prevFilterRef.current, filter);
      if (shouldSync) {
        const currentValue = getCurrentFilterValue();
        setDraftValue(currentValue);
      }
      prevFilterRef.current = filter;
    }
  }, [isOpen, filter]);
  const handleChange = useCallback(
    (value) => {
      if (hasChangedFilter(value, draftValueRef.current)) {
        draftValueRef.current = value;
        setDraftValue(value);
        if (!controlledFiltering) {
          updateFilter(filter.id, value, true);
          if (filter.type !== "multiSelect") {
            setIsOpen(false);
          }
        }
      }
    },
    [filter.id, filter.type, controlledFiltering, updateFilter]
  );
  const handleSubmit = useCallback(() => {
    const stateValue = getCurrentFilterValue();
    if (hasChangedFilter(draftValue, stateValue)) {
      updateFilter(filter.id, draftValue, true);
    }
    setIsOpen(false);
  }, [draftValue, getCurrentFilterValue, filter.id, updateFilter]);
  const handleCancel = useCallback(() => {
    if (!controlledFiltering) {
      setIsOpen(false);
      return;
    }
    const originalValue = getCurrentFilterValue();
    setDraftValue(originalValue);
    setIsOpen(false);
  }, [controlledFiltering, getCurrentFilterValue]);
  const getButtonLabel = useMemo(() => {
    switch (filter.type) {
      case "singleSelect": {
        const singleSelectFilter = filter;
        if (singleSelectFilter.selectedItem) {
          return `${filter.label}: ${singleSelectFilter.selectedItem.label}`;
        }
        return filter.label;
      }
      case "multiSelect": {
        const multiSelectFilter = filter;
        if (multiSelectFilter.selectedItems && multiSelectFilter.selectedItems.length > 0) {
          const selectionCount = multiSelectFilter.selectedItems.length.toString();
          return /* @__PURE__ */ jsxs(Fragment, { children: [
            filter.label,
            /* @__PURE__ */ jsx(
              Chip,
              {
                label: selectionCount,
                color: "#0265DC",
                size: "small",
                "aria-label": `${selectionCount} selected items`
              }
            )
          ] });
        }
        return filter.label;
      }
      case "date":
        if (filter.value) {
          const date = DateTime.fromISO(filter.value, { zone: "local" });
          return `${filter.label}: ${date.monthShort} ${date.day}, ${date.year}`;
        }
        return filter.label;
      case "dateRange":
        if (filter.value?.startDate && filter.value?.endDate) {
          const start = DateTime.fromISO(filter.value.startDate, {
            zone: "local"
          });
          const end = DateTime.fromISO(filter.value.endDate, {
            zone: "local"
          });
          const isSameYear = start.year === end.year;
          const formattedStart = isSameYear ? `${start.monthShort} ${start.day}` : `${start.monthShort} ${start.day}, ${start.year}`;
          return `${filter.label}: ${formattedStart} – ${end.monthShort} ${end.day}, ${end.year}`;
        }
        return filter.label;
      case "custom":
        if (filter.labelChipCount) {
          return /* @__PURE__ */ jsxs(Fragment, { children: [
            filter.label,
            /* @__PURE__ */ jsx(
              Chip,
              {
                label: filter.labelChipCount.toString(),
                color: "#0265DC",
                size: "small",
                "aria-label": `${filter.labelChipCount} selected items`
              }
            )
          ] });
        }
        return filter.label;
      default:
        return filter.label;
    }
  }, [filter]);
  const getContent = useMemo(() => {
    switch (filter.type) {
      case "custom":
        return filter.buttonRender({
          value: draftValue,
          onChange: handleChange
        });
      case "singleSelect":
        return /* @__PURE__ */ jsx(
          FilterSelect,
          {
            filter,
            draftValue,
            onDraftChange: handleChange
          }
        );
      case "multiSelect":
        return /* @__PURE__ */ jsx(
          FilterSelect,
          {
            filter,
            draftValue,
            onDraftChange: handleChange
          }
        );
      case "date":
        return /* @__PURE__ */ jsx(
          FilterDateSingle,
          {
            filter,
            draftValue,
            onDraftChange: handleChange
          }
        );
      case "dateRange":
        return /* @__PURE__ */ jsx(
          FilterDateRange,
          {
            filter,
            draftValue,
            onDraftChange: handleChange
          }
        );
      default:
        return children;
    }
  }, [filter, draftValue, handleChange, children]);
  const handleOutsidePress = () => {
    if (controlledFiltering) {
      handleCancel();
    } else if (filter.type === "multiSelect") {
      setIsOpen(false);
    } else {
      handleSubmit();
    }
  };
  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      if (!controlledFiltering && filter.type !== "multiSelect") {
        handleSubmit();
      }
    }
  };
  const triggerClasses = cx(styles$2["filter-button-trigger"], {
    [styles$2["filter-button-trigger--selected"]]: filter.type === "custom" && filter.value || filter.type === "singleSelect" && filter.selectedItem || filter.type === "multiSelect" && filter.selectedItems && filter.selectedItems.length > 0 || filter.type === "date" && filter.value || filter.type === "dateRange" && filter.value?.startDate && filter.value?.endDate
  });
  const contentClasses = cx(styles$2["filter-button-content"], className);
  const iconOptions = filter.type === "date" || filter.type === "dateRange" ? { before: SvgEvent } : { after: SvgKeyboardArrowDown };
  return /* @__PURE__ */ jsx(FilterItemWrapper, { filter, children: /* @__PURE__ */ jsxs(
    Popover,
    {
      open: isOpen,
      onClose: handleOutsidePress,
      placement: "bottom-start",
      modal: true,
      noPadding: filter.type === "multiSelect" || filter.type === "singleSelect",
      children: [
        /* @__PURE__ */ jsx(
          Popover.Button,
          {
            appearance: "ghost",
            size: toolbarSize,
            icon: iconOptions,
            "data-id": filter.id,
            "data-anv": "toolbar-button",
            className: triggerClasses,
            onClick: () => {
              setIsOpen(!isOpen);
            },
            children: getButtonLabel
          }
        ),
        /* @__PURE__ */ jsxs(Popover.Content, { onKeyDown: handleKeyDown, className: contentClasses, children: [
          getContent,
          controlledFiltering && /* @__PURE__ */ jsxs(
            Flex,
            {
              gap: 2,
              justifyContent: "flex-end",
              className: styles$2["filter-button-buttons"],
              children: [
                /* @__PURE__ */ jsx(Popover.Close, { size: "small", children: "Cancel" }),
                /* @__PURE__ */ jsx(Button, { appearance: "primary", size: "small", onClick: handleSubmit, children: "Apply" })
              ]
            }
          )
        ] })
      ]
    }
  ) });
};

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 SvgTune = (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: "M3 18c0 .55.45 1 1 1h5v-2H4c-.55 0-1 .45-1 1zM3 6c0 .55.45 1 1 1h9V5H4c-.55 0-1 .45-1 1zm10 14v-1h7c.55 0 1-.45 1-1s-.45-1-1-1h-7v-1c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1s1-.45 1-1zM7 10v1H4c-.55 0-1 .45-1 1s.45 1 1 1h3v1c0 .55.45 1 1 1s1-.45 1-1v-4c0-.55-.45-1-1-1s-1 .45-1 1zm14 2c0-.55-.45-1-1-1h-9v2h9c.55 0 1-.45 1-1zm-5-3c.55 0 1-.45 1-1V7h3c.55 0 1-.45 1-1s-.45-1-1-1h-3V4c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1z" }));

const FilterDrawer = () => {
  const [open, setOpen] = useState(false);
  const {
    filters,
    updateFilter,
    onFilterChange,
    hiddenFilters,
    filterGroupRef
  } = useContext(FilterGroupContext);
  const toolbarSize = useToolbarSize();
  const containerQuery = useContainerQuery(filterGroupRef);
  const showInlineFilters = containerQuery && containerQuery.name !== "xs" && containerQuery.name !== "sm";
  const [draftFilters, setDraftFilters] = useState(filters);
  const [searchValues, setSearchValues] = useState({});
  const activeFiltersCount = getActiveFilters(
    !showInlineFilters ? filters : hiddenFilters
  ).length;
  const prevOpenRef = useRef(open);
  const prevFiltersRef = useRef(filters);
  useEffect(() => {
    const justOpened = open && !prevOpenRef.current;
    prevOpenRef.current = open;
    if (open) {
      const anySelectionChanged = prevFiltersRef.current.some(
        (prevFilter, index) => {
          const newFilter = filters[index];
          return newFilter && hasFilterSelectionChanged(prevFilter, newFilter);
        }
      );
      const shouldSync = justOpened || anySelectionChanged;
      if (shouldSync) {
        setDraftFilters(cloneFiltersWithItemRefs(filters));
      }
      prevFiltersRef.current = filters;
    }
  }, [open, filters]);
  const handleDraftChange = useCallback(
    (filterId, value) => {
      setDraftFilters((draft) => updateSingleFilter(draft, filterId, value));
      const filter = filters.find((f) => f.id === filterId);
      if ((filter?.type === "singleSelect" || filter?.type === "multiSelect") && filter.hasSearch && value) {
        setSearchValues((prev) => ({ ...prev, [filterId]: "" }));
        requestAnimationFrame(() => {
          filter.onSearch?.("");
        });
      }
    },
    [filters]
  );
  const clearDraftFilters = () => {
    setDraftFilters(resetFilters(draftFilters));
  };
  const hasActiveDraftFilters = checkActiveFilters(draftFilters);
  const filterForm = useMemo(
    () => draftFilters.map((draftFilter) => {
      const originalFilter = filters.find((f) => f.id === draftFilter.id);
      if (!originalFilter) return null;
      switch (draftFilter.type) {
        case "boolean":
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              label: draftFilter.label,
              checked: draftFilter.checked,
              onChange: (e) => handleDraftChange(draftFilter.id, e?.target.checked ?? false)
            },
            draftFilter.id
          );
        case "custom": {
          const customFilter = originalFilter;
          return /* @__PURE__ */ jsx("div", { children: customFilter.drawerRender?.({
            value: draftFilter.value,
            onChange: (value) => handleDraftChange(draftFilter.id, value)
          }) }, draftFilter.id);
        }
        case "singleSelect": {
          const singleSelectFilter = originalFilter;
          const draftSingleSelectFilter = draftFilter;
          if (singleSelectFilter.simpleDrawerVariant) {
            return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Radio.Group, { legend: singleSelectFilter.label, children: singleSelectFilter.items.map((item) => /* @__PURE__ */ jsx(
              Radio,
              {
                name: `${singleSelectFilter.id}-radio`,
                value: item.id,
                label: item.label,
                checked: draftSingleSelectFilter.selectedItem?.id === item.id,
                onChange: (e) => {
                  if (e?.target.checked) {
                    const selected = singleSelectFilter.items.find(
                      (opt) => opt.id === e.target.value
                    );
                    handleDraftChange(draftFilter.id, selected);
                  }
                }
              },
              item.id
            )) }) }, draftFilter.id);
          } else {
            const selectedItem = draftSingleSelectFilter.selectedItem ? singleSelectFilter.items?.find(
              (item) => item.id === draftSingleSelectFilter.selectedItem?.id
            ) ?? null : null;
            return /* @__PURE__ */ jsxs(
              Combobox,
              {
                items: singleSelectFilter.items,
                selectedItem,
                onChange: (selectedItem2) => {
                  handleDraftChange(draftFilter.id, selectedItem2);
                },
                itemToString: (item) => item?.label ?? "",
                disableFilter: singleSelectFilter.hasSearch,
                children: [
                  singleSelectFilter.hasSearch ? /* @__PURE__ */ jsx(
                    Combobox.SearchField,
                    {
                      label: draftSingleSelectFilter.label,
                      prefix: { icon: { svg: SvgSearch } },
                      placeholder: "Search...",
                      size: "small",
                      value: draftSingleSelectFilter.selectedItem?.label || searchValues[draftFilter.id] || "",
                      onChange: (e) => {
                        const searchValue = e.target.value;
                        setSearchValues((prev) => ({
                          ...prev,
                          [draftFilter.id]: searchValue
                        }));
                        singleSelectFilter.onSearch?.(searchValue);
                      },
                      onClear: () => {
                        setSearchValues((prev) => ({
                          ...prev,
                          [draftFilter.id]: ""
                        }));
                        handleDraftChange(draftFilter.id, void 0);
                        singleSelectFilter.onSearchClear?.();
                      },
                      "data-anv": "filter-drawer-combobox-search"
                    }
                  ) : /* @__PURE__ */ jsx(
                    Combobox.SelectTrigger,
                    {
                      label: singleSelectFilter.label,
                      placeholder: "Select an option...",
                      size: "small"
                    }
                  ),
                  /* @__PURE__ */ jsx(Combobox.Content, { children: ({ items }) => /* @__PURE__ */ jsx(Combobox.List, { style: { padding: 0 }, children: items.map((item, i) => /* @__PURE__ */ jsx(Combobox.Item, { item, index: i, children: item.label }, item.id)) }) })
                ]
              },
              draftFilter.id
            );
          }
        }
        case "multiSelect": {
          const multiSelectFilter = originalFilter;
          const draftMultiSelectFilter = draftFilter;
          if (multiSelectFilter.simpleDrawerVariant) {
            return /* @__PURE__ */ jsx(
              Checkbox.Group,
              {
                legend: multiSelectFilter.label,
                children: multiSelectFilter.items.map((item) => /* @__PURE__ */ jsx(
                  Checkbox,
                  {
                    label: item.label,
                    checked: draftMultiSelectFilter.selectedItems?.some(
                      (selected) => selected.id === item.id
                    ) ?? false,
                    onChange: (e) => {
                      const currentSelected = draftMultiSelectFilter.selectedItems || [];
                      if (e?.target.checked) {
                        handleDraftChange(draftFilter.id, [
                          ...currentSelected,
                          item
                        ]);
                      } else {
                        handleDraftChange(
                          draftFilter.id,
                          currentSelected.filter(
                            (selected) => selected.id !== item.id
                          )
                        );
                      }
                    }
                  },
                  item.id
                ))
              },
              draftFilter.id
            );
          } else {
            const hasActiveSearch = searchValues[draftFilter.id] && searchValues[draftFilter.id].length > 0;
            return /* @__PURE__ */ jsxs(
              Combobox,
              {
                items: multiSelectFilter.items,
                selectedItems: draftMultiSelectFilter.selectedItems || [],
                onChange: (selectedItems) => handleDraftChange(draftFilter.id, selectedItems),
                itemToString: (item) => item?.label ?? "",
                itemToKey: (item) => item?.id ?? "",
                disableFilter: multiSelectFilter.hasSearch,
                multiple: true,
                disableCloseOnSelectItem: !hasActiveSearch,
                children: [
                  multiSelectFilter.hasSearch ? /* @__PURE__ */ jsx(
                    Combobox.SearchField,
                    {
                      label: multiSelectFilter.label,
                      prefix: { icon: { svg: SvgSearch } },
                      placeholder: "Search...",
                      size: "small",
                      value: searchValues[draftFilter.id] || "",
                      onChange: (e) => {
                        const searchValue = e.target.value;
                        setSearchValues((prev) => ({
                          ...prev,
                          [draftFilter.id]: searchValue
                        }));
                        multiSelectFilter.onSearch?.(searchValue);
                      },
                      onClear: () => {
                        setSearchValues((prev) => ({
                          ...prev,
                          [draftFilter.id]: ""
                        }));
                        handleDraftChange(draftFilter.id, []);
                        multiSelectFilter.onSearchClear?.();
                      },
                      "data-anv": "filter-drawer-combobox-search"
                    }
                  ) : /* @__PURE__ */ jsx(
                    Combobox.SelectTrigger,
                    {
                      label: multiSelectFilter.label,
                      placeholder: "Select options...",
                      size: "small"
                    }
                  ),
                  /* @__PURE__ */ jsx(Combobox.Content, { children: ({ items }) => /* @__PURE__ */ jsx(Combobox.List, { style: { padding: 0 }, children: items.map((item, i) => /* @__PURE__ */ jsx(Combobox.Item, { item, index: i, children: item.label }, item.id)) }) })
                ]
              },
              draftFilter.id
            );
          }
        }
        case "date": {
          return /* @__PURE__ */ jsx(
            DateFieldSingle,
            {
              label: draftFilter.label,
              value: draftFilter.value,
              onChange: (change) => {
                handleDraftChange(draftFilter.id, change.date);
              },
              mode: draftFilter.mode
            },
            draftFilter.id
          );
        }
        case "dateRange": {
          return /* @__PURE__ */ jsx(
            DateFieldRange,
            {
              label: draftFilter.label,
              value: draftFilter.value,
              onChange: (change) => {
                handleDraftChange(draftFilter.id, {
                  startDate: change.startDate,
                  endDate: change.endDate
                });
              },
              mode: draftFilter.mode
            },
            draftFilter.id
          );
        }
        default:
          return null;
      }
    }),
    [draftFilters, filters, searchValues, handleDraftChange]
  );
  const applyFiltering = () => {
    draftFilters.forEach((draftFilter) => {
      switch (draftFilter.type) {
        case "boolean":
          updateFilter(draftFilter.id, draftFilter.checked, false);
          break;
        case "singleSelect":
          updateFilter(
            draftFilter.id,
            draftFilter.selectedItem,
            false
          );
          break;
        case "multiSelect":
          updateFilter(
            draftFilter.id,
            draftFilter.selectedItems,
            false
          );
          break;
        case "date":
        case "dateRange":
        case "custom":
          updateFilter(draftFilter.id, draftFilter.value, false);
          break;
      }
    });
    onFilterChange?.(draftFilters);
    setOpen(false);
  };
  const handleCancel = () => {
    setOpen(false);
  };
  const hasHiddenActiveFilters = activeFiltersCount > 0;
  const triggerClasses = cx(
    styles$2["filter-button-trigger"],
    styles$2["filter-drawer-trigger"],
    {
      [styles$2["filter-drawer-trigger--chipped"]]: hasHiddenActiveFilters
    }
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      ButtonToggle,
      {
        "data-anv": "filter-group-drawer-trigger",
        icon: { before: SvgTune },
        onClick: () => setOpen(true),
        className: triggerClasses,
        checked: open,
        size: toolbarSize,
        children: [
          "Filters",
          hasHiddenActiveFilters && /* @__PURE__ */ jsx(
            Chip,
            {
              size: "small",
              color: "#0265DC",
              label: activeFiltersCount.toString()
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      Drawer,
      {
        "data-anv": "filter-group-drawer",
        "data-testid": "filter-group-drawer",
        open,
        onClose: () => setOpen(false),
        children: [
          /* @__PURE__ */ jsx(Drawer.Content, { children: /* @__PURE__ */ jsx(Flex, { direction: "column", gap: 6, grow: 1, children: filterForm }) }),
          /* @__PURE__ */ jsx(Drawer.Footer, { children: /* @__PURE__ */ jsxs(
            Flex,
            {
              justifyContent: hasActiveDraftFilters ? "space-between" : "flex-end",
              grow: 1,
              children: [
                hasActiveDraftFilters && /* @__PURE__ */ jsx(
                  Button,
                  {
                    appearance: "ghost",
                    icon: { before: SvgClose },
                    onClick: clearDraftFilters,
                    children: "Clear All Filters"
                  }
                ),
                /* @__PURE__ */ jsxs(Flex, { gap: "3", children: [
                  /* @__PURE__ */ jsx(Button, { onClick: handleCancel, children: "Cancel" }),
                  /* @__PURE__ */ jsx(Button, { appearance: "primary", onClick: applyFiltering, children: "Apply" })
                ] })
              ]
            }
          ) })
        ]
      }
    )
  ] });
};

const FilterGroupElement = forwardRef(
  (props, ref) => {
    const {
      filters: initialFilters,
      onFilterChange,
      controlledFiltering = false,
      ...rest
    } = props;
    const [filters, setFilters] = useState(initialFilters);
    const [hiddenFilters, setHiddenFilters] = useState([]);
    const filterGroupRef = useRef(null);
    const containerQuery = useContainerQuery(filterGroupRef);
    const toolbarSize = useToolbarSize();
    const showInlineFilters = containerQuery && containerQuery.name !== "xs" && containerQuery.name !== "sm";
    useEffect(() => {
      setFilters((prevFilters) => {
        const existingFiltersMap = new Map(prevFilters.map((f) => [f.id, f]));
        return initialFilters.map((newFilter) => {
          const existingFilter = existingFiltersMap.get(newFilter.id);
          if (!existingFilter) {
            return newFilter;
          }
          if (!hasFilterSelectionChanged(existingFilter, newFilter)) {
            return preserveFilterState(newFilter, existingFilter);
          }
          return newFilter;
        });
      });
    }, [initialFilters]);
    const updateFilter = useCallback(
      (filterId, value2, submit) => {
        setFilters((prevFilters) => {
          const updatedFilters = updateSingleFilter(
            prevFilters,
            filterId,
            value2
          );
          if (submit) {
            onFilterChange?.(updatedFilters);
          }
          return updatedFilters;
        });
      },
      [onFilterChange]
    );
    const addHiddenFilter = useCallback((filter) => {
      setHiddenFilters((prev) => [...prev, filter]);
    }, []);
    const removeHiddenFilter = useCallback((filter) => {
      setHiddenFilters((prev) => prev.filter((f) => f.id !== filter.id));
    }, []);
    const clearAllFilters = () => {
      const resetAllFilters = resetFilters(filters);
      setFilters(resetAllFilters);
      onFilterChange?.(resetAllFilters);
      setTimeout(() => {
        if (filterGroupRef.current) {
          const firstFocusable = filterGroupRef.current.querySelector(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
          );
          if (firstFocusable) {
            firstFocusable.focus();
          }
        }
      }, 0);
    };
    const hasActiveFilters = checkActiveFilters(filters);
    const filterGroupControls = filters.map((filter) => {
      switch (filter.type) {
        case "boolean":
          return /* @__PURE__ */ jsx(
            FilterToggleButton,
            {
              id: filter.id,
              checked: filter.checked,
              onClick: () => {
                updateFilter(filter.id, !filter.checked, true);
              },
              children: filter.label
            },
            filter.id
          );
        case "singleSelect":
        case "multiSelect":
          return /* @__PURE__ */ jsx(
            FilterButton,
            {
              filter,
              className: styles$2["filter-select-content"]
            },
            filter.id
          );
        case "custom":
        case "date":
        case "dateRange":
          return /* @__PURE__ */ jsx(FilterButton, { filter }, filter.id);
        // TODO: Add cases for other filter types here as needed
        default:
          return null;
      }
    });
    const value = useMemo(
      () => ({
        filterGroupRef,
        filters,
        updateFilter,
        onFilterChange,
        controlledFiltering,
        hiddenFilters,
        addHiddenFilter,
        removeHiddenFilter
      }),
      [
        filterGroupRef,
        filters,
        updateFilter,
        onFilterChange,
        controlledFiltering,
        hiddenFilters,
        addHiddenFilter,
        removeHiddenFilter
      ]
    );
    return /* @__PURE__ */ jsx(FilterGroupContext.Provider, { value, children: /* @__PURE__ */ jsxs(
      ToolbarControlGroup,
      {
        ref: useMergeRefs([filterGroupRef, ref]),
        "data-anv": "toolbar-filter-group",
        "aria-label": "Filter controls",
        ...rest,
        children: [
          showInlineFilters && filterGroupControls,
          /* @__PURE__ */ jsx(FilterDrawer, {}),
          showInlineFilters && hasActiveFilters && /* @__PURE__ */ jsx(FilterItemWrapper, { children: /* @__PURE__ */ jsx(
            Button,
            {
              appearance: "ghost",
              size: toolbarSize,
              className: styles$2["filter-button-trigger"],
              icon: {
                before: SvgClose
              },
              onClick: clearAllFilters,
              children: "Clear Filters"
            }
          ) })
        ]
      }
    ) });
  }
);
FilterGroupElement.displayName = "FilterGroup";
const FilterGroup = FilterGroupElement;

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$1,
      {
        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$3["toolbar"], className);
    const toolbarContentClassNames = cx(styles$3["toolbar-content"], {
      [styles$3[`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.`,
        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,
    /**
     * FilterGroup component displays a group of filters with toggles and a clear button.
     * Also contains the FilterDrawer for additional filter options.
     *
     * Features:
     * - Renders filter toggles and popovers for all filter types
     * - Supports controlled and uncontrolled filtering
     * - Integrates with FilterDrawer for batch filter editing
     * - Provides a clear all filters button
     * - Handles overflow and hidden filters
     * - Shares filter state via context for child components
     * - Supports boolean, custom, single-select, multi-select, date, and date range filter types
     * - Date filters include calendar popup for easy selection
     * - Date range filters support start and end date selection
     *
     * @example
     * <Toolbar.Filters
     *   filters={filters}
     *   onFilterChange={handleFilter}
     *   controlledFiltering={true}
     * />
     */
    Filters: FilterGroup,
    /**
     * 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, ToolbarButtonToggle as b, ToolbarButtonLink as c, ToolbarSelect as d, ToolbarControlGroup as e, ToolbarSearchField as f, ToolbarElement as g };
//# sourceMappingURL=Toolbar-C1_etxss.js.map
