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 _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);
}
import React, { Children, forwardRef, useEffect, useRef, useState } from "react";
import { safeUseId, cx, getPlacements } from "../../../utils";
import { useDidMountEffect, useForceUpdate, useForkRef } from "../../../hooks";
import { getChildren, getNewSelected, getValues } from "./utils";
import { useKeyNavigation } from "./hooks";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { ComboboxTarget } from "./ui";
import { ComboboxItemNotFound, StyledPopover, StyledRoot, StyledCombobox, StyledNativeSelect } from "./Combobox.styles";
/**
 * Выпадающий список без внешнего контроля видимости.
 */ export var comboboxRoot = function comboboxRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), name = _ref2.name, form = _ref2.form, readOnly = _ref2.readOnly, disabled = _ref2.disabled, label = _ref2.label, placeholder = _ref2.placeholder, id = _ref2.id, children = _ref2.children, role = _ref2.role, view = _ref2.view, size = _ref2.size, frame = _ref2.frame, usePortal = _ref2.usePortal, _ref_negativeResultContent = _ref2.negativeResultContent, negativeResultContent = _ref_negativeResultContent === void 0 ? 'Элементы не найдены' : _ref_negativeResultContent, _ref_enumerationType = _ref2.enumerationType, enumerationType = _ref_enumerationType === void 0 ? 'comma' : _ref_enumerationType, _ref_opened = _ref2.opened, opened = _ref_opened === void 0 ? false : _ref_opened, _ref_alwaysOpened = _ref2.alwaysOpened, alwaysOpened = _ref_alwaysOpened === void 0 ? false : _ref_alwaysOpened, _ref_placement = _ref2.placement, placement = _ref_placement === void 0 ? 'bottom' : _ref_placement, onToggle = _ref2.onToggle, onKeyDown = _ref2.onKeyDown, filterFunction = _ref2.filterFunction, rest = _object_without_properties(_ref2, [
            "name",
            "form",
            "readOnly",
            "disabled",
            "label",
            "placeholder",
            "id",
            "children",
            "role",
            "view",
            "size",
            "frame",
            "usePortal",
            "negativeResultContent",
            "enumerationType",
            "opened",
            "alwaysOpened",
            "placement",
            "onToggle",
            "onKeyDown",
            "filterFunction"
        ]), _rest1 = _sliced_to_array(_rest, 1), outerRootRef = _rest1[0];
        var _targetRef_current;
        var forceUpdate = useForceUpdate();
        var uniqId = safeUseId();
        var innerId = id || uniqId;
        var _rest_valueType = rest.valueType, valueType = _rest_valueType === void 0 ? 'single' : _rest_valueType, value = rest.value;
        var offset = [
            0,
            4
        ];
        var _useState = _sliced_to_array(useState(null), 2), ref = _useState[0], setRef = _useState[1];
        var targetRef = useRef(null);
        var chipsRefs = useRef([]);
        var comboboxRef = useRef(null);
        var itemsRefs = useRef([]);
        var inputRef = useRef(null);
        var handleRef = useForkRef(targetRef, outerRootRef);
        var controlledRefs = {
            targetRef: targetRef,
            chipsRefs: chipsRefs,
            selectRef: comboboxRef,
            itemsRefs: itemsRefs,
            inputRef: inputRef
        };
        var _useState1 = _sliced_to_array(useState(alwaysOpened || opened), 2), isVisible = _useState1[0], setIsVisible = _useState1[1];
        var _useState2 = _sliced_to_array(useState(''), 2), search = _useState2[0], setSearch = _useState2[1];
        var _useState3 = _sliced_to_array(useState(search), 2), filterValue = _useState3[0], setFilterValue = _useState3[1];
        // INFO: нужно высчитывать для корректной работы портала
        var dynamicTargetWidth = (_targetRef_current = targetRef.current) === null || _targetRef_current === void 0 ? void 0 : _targetRef_current.offsetWidth;
        // INFO: Из-за того, что классы передаются через ref,
        // состояние пропсов после изменения view, size
        // всегда предыдущее, поэтому нужно делать форс-ререндер
        useDidMountEffect(function() {
            forceUpdate();
        }, [
            view,
            size
        ]);
        useEffect(function() {
            if (disabled || readOnly) {
                return;
            }
            setIsVisible(alwaysOpened || opened);
        }, [
            opened,
            alwaysOpened,
            disabled,
            readOnly
        ]);
        useEffect(function() {
            // INFO: Для кейсов, когда значение выбрано и нужно вывести весь список
            if (alwaysOpened || opened) {
                setFilterValue('');
            }
        }, []);
        var onInnerToggle = function onInnerToggle(openValue, event) {
            if (disabled || readOnly) {
                return;
            }
            // INFO: Для кейсов, когда значение выбрано и нужно вывести весь список
            if (!isVisible) {
                setFilterValue('');
            }
            if (onToggle) {
                onToggle(alwaysOpened || openValue, event);
                return;
            }
            setIsVisible(alwaysOpened || openValue);
        };
        var closedWithoutChanges = useRef(true);
        var updateValue = function updateValue(item, event) {
            var _rest_onChangeValue;
            var _item_dataset = item.dataset, newValue = _item_dataset.value;
            if (rest.valueType === 'multiple') {
                var _rest_onChangeValue1;
                var newSelected = getNewSelected(rest.value, newValue, rest.valueType);
                (_rest_onChangeValue1 = rest.onChangeValue) === null || _rest_onChangeValue1 === void 0 ? void 0 : _rest_onChangeValue1.call(rest, newSelected);
                return;
            }
            var newSelected1 = getNewSelected(rest.value, newValue, 'single');
            (_rest_onChangeValue = rest.onChangeValue) === null || _rest_onChangeValue === void 0 ? void 0 : _rest_onChangeValue.call(rest, newSelected1);
            onInnerToggle === null || onInnerToggle === void 0 ? void 0 : onInnerToggle(alwaysOpened || false, event);
            closedWithoutChanges.current = false;
        };
        var onClickChildrenItem = function onClickChildrenItem(event) {
            // INFO: Для корректной работы компонента Popper
            event.stopPropagation();
            var item = event.currentTarget;
            updateValue(item, event);
        };
        var onChangeChipValue = function onChangeChipValue(newValue) {
            var _rest_onChangeValue;
            if (rest.valueType !== 'multiple') {
                return;
            }
            (_rest_onChangeValue = rest.onChangeValue) === null || _rest_onChangeValue === void 0 ? void 0 : _rest_onChangeValue.call(rest, newValue);
        };
        var _useKeyNavigation = useKeyNavigation({
            controlledRefs: controlledRefs,
            opened: isVisible,
            enumerationType: enumerationType,
            valueType: valueType,
            componentType: 'combobox',
            value: value,
            search: filterValue,
            updateOpened: onInnerToggle,
            updateValue: updateValue
        }), onKeyDownTarget = _useKeyNavigation.onKeyDownTarget, onKeyDownSelect = _useKeyNavigation.onKeyDownSelect;
        var childrenArray = Children.toArray(children);
        var childrenMemo = getChildren(childrenArray, {
            onClick: onClickChildrenItem,
            childrenRefs: itemsRefs
        }, value, filterValue, filterFunction).filter(Boolean);
        var values = getValues(childrenArray, value);
        var onSearch = function onSearch(newSearch, newOpened) {
            setSearch(newSearch);
            setFilterValue(newSearch);
            setIsVisible(newOpened !== null && newOpened !== void 0 ? newOpened : true);
        };
        var onKeyDownHandle = function onKeyDownHandle(event) {
            onKeyDown === null || onKeyDown === void 0 ? void 0 : onKeyDown(event);
            onKeyDownTarget(event);
        };
        useEffect(function() {
            if (alwaysOpened && rest.valueType === 'single') {
                setSearch(String(value));
            }
        }, [
            value,
            alwaysOpened
        ]);
        return /*#__PURE__*/ React.createElement(StyledRoot, {
            ref: comboboxRef
        }, /*#__PURE__*/ React.createElement(StyledNativeSelect, {
            "aria-invalid": "false",
            "aria-hidden": "true",
            "aria-readonly": readOnly,
            tabIndex: -1,
            form: form,
            name: name,
            value: "".concat(value),
            disabled: disabled || readOnly
        }), /*#__PURE__*/ React.createElement(StyledPopover, {
            role: role,
            opened: isVisible,
            onToggle: onInnerToggle,
            target: /*#__PURE__*/ React.createElement(ComboboxTarget, _object_spread({
                opened: isVisible,
                values: values,
                label: label,
                placeholder: placeholder,
                search: search,
                enumerationType: enumerationType,
                valueType: valueType,
                readOnly: readOnly,
                disabled: disabled,
                size: size,
                closedWithoutChanges: closedWithoutChanges,
                ref: handleRef,
                chipsRefs: chipsRefs,
                inputRef: inputRef,
                id: innerId,
                onChange: onChangeChipValue,
                onSearch: onSearch,
                onKeyDown: onKeyDownHandle
            }, rest)),
            className: cx(ref === null || ref === void 0 ? void 0 : ref.classList.toString()),
            id: innerId,
            offset: offset,
            placement: getPlacements(placement),
            usePortal: usePortal,
            selectWidth: dynamicTargetWidth,
            frame: frame,
            trigger: "click",
            isFocusTrapped: false,
            preventOverflow: false,
            closeOnEsc: false,
            closeOnOverlayClick: true
        }, /*#__PURE__*/ React.createElement(Root, {
            ref: setRef,
            view: view,
            size: size
        }, /*#__PURE__*/ React.createElement(StyledCombobox, {
            onKeyDown: onKeyDownSelect
        }, childrenMemo.length ? childrenMemo : /*#__PURE__*/ React.createElement(ComboboxItemNotFound, null, negativeResultContent)))));
    });
};
export var comboboxConfig = {
    name: 'Combobox',
    tag: 'div',
    layout: comboboxRoot,
    base: '',
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
