import { objectWithoutProperties as _objectWithoutProperties, slicedToArray as _slicedToArray, extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useMemo, useRef } from 'react';
import { ListWrapper, Ul, StyledEmptyState, base } from './Select.styles.js';
import { classes } from './Select.tokens.js';
import { FloatingPopover } from './FloatingPopover.js';
import { SelectNative } from './ui/SelectNative/SelectNative.js';
import { Context } from './Select.context.js';
import { initialItemsTransform } from './utils/initialItemsTransform.js';
import { usePathMaps } from './hooks/usePathMaps.js';
import { safeUseId } from '../../utils/react.js';
import { useValue } from './hooks/useValue.js';
import { useListState } from './hooks/useListState.js';
import { getItemByFocused } from './utils/getItemByFocused.js';
import { useCheckedState } from './hooks/useCheckedState.js';
import { useKeyNavigation } from './hooks/useKeyboardNavigation.js';
import { useOutsideClick } from '../../hooks/useOutsideClick.js';
import { Target } from './ui/Target/Target.js';
import { TreeList } from './ui/TreeList/TreeList.js';
import { SelectAll } from './ui/SelectAll/SelectAll.js';
import { isEmpty } from '../../utils/isEmpty.js';
import { VirtualList } from './ui/VirtualList/VirtualList.js';
import { Inner } from './ui/Inner/Inner.js';
import { hasOuterValue } from './utils/hasOuterValue.js';

var _excluded = ["size", "view", "chipView", "hintSize", "hintView", "target", "contentLeft", "contentRight", "placeholder", "helperText", "chipType", "chipClickArea", "required", "requiredPlacement", "optional", "optionalText", "hasRequiredIndicator", "hintText", "hintTrigger", "hintTargetIcon", "hintTargetPlacement", "hintPlacement", "hintHasArrow", "hintOffset", "hintWidth", "hintContentLeft", "label", "labelPlacement", "keepPlaceholder", "multiselect", "value", "onChange", "isTargetAmount", "renderTarget", "selectAllOptions", "name", "defaultValue", "_offset", "_checkboxAppearance", "items", "treeView", "arrowPlacement", "placement", "disabled", "readOnly", "variant", "zIndex", "listMaxHeight", "listWidth", "portal", "renderValue", "renderItem", "renderSelectionIcon", "closeAfterSelect", "beforeList", "afterList", "virtual", "onScroll", "onToggle", "mode", "flip", "shift", "singleLine", "emptyStateDescription"];

/**
 * Выпадающий список. Поддерживает выбор одного или нескольких значений.
 */
