"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 selectConfig () {
        return selectConfig;
    },
    get selectRoot () {
        return selectRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../utils");
const _hooks = require("../../hooks");
const _hooks1 = require("./hooks");
const _ui = require("./ui");
const _Selectstyles = require("./Select.styles");
const _Selecttokens = require("./Select.tokens");
const _FloatingPopover = require("./FloatingPopover");
const _SelectNative = require("./ui/SelectNative/SelectNative");
const _Selectcontext = require("./Select.context");
const _utils1 = require("./utils");
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 selectRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, ref)=>{
        const { // Config
        size, view, chipView, hintSize, hintView, // Target
        target = 'textfield-like', contentLeft, contentRight, placeholder, helperText, chipType = 'default', chipClickArea = 'full', required, requiredPlacement = 'right', optional, optionalText, hasRequiredIndicator = false, hintText, hintTrigger, hintTargetIcon, hintTargetPlacement = 'outer', hintPlacement, hintHasArrow, hintOffset = [
            0,
            8
        ], hintWidth, hintContentLeft, label, labelPlacement, keepPlaceholder, // IsMultiselect
        multiselect, value: outerValue, onChange: outerOnChange, isTargetAmount, renderTarget, selectAllOptions, name, defaultValue, // Private
        _offset, _checkboxAppearance, // Basic
        items, treeView = false, arrowPlacement = 'left', placement = 'bottom', disabled = false, readOnly = false, variant = 'normal', zIndex, listMaxHeight, listWidth, portal, renderValue, renderItem, renderSelectionIcon, closeAfterSelect: outerCloseAfterSelect, beforeList, afterList, virtual = false, onScroll, onToggle, mode = 'default', flip, shift, singleLine, emptyStateDescription, // Rest
        ...rest } = props;
        // Deep copy массива items с добавлением parent-ноды родителя.
        const transformedItems = (0, _react.useMemo)(()=>(0, _utils1.initialItemsTransform)(items || []), [
            items
        ]);
        // Создаем структуры для быстрой работы с деревом.
        const [pathMap, focusedToValueMap, valueToCheckedMap, valueToItemMap, valueToPathMap] = (0, _hooks1.usePathMaps)(transformedItems);
        /**
         * Refs
         */ const floatingPopoverRef = (0, _react.useRef)(null);
        const treeId = (0, _utils.safeUseId)();
        const listWrapperRef = (0, _react.useRef)(null);
        const rootRef = (0, _react.useRef)(null);
        const closeAfterSelect = outerCloseAfterSelect ?? !multiselect;
        /**
         * Hooks
         */ const nativeMode = Boolean(name && !(0, _utils1.hasOuterValue)(outerValue));
        const { value, handleChange } = (0, _hooks1.useValue)({
            outerValue,
            outerOnChange,
            defaultValue,
            multiselect,
            nativeMode
        });
        const requiredProps = target === 'button-like' ? undefined : {
            required,
            requiredPlacement,
            hasRequiredIndicator,
            optional,
            optionalText
        };
        const hintProps = target === 'button-like' || !hintText ? undefined : {
            hintText,
            hintTrigger,
            hintView,
            hintSize,
            hintTargetIcon,
            hintTargetPlacement,
            hintPlacement,
            hintOffset,
            hintWidth,
            hintHasArrow,
            hintContentLeft
        };
        const { path, treePath, focusedPath, dispatchPath, dispatchTreePath, dispatchFocusedPath, handleListToggle, resetListState, isListOpened } = (0, _hooks1.useListState)({
            disabled,
            readOnly,
            onToggle,
            multiselect,
            rootRef
        });
        const activeDescendantItemValue = (0, _utils1.getItemByFocused)(focusedPath, focusedToValueMap)?.value.toString() || '';
        const { checked, handleCheckboxChange, handleItemClick, handlePressDown } = (0, _hooks1.useCheckedState)({
            multiselect,
            mode,
            value,
            valueToCheckedMap,
            valueToItemMap,
            closeAfterSelect,
            handleChange,
            resetListState
        });
        const { onKeyDown } = (0, _hooks1.useKeyNavigation)({
            focusedPath,
            dispatchFocusedPath,
            path,
            dispatchPath,
            pathMap,
            focusedToValueMap,
            handleListToggle,
            handlePressDown,
            treePath,
            dispatchTreePath,
            treeView,
            valueToPathMap,
            items: transformedItems,
            disabled,
            readOnly
        });
        /**
         * Effects
         */ /* Логика работы при клике за пределами выпадающего списка */ (0, _hooks.useOutsideClick)(()=>{
            if (!isListOpened) {
                return;
            }
            handleListToggle(false);
        }, [
            floatingPopoverRef,
            listWrapperRef
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            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.SelectNative, {
            items: valueToItemMap,
            name: name,
            value: value,
            multiselect: multiselect,
            handleChange: handleChange,
            outerOnChange: outerOnChange,
            ref: ref
        }), /*#__PURE__*/ _react.default.createElement(_Selectcontext.Context.Provider, {
            value: {
                focusedPath,
                checked,
                multiselect,
                size,
                handleCheckboxChange,
                handleItemClick,
                variant,
                renderItem,
                renderSelectionIcon,
                treeId,
                _checkboxAppearance,
                treePath,
                dispatchTreePath,
                arrowPlacement,
                valueToPathMap,
                singleLine
            }
        }, /*#__PURE__*/ _react.default.createElement(_FloatingPopover.FloatingPopover, {
            ref: floatingPopoverRef,
            opened: isListOpened,
            onToggle: handleListToggle,
            placement: placement,
            portal: portal,
            listWidth: listWidth,
            offset: _offset,
            target: (referenceRef)=>/*#__PURE__*/ _react.default.createElement(_ui.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(_ui.TreeList, {
            items: items,
            listMaxHeight: listMaxHeight,
            onScroll: virtual ? undefined : onScroll,
            virtual: virtual,
            beforeList: beforeList,
            afterList: afterList,
            emptyStateDescription: emptyStateDescription
        }) : /*#__PURE__*/ _react.default.createElement(_Selectstyles.ListWrapper, {
            ref: listWrapperRef,
            listWidth: listWidth
        }, /*#__PURE__*/ _react.default.createElement(_Selectstyles.Ul, {
            role: "tree",
            id: `${treeId}_tree_level_1`,
            "aria-multiselectable": Boolean(multiselect),
            listMaxHeight: listMaxHeight,
            onScroll: virtual ? undefined : onScroll,
            virtual: virtual
        }, beforeList, multiselect && selectAllOptions && /*#__PURE__*/ _react.default.createElement(_ui.SelectAll, {
            selectAllOptions: selectAllOptions,
            variant: variant
        }), (0, _utils.isEmpty)(transformedItems) ? /*#__PURE__*/ _react.default.createElement(_Selectstyles.StyledEmptyState, {
            className: _Selecttokens.classes.emptyStateWrapper,
            description: emptyStateDescription || 'Ничего не найдено'
        }) : /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, virtual ? /*#__PURE__*/ _react.default.createElement(_ui.VirtualList, {
            items: transformedItems,
            listMaxHeight: listMaxHeight,
            onScroll: onScroll
        }) : transformedItems.map((item, index)=>/*#__PURE__*/ _react.default.createElement(_ui.Inner, {
                key: `${index}/0`,
                item: item,
                currentLevel: 0,
                path: path,
                dispatchPath: dispatchPath,
                index: index,
                listWidth: listWidth,
                portal: listWrapperRef,
                shift: shift,
                flip: flip
            }))), afterList))))));
    });
const selectConfig = {
    name: 'Select',
    tag: 'div',
    layout: selectRoot,
    base: _Selectstyles.base,
    variations: {},
    defaults: {
        view: 'default',
        size: 'm',
        labelPlacement: 'outer',
        chipView: 'default',
        hintView: 'default',
        hintSize: 'm'
    }
};
