"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 dropdownConfig () {
        return dropdownConfig;
    },
    get dropdownRoot () {
        return dropdownRoot;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../utils");
var _utils1 = require("../../utils");
var _hooks = require("../../hooks");
var _pathReducer = require("./reducers/pathReducer");
var _focusedPathReducer = require("./reducers/focusedPathReducer");
var _ui = require("./ui");
var _base = require("./variations/_view/base");
var _base1 = require("./variations/_size/base");
var _Dropdownstyles = require("./Dropdown.styles");
var _utils2 = require("./utils");
var _Dropdowntokens = require("./Dropdown.tokens");
var _useKeyboardNavigation = require("./hooks/useKeyboardNavigation");
var _useHashMaps = require("./hooks/useHashMaps");
var _FloatingPopover = require("./FloatingPopover");
var _Dropdowncontext = require("./Dropdown.context");
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 dropdownRoot = function dropdownRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), items = _ref2.items, children = _ref2.children, placement = _ref2.placement, offset = _ref2.offset, _ref_closeOnOverlayClick = _ref2.closeOnOverlayClick, closeOnOverlayClick = _ref_closeOnOverlayClick === void 0 ? true : _ref_closeOnOverlayClick, onToggle = _ref2.onToggle, size = _ref2.size, view = _ref2.view, _ref_itemRole = _ref2.itemRole, itemRole = _ref_itemRole === void 0 ? 'treeitem' : _ref_itemRole, className = _ref2.className, listMaxHeight = _ref2.listMaxHeight, listWidth = _ref2.listWidth, listHeight = _ref2.listHeight, _ref_closeOnSelect = _ref2.closeOnSelect, closeOnSelect = _ref_closeOnSelect === void 0 ? true : _ref_closeOnSelect, onHover = _ref2.onHover, onItemSelect = _ref2.onItemSelect, onItemClick = _ref2.onItemClick, _ref_trigger = _ref2.trigger, trigger = _ref_trigger === void 0 ? 'click' : _ref_trigger, _ref_openByRightClick = _ref2.openByRightClick, openByRightClick = _ref_openByRightClick === void 0 ? false : _ref_openByRightClick, _ref_variant = _ref2.variant, variant = _ref_variant === void 0 ? 'normal' : _ref_variant, _ref_hasArrow = _ref2.hasArrow, hasArrow = _ref_hasArrow === void 0 ? true : _ref_hasArrow, _ref_alwaysOpened = _ref2.alwaysOpened, alwaysOpened = _ref_alwaysOpened === void 0 ? false : _ref_alwaysOpened, portal = _ref2.portal, renderItem = _ref2.renderItem, zIndex = _ref2.zIndex, beforeList = _ref2.beforeList, afterList = _ref2.afterList, rest = _object_without_properties(_ref2, [
            "items",
            "children",
            "placement",
            "offset",
            "closeOnOverlayClick",
            "onToggle",
            "size",
            "view",
            "itemRole",
            "className",
            "listMaxHeight",
            "listWidth",
            "listHeight",
            "closeOnSelect",
            "onHover",
            "onItemSelect",
            "onItemClick",
            "trigger",
            "openByRightClick",
            "variant",
            "hasArrow",
            "alwaysOpened",
            "portal",
            "renderItem",
            "zIndex",
            "beforeList",
            "afterList"
        ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
        var _getItemByFocused;
        var initialPath = alwaysOpened ? [
            'root'
        ] : [];
        var _useReducer = _sliced_to_array((0, _react.useReducer)(_pathReducer.pathReducer, initialPath), 2), path = _useReducer[0], dispatchPath = _useReducer[1];
        var _useReducer1 = _sliced_to_array((0, _react.useReducer)(_focusedPathReducer.focusedPathReducer, []), 2), focusedPath = _useReducer1[0], dispatchFocusedPath = _useReducer1[1];
        var isCurrentListOpen = Boolean(path[0]);
        var _useHashMaps1 = _sliced_to_array((0, _useHashMaps.useHashMaps)(items), 2), pathMap = _useHashMaps1[0], focusedToValueMap = _useHashMaps1[1];
        var activeDescendantItemValue = ((_getItemByFocused = (0, _utils2.getItemByFocused)(focusedPath, focusedToValueMap)) === null || _getItemByFocused === void 0 ? void 0 : _getItemByFocused.value) || '';
        var floatingPopoverRef = (0, _react.useRef)(null);
        var listWrapperRef = (0, _react.useRef)(null);
        var treeId = (0, _utils.safeUseId)();
        /* Логика работы при клике за пределами выпадающего списка */ (0, _hooks.useOutsideClick)(function(event) {
            if (!isCurrentListOpen || !closeOnOverlayClick || alwaysOpened) {
                return;
            }
            dispatchPath({
                type: 'reset'
            });
            dispatchFocusedPath({
                type: 'reset'
            });
            if (onToggle) {
                onToggle(false, event);
            }
        }, [
            floatingPopoverRef,
            listWrapperRef
        ]);
        var handleGlobalToggle = function handleGlobalToggle(opened, event) {
            if (alwaysOpened || opened) {
                dispatchPath({
                    type: 'opened_first_level'
                });
            } else {
                dispatchFocusedPath({
                    type: 'reset'
                });
                dispatchPath({
                    type: 'reset'
                });
            }
            if (onToggle) {
                onToggle(opened, event);
            }
        };
        var onContextMenu = (0, _react.useCallback)(function(e) {
            e.preventDefault();
            if (alwaysOpened) {
                return;
            }
            handleGlobalToggle(!isCurrentListOpen, e);
        }, [
            handleGlobalToggle,
            isCurrentListOpen,
            alwaysOpened
        ]);
        var onKeyDown = (0, _useKeyboardNavigation.useKeyNavigation)({
            focusedPath: focusedPath,
            dispatchFocusedPath: dispatchFocusedPath,
            path: path,
            dispatchPath: dispatchPath,
            pathMap: pathMap,
            focusedToValueMap: focusedToValueMap,
            handleGlobalToggle: handleGlobalToggle,
            closeOnSelect: closeOnSelect,
            onItemSelect: onItemSelect,
            onItemClick: onItemClick
        }).onKeyDown;
        return /*#__PURE__*/ _react.default.createElement(_Dropdowncontext.Context.Provider, {
            value: {
                focusedPath: focusedPath,
                size: size,
                variant: variant,
                itemRole: itemRole,
                handleGlobalToggle: handleGlobalToggle,
                closeOnSelect: closeOnSelect,
                onHover: onHover,
                onItemClick: onItemClick,
                onItemSelect: onItemSelect,
                hasArrow: hasArrow,
                treeId: treeId,
                renderItem: renderItem
            }
        }, /*#__PURE__*/ _react.default.createElement(_FloatingPopover.FloatingPopover, {
            ref: floatingPopoverRef,
            opened: isCurrentListOpen,
            onToggle: handleGlobalToggle,
            placement: (0, _utils2.getPlacement)(placement),
            offset: offset,
            portal: portal,
            trigger: trigger,
            target: (0, _utils2.childrenWithProps)(children, {
                role: 'combobox',
                'aria-controls': "".concat(treeId, "_tree_level_1"),
                'aria-expanded': isCurrentListOpen,
                'aria-activedescendant': activeDescendantItemValue ? (0, _utils2.getItemId)(treeId, activeDescendantItemValue.toString()) : '',
                onKeyDown: onKeyDown,
                onContextMenu: openByRightClick ? onContextMenu : undefined
            }),
            zIndex: zIndex,
            isInner: false
        }, /*#__PURE__*/ _react.default.createElement(Root, _object_spread({
            className: (0, _utils1.cx)(className, _Dropdowntokens.classes.dropdownRoot),
            ref: ref,
            view: view,
            size: size
        }, rest), /*#__PURE__*/ _react.default.createElement(_Dropdownstyles.ListWrapper, {
            ref: listWrapperRef,
            listWidth: listWidth
        }, /*#__PURE__*/ _react.default.createElement(_Dropdownstyles.Ul, {
            id: "".concat(treeId, "_tree_level_1"),
            role: "tree",
            listMaxHeight: listMaxHeight || listHeight
        }, beforeList, items.map(function(item, index) {
            return /*#__PURE__*/ _react.default.createElement(_ui.DropdownInner, {
                key: "".concat(index, "/0"),
                item: item,
                currentLevel: 0,
                trigger: trigger,
                path: path,
                dispatchPath: dispatchPath,
                index: index,
                listWidth: listWidth,
                portal: listWrapperRef
            });
        }), afterList)))));
    });
};
var dropdownConfig = {
    name: 'Dropdown',
    tag: 'div',
    layout: dropdownRoot,
    base: _Dropdownstyles.base,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