var selectRoot = function selectRoot(Root) {
  return /*#__PURE__*/forwardRef(function (props, ref) {
    var _getItemByFocused;
    var size = props.size,
      view = props.view,
      chipView = props.chipView,
      hintSize = props.hintSize,
      hintView = props.hintView,
      _props$target = props.target,
      _target = _props$target === void 0 ? 'textfield-like' : _props$target,
      contentLeft = props.contentLeft,
      contentRight = props.contentRight,
      placeholder = props.placeholder,
      helperText = props.helperText,
      _props$chipType = props.chipType,
      chipType = _props$chipType === void 0 ? 'default' : _props$chipType,
      _props$chipClickArea = props.chipClickArea,
      chipClickArea = _props$chipClickArea === void 0 ? 'full' : _props$chipClickArea,
      required = props.required,
      _props$requiredPlacem = props.requiredPlacement,
      requiredPlacement = _props$requiredPlacem === void 0 ? 'right' : _props$requiredPlacem,
      optional = props.optional,
      optionalText = props.optionalText,
      _props$hasRequiredInd = props.hasRequiredIndicator,
      hasRequiredIndicator = _props$hasRequiredInd === void 0 ? false : _props$hasRequiredInd,
      hintText = props.hintText,
      hintTrigger = props.hintTrigger,
      hintTargetIcon = props.hintTargetIcon,
      _props$hintTargetPlac = props.hintTargetPlacement,
      hintTargetPlacement = _props$hintTargetPlac === void 0 ? 'outer' : _props$hintTargetPlac,
      hintPlacement = props.hintPlacement,
      hintHasArrow = props.hintHasArrow,
      _props$hintOffset = props.hintOffset,
      hintOffset = _props$hintOffset === void 0 ? [0, 8] : _props$hintOffset,
      hintWidth = props.hintWidth,
      hintContentLeft = props.hintContentLeft,
      label = props.label,
      labelPlacement = props.labelPlacement,
      keepPlaceholder = props.keepPlaceholder,
      multiselect = props.multiselect,
      outerValue = props.value,
      outerOnChange = props.onChange,
      isTargetAmount = props.isTargetAmount,
      renderTarget = props.renderTarget,
      selectAllOptions = props.selectAllOptions,
      name = props.name,
      defaultValue = props.defaultValue,
      _offset = props._offset,
      _checkboxAppearance = props._checkboxAppearance,
      items = props.items,
      _props$treeView = props.treeView,
      treeView = _props$treeView === void 0 ? false : _props$treeView,
      _props$arrowPlacement = props.arrowPlacement,
      arrowPlacement = _props$arrowPlacement === void 0 ? 'left' : _props$arrowPlacement,
      _props$placement = props.placement,
      placement = _props$placement === void 0 ? 'bottom' : _props$placement,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$readOnly = props.readOnly,
      readOnly = _props$readOnly === void 0 ? false : _props$readOnly,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'normal' : _props$variant,
      zIndex = props.zIndex,
      listMaxHeight = props.listMaxHeight,
      listWidth = props.listWidth,
      portal = props.portal,
      renderValue = props.renderValue,
      renderItem = props.renderItem,
      renderSelectionIcon = props.renderSelectionIcon,
      outerCloseAfterSelect = props.closeAfterSelect,
      beforeList = props.beforeList,
      afterList = props.afterList,
      _props$virtual = props.virtual,
      virtual = _props$virtual === void 0 ? false : _props$virtual,
      onScroll = props.onScroll,
      onToggle = props.onToggle,
      _props$mode = props.mode,
      mode = _props$mode === void 0 ? 'default' : _props$mode,
      flip = props.flip,
      shift = props.shift,
      singleLine = props.singleLine,
      emptyStateDescription = props.emptyStateDescription,
      rest = _objectWithoutProperties(props, _excluded);

    // Deep copy массива items с добавлением parent-ноды родителя.
    var transformedItems = useMemo(function () {
      return initialItemsTransform(items || []);
    }, [items]);

    // Создаем структуры для быстрой работы с деревом.
    var _usePathMaps = usePathMaps(transformedItems),
      _usePathMaps2 = _slicedToArray(_usePathMaps, 5),
      pathMap = _usePathMaps2[0],
      focusedToValueMap = _usePathMaps2[1],
      valueToCheckedMap = _usePathMaps2[2],
      valueToItemMap = _usePathMaps2[3],
      valueToPathMap = _usePathMaps2[4];

    /**
     * Refs
     */
    var floatingPopoverRef = useRef(null);
    var treeId = safeUseId();
    var listWrapperRef = useRef(null);
    var rootRef = useRef(null);
    var closeAfterSelect = outerCloseAfterSelect !== null && outerCloseAfterSelect !== void 0 ? outerCloseAfterSelect : !multiselect;

    /**
     * Hooks
     */
    var nativeMode = Boolean(name && !hasOuterValue(outerValue));
    var _useValue = useValue({
        outerValue: outerValue,
        outerOnChange: outerOnChange,
        defaultValue: defaultValue,
        multiselect: multiselect,
        nativeMode: nativeMode
      }),
      value = _useValue.value,
      handleChange = _useValue.handleChange;
    var requiredProps = _target === 'button-like' ? undefined : {
      required: required,
      requiredPlacement: requiredPlacement,
      hasRequiredIndicator: hasRequiredIndicator,
      optional: optional,
      optionalText: optionalText
    };
    var hintProps = _target === 'button-like' || !hintText ? undefined : {
      hintText: hintText,
      hintTrigger: hintTrigger,
      hintView: hintView,
      hintSize: hintSize,
      hintTargetIcon: hintTargetIcon,
      hintTargetPlacement: hintTargetPlacement,
      hintPlacement: hintPlacement,
      hintOffset: hintOffset,
      hintWidth: hintWidth,
      hintHasArrow: hintHasArrow,
      hintContentLeft: hintContentLeft
    };
    var _useListState = useListState({
        disabled: disabled,
        readOnly: readOnly,
        onToggle: onToggle,
        multiselect: multiselect,
        rootRef: rootRef
      }),
      path = _useListState.path,
      treePath = _useListState.treePath,
      focusedPath = _useListState.focusedPath,
      dispatchPath = _useListState.dispatchPath,
      dispatchTreePath = _useListState.dispatchTreePath,
      dispatchFocusedPath = _useListState.dispatchFocusedPath,
      handleListToggle = _useListState.handleListToggle,
      resetListState = _useListState.resetListState,
      isListOpened = _useListState.isListOpened;
    var activeDescendantItemValue = ((_getItemByFocused = getItemByFocused(focusedPath, focusedToValueMap)) === null || _getItemByFocused === void 0 ? void 0 : _getItemByFocused.value.toString()) || '';
    var _useCheckedState = useCheckedState({
        multiselect: multiselect,
        mode: mode,
        value: value,
        valueToCheckedMap: valueToCheckedMap,
        valueToItemMap: valueToItemMap,
        closeAfterSelect: closeAfterSelect,
        handleChange: handleChange,
        resetListState: resetListState
      }),
      checked = _useCheckedState.checked,
      handleCheckboxChange = _useCheckedState.handleCheckboxChange,
      handleItemClick = _useCheckedState.handleItemClick,
      handlePressDown = _useCheckedState.handlePressDown;
    var _useKeyNavigation = useKeyNavigation({
        focusedPath: focusedPath,
        dispatchFocusedPath: dispatchFocusedPath,
        path: path,
        dispatchPath: dispatchPath,
        pathMap: pathMap,
        focusedToValueMap: focusedToValueMap,
        handleListToggle: handleListToggle,
        handlePressDown: handlePressDown,
        treePath: treePath,
        dispatchTreePath: dispatchTreePath,
        treeView: treeView,
        valueToPathMap: valueToPathMap,
        items: transformedItems,
        disabled: disabled,
        readOnly: readOnly
      }),
      onKeyDown = _useKeyNavigation.onKeyDown;

    /**
     * Effects
     */
    /* Логика работы при клике за пределами выпадающего списка */
    useOutsideClick(function () {
      if (!isListOpened) {
        return;
      }
      handleListToggle(false);
    }, [floatingPopoverRef, listWrapperRef]);
    return /*#__PURE__*/React__default.createElement(Root, _extends({
      view: view,
      size: size,
      labelPlacement: labelPlacement,
      chipView: chipView,
      disabled: disabled,
      readOnly: readOnly,
      hintView: hintView,
      hintSize: hintSize,
      ref: rootRef
    }, rest), nativeMode && /*#__PURE__*/React__default.createElement(SelectNative, {
      items: valueToItemMap,
      name: name,
      value: value,
      multiselect: multiselect,
      handleChange: handleChange,
      outerOnChange: outerOnChange,
      ref: ref
    }), /*#__PURE__*/React__default.createElement(Context.Provider, {
      value: {
        focusedPath: focusedPath,
        checked: checked,
        multiselect: multiselect,
        size: size,
        handleCheckboxChange: handleCheckboxChange,
        handleItemClick: handleItemClick,
        variant: variant,
        renderItem: renderItem,
        renderSelectionIcon: renderSelectionIcon,
        treeId: treeId,
        _checkboxAppearance: _checkboxAppearance,
        treePath: treePath,
        dispatchTreePath: dispatchTreePath,
        arrowPlacement: arrowPlacement,
        valueToPathMap: valueToPathMap,
        singleLine: singleLine
      }
    }, /*#__PURE__*/React__default.createElement(FloatingPopover, {
      ref: floatingPopoverRef,
      opened: isListOpened,
      onToggle: handleListToggle,
      placement: placement,
      portal: portal,
      listWidth: listWidth,
      offset: _offset,
      target: function target(referenceRef) {
        return /*#__PURE__*/React__default.createElement(Target, {
          ref: name ? null : ref,
          target: _target,
          renderTarget: renderTarget,
          value: value,
          opened: isListOpened,
          valueToItemMap: valueToItemMap,
          label: label,
          placeholder: placeholder,
          onKeyDown: onKeyDown,
          labelPlacement: labelPlacement,
          size: size,
          view: view,
          keepPlaceholder: keepPlaceholder,
          contentLeft: contentLeft,
          contentRight: contentRight,
          disabled: disabled,
          readOnly: readOnly,
          renderValue: renderValue,
          inputWrapperRef: referenceRef,
          multiselect: multiselect,
          helperText: helperText,
          treeId: treeId,
          activeDescendantItemValue: activeDescendantItemValue,
          isTargetAmount: isTargetAmount,
          handleChange: handleChange,
          chipView: chipView,
          chipType: chipType,
          chipClickArea: chipClickArea,
          requiredProps: requiredProps,
          hintProps: hintProps
        });
      },
      zIndex: zIndex,
      isInner: false,
      shift: shift,
      flip: flip
    }, /*#__PURE__*/React__default.createElement(Root, {
      view: view,
      size: size,
      labelPlacement: labelPlacement,
      chipView: chipView,
      disabled: disabled,
      readOnly: readOnly,
      style: rest.style,
      className: rest.className
    }, treeView ? /*#__PURE__*/React__default.createElement(TreeList, {
      items: items,
      listMaxHeight: listMaxHeight,
      onScroll: virtual ? undefined : onScroll,
      virtual: virtual,
      beforeList: beforeList,
      afterList: afterList,
      emptyStateDescription: emptyStateDescription
    }) : /*#__PURE__*/React__default.createElement(ListWrapper, {
      ref: listWrapperRef,
      listWidth: listWidth
    }, /*#__PURE__*/React__default.createElement(Ul, {
      role: "tree",
      id: "".concat(treeId, "_tree_level_1"),
      "aria-multiselectable": Boolean(multiselect),
      listMaxHeight: listMaxHeight,
      onScroll: virtual ? undefined : onScroll,
      virtual: virtual
    }, beforeList, multiselect && selectAllOptions && /*#__PURE__*/React__default.createElement(SelectAll, {
      selectAllOptions: selectAllOptions,
      variant: variant
    }), isEmpty(transformedItems) ? /*#__PURE__*/React__default.createElement(StyledEmptyState, {
      className: classes.emptyStateWrapper,
      description: emptyStateDescription || 'Ничего не найдено'
    }) : /*#__PURE__*/React__default.createElement(React__default.Fragment, null, virtual ? /*#__PURE__*/React__default.createElement(VirtualList, {
      items: transformedItems,
      listMaxHeight: listMaxHeight,
      onScroll: onScroll
    }) : transformedItems.map(function (item, index) {
      return /*#__PURE__*/React__default.createElement(Inner, {
        key: "".concat(index, "/0"),
        item: item,
        currentLevel: 0,
        path: path,
        dispatchPath: dispatchPath,
        index: index,
        listWidth: listWidth,
        portal: listWrapperRef,
        shift: shift,
        flip: flip
      });
    })), afterList))))));
  });
};
var selectConfig = {
  name: 'Select',
  tag: 'div',
  layout: selectRoot,
  base: base,
  variations: {},
  defaults: {
    view: 'default',
    size: 'm',
    labelPlacement: 'outer',
    chipView: 'default',
    hintView: 'default',
    hintSize: 'm'
  }
};

export { selectConfig, selectRoot };
