"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get autocompleteConfig () {
        return autocompleteConfig;
    },
    get autocompleteRoot () {
        return autocompleteRoot;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../utils");
var _hooks = require("../../hooks");
var _FloatingPopover = require("./FloatingPopover");
var _focusedReducer = require("./reducers/focusedReducer");
var _ui = require("./ui");
var _Autocompletestyles = require("./Autocomplete.styles");
var _useKeyboardNavigation = require("./hooks/useKeyboardNavigation");
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var autocompleteRoot = function autocompleteRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), outerValue = _ref2.value, defaultValue = _ref2.defaultValue, onChange = _ref2.onChange, suggestions = _ref2.suggestions, view = _ref2.view, size = _ref2.size, labelPlacement = _ref2.labelPlacement, keepPlaceholder = _ref2.keepPlaceholder, disabled = _ref2.disabled, readOnly = _ref2.readOnly, label = _ref2.label, leftHelper = _ref2.leftHelper, contentLeft = _ref2.contentLeft, contentRight = _ref2.contentRight, textBefore = _ref2.textBefore, textAfter = _ref2.textAfter, onScroll = _ref2.onScroll, _ref_listMaxHeight = _ref2.listMaxHeight, listMaxHeight = _ref_listMaxHeight === void 0 ? '25rem' : _ref_listMaxHeight, listWidth = _ref2.listWidth, portal = _ref2.portal, zIndex = _ref2.zIndex, filter = _ref2.filter, onSuggestionSelect = _ref2.onSuggestionSelect, _ref_threshold = _ref2.threshold, threshold = _ref_threshold === void 0 ? 2 : _ref_threshold, renderList = _ref2.renderList, renderListEnd = _ref2.renderListEnd, renderItem = _ref2.renderItem, onSearch = _ref2.onSearch, hintText = _ref2.hintText, _ref_hintView = _ref2.hintView, hintView = _ref_hintView === void 0 ? 'default' : _ref_hintView, _ref_hintSize = _ref2.hintSize, hintSize = _ref_hintSize === void 0 ? 'm' : _ref_hintSize, beforeList = _ref2.beforeList, afterList = _ref2.afterList, _ref_virtual = _ref2.virtual, virtual = _ref_virtual === void 0 ? false : _ref_virtual, _ref_flip = _ref2.flip, flip = _ref_flip === void 0 ? false : _ref_flip, rootClassName = _ref2.rootClassName, rootStyle = _ref2.rootStyle, // @ts-ignore
        _offset = _ref2._offset, rest = _object_without_properties(_ref2, [
            "value",
            "defaultValue",
            "onChange",
            "suggestions",
            "view",
            "size",
            "labelPlacement",
            "keepPlaceholder",
            "disabled",
            "readOnly",
            "label",
            "leftHelper",
            "contentLeft",
            "contentRight",
            "textBefore",
            "textAfter",
            "onScroll",
            "listMaxHeight",
            "listWidth",
            "portal",
            "zIndex",
            "filter",
            "onSuggestionSelect",
            "threshold",
            "renderList",
            "renderListEnd",
            "renderItem",
            "onSearch",
            "hintText",
            "hintView",
            "hintSize",
            "beforeList",
            "afterList",
            "virtual",
            "flip",
            "rootClassName",
            "rootStyle",
            "_offset"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _useReducer = _sliced_to_array((0, _react.useReducer)(_focusedReducer.focusedReducer, null), 2), focused = _useReducer[0], dispatchFocused = _useReducer[1];
        var _useState = _sliced_to_array((0, _react.useState)(defaultValue || ''), 2), innerValue = _useState[0], setInnerValue = _useState[1];
        var _useState1 = _sliced_to_array((0, _react.useState)(false), 2), isOpen = _useState1[0], setIsOpen = _useState1[1];
        var listId = (0, _utils.safeUseId)();
        var value = outerValue !== null && outerValue !== void 0 ? outerValue : innerValue;
        var helperTextId = (0, _utils.safeUseId)();
        var floatingPopoverRef = (0, _react.useRef)(null);
        var listWrapperRef = (0, _react.useRef)(null);
        /* Логика работы при клике за пределами выпадающего списка */ (0, _hooks.useOutsideClick)(function() {
            setIsOpen(false);
        }, [
            floatingPopoverRef,
            listWrapperRef
        ]);
        var handleFocus = function handleFocus() {
            if (value.toString().length >= threshold) {
                setIsOpen(true);
            }
        };
        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(param) {
            var label = param.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 onKeyDown = (0, _useKeyboardNavigation.useKeyNavigation)({
            isOpen: isOpen,
            setIsOpen: setIsOpen,
            focused: focused,
            dispatchFocused: dispatchFocused,
            finalResults: finalResults,
            handleItemClick: handleItemClick
        }).onKeyDown;
        (0, _hooks.useDidMountEffect)(function() {
            dispatchFocused({
                type: 'reset'
            });
        }, [
            value
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            view: view,
            size: size,
            labelPlacement: labelPlacement,
            disabled: disabled,
            readOnly: readOnly,
            hintView: hintView,
            hintSize: hintSize,
            className: rootClassName,
            style: rootStyle
        }, /*#__PURE__*/ _react.default.createElement(_FloatingPopover.FloatingPopover, {
            ref: floatingPopoverRef,
            opened: isOpen,
            portal: portal,
            zIndex: zIndex,
            listWidth: listWidth,
            offset: _offset,
            flip: flip,
            target: function target(referenceRef) {
                return /*#__PURE__*/ _react.default.createElement(_ui.StyledTextField, _object_spread({
                    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,
                    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 && /*#__PURE__*/ _react.default.createElement(_Autocompletestyles.StyledLeftHelper, {
                        onClick: helperTextStopPropagation
                    }, leftHelper)
                }, rest));
            }
        }, renderList && renderList(finalResults) || Boolean(finalResults.length) && /*#__PURE__*/ _react.default.createElement(Root, {
            view: view,
            size: size,
            labelPlacement: labelPlacement,
            disabled: disabled,
            readOnly: readOnly
        }, /*#__PURE__*/ _react.default.createElement(_Autocompletestyles.ListWrapper, {
            ref: listWrapperRef
        }, /*#__PURE__*/ _react.default.createElement(_Autocompletestyles.Ul, {
            id: listId,
            role: "listbox",
            "aria-label": label,
            onScroll: virtual ? undefined : onScroll,
            listMaxHeight: listMaxHeight,
            virtual: virtual
        }, virtual ? /*#__PURE__*/ _react.default.createElement(_ui.VirtualList, {
            items: finalResults,
            onClick: handleItemClick,
            listId: listId,
            listMaxHeight: listMaxHeight,
            onScroll: onScroll,
            renderItem: renderItem
        }) : /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, beforeList, finalResults.map(function(suggestion, index) {
            return /*#__PURE__*/ _react.default.createElement(_ui.SuggestionItem, {
                key: index,
                item: suggestion,
                onClick: handleItemClick,
                id: "".concat(listId, "/").concat(index),
                focused: focused === index,
                renderItem: renderItem
            });
        }), afterList), renderListEnd && /*#__PURE__*/ _react.default.createElement(_Autocompletestyles.InfiniteLoaderWrapper, null, renderListEnd()))))));
    });
};
var autocompleteConfig = {
    name: 'Autocomplete',
    tag: 'div',
    layout: autocompleteRoot,
    base: _Autocompletestyles.base,
    defaults: {
        view: 'default',
        size: 'l',
        labelPlacement: 'outer'
    },
    variations: {
        view: {
            css: ''
        }
    }
};
