// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { useRef } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import Button from '../Button';
import ButtonGroup from '../ButtonGroup';
import Dropdown from '../Dropdown';
import { wrapFunction, createFocusManager } from '../utils';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const focusStrategy = {
  getNext(container, element) {
    const elements = container.children;
    const index = Array.prototype.indexOf.call(elements, element);
    if (index === 0) {
      return elements[1].firstElementChild;
    }
    return undefined;
  },
  getPrev(container, element) {
    if (element === container.children[1].querySelector('button')) {
      return container.children[0];
    }
    return undefined;
  },
  getFirst(container) {
    return container.children[0];
  },
  getLast(container) {
    return container.children[1].querySelector('button');
  }
};
/**
 * `Split Button` is a combination of a standard [Button](#!/Button) with a [Dropdown](#!/Dropdown) menu.
 * It is used for grouping several related actions when one of the actions should be accessible immediately
 * because it is used more often than others.
 * @since 0.0.40
 */
const SplitButton = _ref => {
  let {
    baseClassName = `${CLS_PREFIX}split-button`,
    className,
    menu,
    children,
    onClick,
    onKeyDown,
    icon,
    size,
    ...props
  } = _ref;
  const rootRef = useRef(null);
  const {
    focusNext,
    focusPrev
  } = createFocusManager(rootRef, undefined, focusStrategy);
  const handleKeyDown = wrapFunction(onKeyDown, e => {
    e.stopPropagation();
    switch (e.key) {
      case 'ArrowLeft':
        e.preventDefault();
        focusPrev();
        break;
      case 'ArrowRight':
        e.preventDefault();
        focusNext();
        break;
    }
  });
  return /*#__PURE__*/_jsxs(ButtonGroup, {
    className: classNames(baseClassName, className),
    innerRef: rootRef,
    onKeyDown: handleKeyDown,
    ...props,
    children: [/*#__PURE__*/_jsx(Button, {
      icon: icon,
      size: size,
      tabIndex: 0,
      onClick: onClick,
      children: children
    }), /*#__PURE__*/_jsx(Dropdown, {
      className: `${baseClassName}__dropdown-trigger`,
      menu: menu,
      menuPlacement: "bottom-end",
      children: /*#__PURE__*/_jsx(Button, {
        size: size,
        caret: true,
        tabIndex: -1
      })
    })]
  });
};
export default SplitButton;