"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;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../utils");
const _hooks = require("../../hooks");
const _FloatingPopover = require("./FloatingPopover");
const _focusedReducer = require("./reducers/focusedReducer");
const _ui = require("./ui");
const _Autocompletestyles = require("./Autocomplete.styles");
const _useKeyboardNavigation = require("./hooks/useKeyboardNavigation");
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;
}
const autocompleteRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ value: outerValue, defaultValue, onChange, suggestions, view, size, labelPlacement, keepPlaceholder, disabled, readOnly, label, leftHelper, contentLeft, contentRight, textBefore, textAfter, onScroll, onBlur, onFocus, listMaxHeight = '25rem', listWidth, portal, zIndex, filter, onSuggestionSelect, threshold = 2, renderList, renderListEnd, renderItem, onSearch, hintText, hintView = 'default', hintSize = 'm', beforeList, afterList, virtual = false, flip = false, rootClassName, rootStyle, // @ts-ignore
    _offset, ...rest }, ref)=>{
        const [focused, dispatchFocused] = (0, _react.useReducer)(_focusedReducer.focusedReducer, null);
        const [innerValue, setInnerValue] = (0, _react.useState)(defaultValue || '');
        const [isOpen, setIsOpen] = (0, _react.useState)(false);
        const listId = (0, _utils.safeUseId)();
        const value = outerValue ?? innerValue;
        const helperTextId = (0, _utils.safeUseId)();
        const floatingPopoverRef = (0, _react.useRef)(null);
        const floatingListRef = (0, _react.useRef)(null);
        const listWrapperRef = (0, _react.useRef)(null);
        const isListMouseDownRef = (0, _react.useRef)(false);
        /* Логика работы при клике за пределами выпадающего списка */ (0, _hooks.useOutsideClick)(()=>{
            setIsOpen(false);
        }, [
            floatingPopoverRef,
            listWrapperRef
        ]);
        const handleFocus = (event)=>{
            if (onFocus) {
                onFocus(event);
            }
            if (!readOnly && value.toString().length >= threshold) {
                setIsOpen(true);
            }
        };
        const handleBlur = (event)=>{
            if (onBlur) {
                onBlur(event);
            }
            if (isListMouseDownRef.current) {
                return;
            }
            setIsOpen(false);
        };
        const handleListMouseDown = ()=>{
            isListMouseDownRef.current = true;
            window.setTimeout(()=>{
                isListMouseDownRef.current = false;
            }, 0);
        };
        const handleItemClick = (e)=>{
            setInnerValue(e.label);
            if (onSuggestionSelect) {
                onSuggestionSelect(e);
            }
            setIsOpen(false);
        };
        const handleChange = (e)=>{
            const currentValue = e.target.value;
            setInnerValue(currentValue);
            if (onChange) {
                onChange(e);
            }
            if (currentValue.toString().length >= threshold) {
                setIsOpen(true);
            } else {
                setIsOpen(false);
            }
        };
        const defaultFilterCallback = ({ label })=>{
            return label.toLowerCase().includes(value.toString().toLowerCase());
        };
        const helperTextStopPropagation = (event)=>{
            event.stopPropagation();
        };
        const finalResults = suggestions?.filter(filter || defaultFilterCallback) || [];
        const { onKeyDown } = (0, _useKeyboardNavigation.useKeyNavigation)({
            isOpen,
            setIsOpen,
            focused,
            dispatchFocused,
            finalResults,
            handleItemClick
        });
        (0, _hooks.useDidMountEffect)(()=>{
            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,
            floatingRef: floatingListRef,
            onFloatingMouseDown: handleListMouseDown,
            target: (referenceRef)=>/*#__PURE__*/ _react.default.createElement(_ui.StyledTextField, {
                    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": `${listId}/${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((suggestion, index)=>/*#__PURE__*/ _react.default.createElement(_ui.SuggestionItem, {
                key: index,
                item: suggestion,
                onClick: handleItemClick,
                id: `${listId}/${index}`,
                focused: focused === index,
                renderItem: renderItem
            })), afterList), renderListEnd && /*#__PURE__*/ _react.default.createElement(_Autocompletestyles.InfiniteLoaderWrapper, null, renderListEnd()))))));
    });
const autocompleteConfig = {
    name: 'Autocomplete',
    tag: 'div',
    layout: autocompleteRoot,
    base: _Autocompletestyles.base,
    defaults: {
        view: 'default',
        size: 'l',
        labelPlacement: 'outer'
    },
    variations: {
        view: {
            css: ''
        }
    }
};
