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

import classNames from 'classnames';
import { useRef } from 'react';
import { CLS_PREFIX } from '../../constants';
import ResponsiveContext from '../ResponsiveContext';
import Squeezer from '../Squeezer';
import DropdownControl from './DropdownControl';
import ButtonGroupControl from './ButtonGroupControl';
import { useResponsive } from './useResponsive';
import { useSelected } from './useSelected';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export const SEGMENTED_CONTROL_BASE_CLASS_NAME = `${CLS_PREFIX}segmented-control`;

/**
 * `Segmented Control` is a group of several [Buttons](#!/Button)
 * each of which functions as a mutually exclusive option.
 * @since 0.0.68
 */
const SegmentedControl = _ref => {
  let {
    label,
    labelPlacement = 'top',
    buttons,
    monospaced = false,
    multiple = false,
    selected: externalSelected,
    onChange,
    inline = false,
    ghost = false,
    className,
    baseClassName = SEGMENTED_CONTROL_BASE_CLASS_NAME,
    ...props
  } = _ref;
  const rootRef = useRef(null);
  const {
    isResponsive,
    isInResponsiveContext,
    ...squeezerProps
  } = useResponsive();
  const {
    selectedValues,
    handleChange
  } = useSelected({
    multiple,
    externalSelected,
    onChange
  });
  const renderControl = () => {
    const hasIcons = buttons.some(_ref2 => {
      let {
        icon
      } = _ref2;
      return !!icon;
    });
    if (!hasIcons && !multiple && isResponsive) {
      return /*#__PURE__*/_jsx(DropdownControl, {
        buttons: buttons,
        selected: selectedValues[0],
        onClick: handleChange
      });
    }
    return /*#__PURE__*/_jsx(ResponsiveContext.Provider, {
      value: isResponsive,
      children: /*#__PURE__*/_jsx(ButtonGroupControl, {
        buttons: buttons,
        selectedValues: selectedValues,
        onClick: handleChange,
        ghost: ghost,
        isResponsive: isResponsive,
        monospaced: monospaced,
        baseClassName: baseClassName
      })
    });
  };
  return /*#__PURE__*/_jsxs("div", {
    ref: rootRef,
    className: classNames(baseClassName, {
      [`${baseClassName}--inline`]: inline,
      [`${baseClassName}--collapsed`]: isResponsive,
      [`${baseClassName}--vertical`]: label && labelPlacement === 'top'
    }, className),
    ...props,
    children: [label && /*#__PURE__*/_jsx("div", {
      className: `${baseClassName}__label`,
      children: label
    }), renderControl(), !isInResponsiveContext && /*#__PURE__*/_jsx(Squeezer, {
      ref: rootRef,
      ...squeezerProps
    })]
  });
};
export default SegmentedControl;