import { jsx, jsxs } from 'react/jsx-runtime';
import { createContext, useContext, useId, useRef, useCallback, useEffect, forwardRef } from 'react';
import { B as ButtonToggle } from './ButtonToggle-DBGc7dIn.js';
import { T as Tooltip } from './Tooltip-BC8lnFhe.js';
import { g as getKeyboardFocusableElements } from './getKeyboardFocusableElements-B_U9rt6y.js';
import { c as cx } from './index-De1g9FRV.js';
import { u as useIntersectionObserver } from './useIntersectionObserver-BEmMDO3P.js';
import { useTrackingId } from './useTrackingId.js';

import './ToolbarButtonToggle.css';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"]');
      const isInDialog = !item.closest("dialog");
      const isNotInMenuContent = !item.closest('[data-anv="menu-content"]');
      const isNotSearchField = !item.closest(
        '[data-anv="filter-search-field"]'
      );
      return isHidden && isInDrawer && isInPopover && isInDialog && isNotInMenuContent && isNotSearchField;
    }
  );
  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 = {
	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["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 OverflowItemContext = createContext({
  isInOverflowMenu: false
});
const useOverFlowItemContext = () => useContext(OverflowItemContext);

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["toolbar-button-item"],
    styles["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";

export { OverflowItemContext as O, ToolbarButtonToggle as T, updateToolbarItemsTabIndex as a, ToolbarContext as b, useOverFlowItemContext as c, ToolbarItemWrapper as d, handleMenuKeyboardNavigation as e, getToolbarElements as g, handleToolbarKeyDown as h, styles as s, useToolbarSize as u };
//# sourceMappingURL=ToolbarButtonToggle-3xbnm1Qr.js.map
