'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var FloatingPopover = require('./FloatingPopover.js');
var focusedReducer = require('./reducers/focusedReducer.js');
var Autocomplete_styles = require('./Autocomplete.styles.js');
var useKeyboardNavigation = require('./hooks/useKeyboardNavigation.js');
var react = require('../../utils/react.js');
var useOutsideClick = require('../../hooks/useOutsideClick.js');
var useDidMountEffect = require('../../hooks/useDidMountEffect.js');
var TextField_styles = require('./ui/TextField/TextField.styles.js');
var VirtualList = require('./ui/VirtualList/VirtualList.js');
var SuggestionItem = require('./ui/SuggestionItem/SuggestionItem.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var _excluded = ["value", "defaultValue", "onChange", "suggestions", "view", "size", "labelPlacement", "keepPlaceholder", "disabled", "readOnly", "label", "leftHelper", "contentLeft", "contentRight", "textBefore", "textAfter", "onScroll", "onBlur", "onFocus", "listMaxHeight", "listWidth", "portal", "zIndex", "filter", "onSuggestionSelect", "threshold", "renderList", "renderListEnd", "renderItem", "onSearch", "hintText", "hintView", "hintSize", "beforeList", "afterList", "virtual", "flip", "rootClassName", "rootStyle", "_offset"];

/**
 * Компонент Autocomplete. Поле ввода с подсказками в выпадающем списке.
 */
var autocompleteRoot = function autocompleteRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (_ref, ref) {
    var _StyledLeftHelper;
    var outerValue = _ref.value,
      defaultValue = _ref.defaultValue,
      onChange = _ref.onChange,
      suggestions = _ref.suggestions,
      view = _ref.view,
      size = _ref.size,
      labelPlacement = _ref.labelPlacement,
      keepPlaceholder = _ref.keepPlaceholder,
      disabled = _ref.disabled,
      readOnly = _ref.readOnly,
      label = _ref.label,
      leftHelper = _ref.leftHelper,
      contentLeft = _ref.contentLeft,
      contentRight = _ref.contentRight,
      textBefore = _ref.textBefore,
      textAfter = _ref.textAfter,
      onScroll = _ref.onScroll,
      onBlur = _ref.onBlur,
      onFocus = _ref.onFocus,
      _ref$listMaxHeight = _ref.listMaxHeight,
      listMaxHeight = _ref$listMaxHeight === void 0 ? '25rem' : _ref$listMaxHeight,
      listWidth = _ref.listWidth,
      portal = _ref.portal,
      zIndex = _ref.zIndex,
      filter = _ref.filter,
      onSuggestionSelect = _ref.onSuggestionSelect,
      _ref$threshold = _ref.threshold,
      threshold = _ref$threshold === void 0 ? 2 : _ref$threshold,
      renderList = _ref.renderList,
      renderListEnd = _ref.renderListEnd,
      renderItem = _ref.renderItem,
      onSearch = _ref.onSearch,
      hintText = _ref.hintText,
      _ref$hintView = _ref.hintView,
      hintView = _ref$hintView === void 0 ? 'default' : _ref$hintView,
      _ref$hintSize = _ref.hintSize,
      hintSize = _ref$hintSize === void 0 ? 'm' : _ref$hintSize,
      beforeList = _ref.beforeList,
      afterList = _ref.afterList,
      _ref$virtual = _ref.virtual,
      virtual = _ref$virtual === void 0 ? false : _ref$virtual,
      _ref$flip = _ref.flip,
      flip = _ref$flip === void 0 ? false : _ref$flip,
      rootClassName = _ref.rootClassName,
      rootStyle = _ref.rootStyle,
      _offset = _ref._offset,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(_ref, _excluded);
    var _useReducer = React.useReducer(focusedReducer.focusedReducer, null),
      _useReducer2 = _rollupPluginBabelHelpers.slicedToArray(_useReducer, 2),
      focused = _useReducer2[0],
      dispatchFocused = _useReducer2[1];
    var _useState = React.useState(defaultValue || ''),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      innerValue = _useState2[0],
      setInnerValue = _useState2[1];
    var _useState3 = React.useState(false),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      isOpen = _useState4[0],
      setIsOpen = _useState4[1];
    var listId = react.safeUseId();
    var value = outerValue !== null && outerValue !== void 0 ? outerValue : innerValue;
    var helperTextId = react.safeUseId();
    var floatingPopoverRef = React.useRef(null);
    var floatingListRef = React.useRef(null);
    var listWrapperRef = React.useRef(null);
    var isListMouseDownRef = React.useRef(false);

    /* Логика работы при клике за пределами выпадающего списка */
    useOutsideClick.useOutsideClick(function () {
      setIsOpen(false);
    }, [floatingPopoverRef, listWrapperRef]);
    var handleFocus = function handleFocus(event) {
      if (onFocus) {
        onFocus(event);
      }
      if (!readOnly && value.toString().length >= threshold) {
        setIsOpen(true);
      }
    };
    var handleBlur = function handleBlur(event) {
      if (onBlur) {
        onBlur(event);
      }
      if (isListMouseDownRef.current) {
        return;
      }
      setIsOpen(false);
    };
    var handleListMouseDown = function handleListMouseDown() {
      isListMouseDownRef.current = true;
      window.setTimeout(function () {
        isListMouseDownRef.current = false;
      }, 0);
    };
    var handleItemClick = function handleItemClick(e) {
      setInnerValue(e.label);
      if (onSuggestionSelect) {
        onSuggestionSelect(e);
      }
      setIsOpen(false);
    };
    var handleChange = function handleChange(e) {
      var currentValue = e.target.value;
      setInnerValue(currentValue);
      if (onChange) {
        onChange(e);
      }
      if (currentValue.toString().length >= threshold) {
        setIsOpen(true);
      } else {
        setIsOpen(false);
      }
    };
    var defaultFilterCallback = function defaultFilterCallback(_ref2) {
      var label = _ref2.label;
      return label.toLowerCase().includes(value.toString().toLowerCase());
    };
    var helperTextStopPropagation = function helperTextStopPropagation(event) {
      event.stopPropagation();
    };
    var finalResults = (suggestions === null || suggestions === void 0 ? void 0 : suggestions.filter(filter || defaultFilterCallback)) || [];
    var _useKeyNavigation = useKeyboardNavigation.useKeyNavigation({
        isOpen: isOpen,
        setIsOpen: setIsOpen,
        focused: focused,
        dispatchFocused: dispatchFocused,
        finalResults: finalResults,
        handleItemClick: handleItemClick
      }),
      onKeyDown = _useKeyNavigation.onKeyDown;
    useDidMountEffect.useDidMountEffect(function () {
      dispatchFocused({
        type: 'reset'
      });
    }, [value]);
    return /*#__PURE__*/React__default.default.createElement(Root, {
      view: view,
      size: size,
      labelPlacement: labelPlacement,
      disabled: disabled,
      readOnly: readOnly,
      hintView: hintView,
      hintSize: hintSize,
      className: rootClassName,
      style: rootStyle
    }, /*#__PURE__*/React__default.default.createElement(FloatingPopover.FloatingPopover, {
      ref: floatingPopoverRef,
      opened: isOpen,
      portal: portal,
      zIndex: zIndex,
      listWidth: listWidth,
      offset: _offset,
      flip: flip,
      floatingRef: floatingListRef,
      onFloatingMouseDown: handleListMouseDown,
      target: function target(referenceRef) {
        return /*#__PURE__*/React__default.default.createElement(TextField_styles.StyledTextField, _rollupPluginBabelHelpers.extends({
          ref: ref,
          inputWrapperRef: referenceRef,
          value: value,
          onChange: handleChange,
          onSearch: focused === null ? onSearch : undefined,
          size: size,
          view: view,
          disabled: disabled,
          readOnly: readOnly,
          label: label,
          contentLeft: contentLeft,
          contentRight: contentRight,
          textBefore: textBefore,
          textAfter: textAfter,
          onFocus: handleFocus,
          onBlur: handleBlur,
          onKeyDown: onKeyDown,
          role: "combobox",
          "aria-autocomplete": "list",
          "aria-controls": listId,
          "aria-expanded": isOpen,
          "aria-activedescendant": "".concat(listId, "/").concat(focused),
          "aria-describedby": helperTextId,
          hintText: String(hintText || ''),
          labelPlacement: labelPlacement,
          keepPlaceholder: keepPlaceholder,
          leftHelper: leftHelper && (_StyledLeftHelper || (_StyledLeftHelper = /*#__PURE__*/React__default.default.createElement(Autocomplete_styles.StyledLeftHelper, {
            onClick: helperTextStopPropagation
          }, leftHelper)))
        }, rest));
      }
    }, renderList && renderList(finalResults) || Boolean(finalResults.length) && /*#__PURE__*/React__default.default.createElement(Root, {
      view: view,
      size: size,
      labelPlacement: labelPlacement,
      disabled: disabled,
      readOnly: readOnly
    }, /*#__PURE__*/React__default.default.createElement(Autocomplete_styles.ListWrapper, {
      ref: listWrapperRef
    }, /*#__PURE__*/React__default.default.createElement(Autocomplete_styles.Ul, {
      id: listId,
      role: "listbox",
      "aria-label": label,
      onScroll: virtual ? undefined : onScroll,
      listMaxHeight: listMaxHeight,
      virtual: virtual
    }, virtual ? /*#__PURE__*/React__default.default.createElement(VirtualList.VirtualList, {
      items: finalResults,
      onClick: handleItemClick,
      listId: listId,
      listMaxHeight: listMaxHeight,
      onScroll: onScroll,
      renderItem: renderItem
    }) : /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, beforeList, finalResults.map(function (suggestion, index) {
      return /*#__PURE__*/React__default.default.createElement(SuggestionItem.SuggestionItem, {
        key: index,
        item: suggestion,
        onClick: handleItemClick,
        id: "".concat(listId, "/").concat(index),
        focused: focused === index,
        renderItem: renderItem
      });
    }), afterList), renderListEnd && /*#__PURE__*/React__default.default.createElement(Autocomplete_styles.InfiniteLoaderWrapper, null, renderListEnd()))))));
  });
};
var autocompleteConfig = {
  name: 'Autocomplete',
  tag: 'div',
  layout: autocompleteRoot,
  base: Autocomplete_styles.base,
  defaults: {
    view: 'default',
    size: 'l',
    labelPlacement: 'outer'
  },
  variations: {
    view: {
      css: ''
    }
  }
};

exports.autocompleteConfig = autocompleteConfig;
exports.autocompleteRoot = autocompleteRoot;
