// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

import { Children, useContext, isValidElement, useState } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import Dropdown from '../Dropdown';
import ToolbarMenu from './ToolbarMenu';
import RegistryContext, { useRegistry, useRegistryItem } from './RegistryContext';
import DistractionFreeModeContext from '../DistractionFreeModeContext';
import { toToolbarItems } from './ToolbarItem';
import ToolbarExpander from './ToolbarExpander';
import { jsx as _jsx } from "react/jsx-runtime";
/**
 * `ToolbarGroup` is a part of [Toolbar](#!/Toolbar) component.
 * It is used for grouping several toolbar controls together.
 * @since 0.0.57
 */
const ToolbarGroup = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}toolbar__group`,
    className,
    title,
    children,
    groupable = true,
    ...props
  } = _ref;
  const [compact] = useRegistryItem();
  const registry = useRegistry();
  const [availableInDistractionFreeMode, setAvailableInDistractionFreeMode] = useState(false);
  const distractionFreeMode = useContext(DistractionFreeModeContext);
  const distractionFreeModeContextValue = {
    enabled: distractionFreeMode?.enabled ?? false,
    toggle: () => {
      if (distractionFreeMode) {
        distractionFreeMode.toggle();
        setAvailableInDistractionFreeMode(current => !current);
      }
    }
  };
  let hasExpander = Children.toArray(children).some(child => /*#__PURE__*/isValidElement(child) && child.type === ToolbarExpander);
  if (groupable && compact && Children.count(children) > 1) {
    hasExpander = false;
    children = /*#__PURE__*/_jsx(Dropdown, {
      menu: /*#__PURE__*/_jsx(ToolbarMenu, {
        onItemClick: () => {},
        children: children
      }),
      children: title
    });
  } else {
    children = /*#__PURE__*/_jsx(RegistryContext.Provider, {
      value: registry,
      children: /*#__PURE__*/_jsx(DistractionFreeModeContext.Provider, {
        value: distractionFreeModeContextValue,
        children: toToolbarItems(children)
      })
    });
  }
  if (distractionFreeModeContextValue.enabled && !availableInDistractionFreeMode) {
    return null;
  }
  return /*#__PURE__*/_jsx("div", {
    className: classNames(baseClassName, className, {
      [`${baseClassName}--grow`]: hasExpander || distractionFreeModeContextValue.enabled && availableInDistractionFreeMode
    }),
    ...props,
    children: children
  });
};
export default ToolbarGroup;