"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 horizontalTabsConfig () {
        return horizontalTabsConfig;
    },
    get horizontalTabsRoot () {
        return horizontalTabsRoot;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../../../../utils");
var _Icon = require("../../../../_Icon");
var _tokens = require("../../../tokens");
var _TabsContext = require("../../../TabsContext");
var _utils1 = require("../../../utils");
var _base = require("./variations/_size/base");
var _base1 = require("./variations/_view/base");
var _base2 = require("./variations/_disabled/base");
var _base3 = require("./variations/_pilled/base");
var _base4 = require("./variations/_stretch/base");
var _HorizontalTabsstyles = require("./HorizontalTabs.styles");
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_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 _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 Keys = /*#__PURE__*/ function(Keys) {
    Keys[Keys["end"] = 35] = "end";
    Keys[Keys["home"] = 36] = "home";
    Keys[Keys["left"] = 37] = "left";
    Keys[Keys["right"] = 39] = "right";
    return Keys;
}(Keys || {});
var getIconSize = function getIconSize(size) {
    return size === 'h1' || size === 'h2' ? 'm' : 's';
};
var horizontalTabsRoot = function horizontalTabsRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(props, outerRef) {
        var id = props.id, _props_stretch = props.stretch, stretch = _props_stretch === void 0 ? false : _props_stretch, _props_disabled = props.disabled, disabled = _props_disabled === void 0 ? false : _props_disabled, _props_clip = props.clip, clip = _props_clip === void 0 ? 'scroll' : _props_clip, size = props.size, view = props.view, children = props.children, _props_pilled = props.pilled, pilled = _props_pilled === void 0 ? false : _props_pilled, index = props.index, className = props.className, _props_hasDivider = props.hasDivider, hasDivider = _props_hasDivider === void 0 ? true : _props_hasDivider, rest = _object_without_properties(props, [
            "id",
            "stretch",
            "disabled",
            "clip",
            "size",
            "view",
            "children",
            "pilled",
            "index",
            "className",
            "hasDivider"
        ]);
        var _useState = _sliced_to_array((0, _react.useState)(true), 2), firstItemVisible = _useState[0], setFirstItemVisible = _useState[1];
        var _useState1 = _sliced_to_array((0, _react.useState)(false), 2), lastItemVisible = _useState1[0], setLastItemVisible = _useState1[1];
        // Триггер доп. скролла при появлении левой стрелки, которая отъедает ширину scroll-контейнера
        var _useState2 = _sliced_to_array((0, _react.useState)(false), 2), shouldTriggerAdditionalScroll = _useState2[0], setShouldTriggerAdditionalScroll = _useState2[1];
        var refs = (0, _react.useMemo)(function() {
            return new _TabsContext.TabItemRefs(index);
        }, []);
        var uniqId = (0, _utils.safeUseId)();
        var tabsId = id || uniqId;
        var isFilled = view === 'filled'; // outer padding is only for filled view
        var pilledAttr = view !== 'clear' && pilled;
        var pilledClass = pilledAttr ? _tokens.classes.tabsPilled : undefined;
        var noDividerClass = !hasDivider ? _tokens.classes.tabsNoDivider : undefined;
        var stretchClass = firstItemVisible && lastItemVisible && stretch ? _tokens.classes.tabsStretch : undefined;
        var hasLeftArrowClass = !firstItemVisible ? _tokens.classes.tabsHasLeftArrow : undefined;
        var hasRightArrowClass = !lastItemVisible ? _tokens.classes.tabsHasRightArrow : undefined;
        var clipScrollClass = clip === 'scroll' ? _tokens.classes.tabsClipScroll : undefined;
        var clipShowAllClass = clip === 'showAll' ? _tokens.classes.tabsClipShowAll : undefined;
        var scrollRef = (0, _react.useRef)(null);
        var trackRef = (0, _react.useRef)(null);
        var leftArrowRef = (0, _react.useRef)(null);
        var onPrev = (0, _react.useCallback)(function() {
            if (disabled || !scrollRef.current) {
                return;
            }
            var scrollLeft = scrollRef.current.scrollLeft;
            var firstOverflowingTab = (0, _utils1.getFirstOverflowingTab)(refs.items.slice().reverse(), scrollLeft, rest.orientation);
            if (!(firstOverflowingTab === null || firstOverflowingTab === void 0 ? void 0 : firstOverflowingTab.current)) {
                return;
            }
            var scrollElStyle = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                left: firstOverflowingTab.current.offsetLeft - parseInt(scrollElStyle.paddingLeft, 10)
            });
        }, [
            disabled,
            scrollRef,
            refs
        ]);
        var onNext = (0, _react.useCallback)(function() {
            if (disabled || !scrollRef.current) {
                return;
            }
            var scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
            var lastOverflowingTab = (0, _utils1.getLastOverflowingTab)(refs.items, scrollRight, rest.orientation);
            if (!(lastOverflowingTab === null || lastOverflowingTab === void 0 ? void 0 : lastOverflowingTab.current)) {
                return;
            }
            if (firstItemVisible) {
                setShouldTriggerAdditionalScroll(true);
            }
            var scrollElStyle = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                left: Math.round(lastOverflowingTab.current.offsetLeft + lastOverflowingTab.current.offsetWidth - scrollRef.current.clientWidth + parseInt(scrollElStyle.paddingRight, 10))
            });
        }, [
            firstItemVisible,
            disabled,
            scrollRef,
            refs
        ]);
        var PreviousButton = (0, _react.useMemo)(function() {
            return /*#__PURE__*/ _react.default.createElement(_HorizontalTabsstyles.StyledArrow, {
                type: "button",
                "aria-label": "Предыдущий таб",
                onClick: onPrev,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled,
                isFilled: isFilled,
                ref: leftArrowRef,
                isLeftArrow: true
            }, /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureLeft, {
                size: getIconSize(size),
                color: "inherit"
            }));
        }, [
            onPrev,
            size,
            disabled,
            isFilled
        ]);
        var NextButton = (0, _react.useMemo)(function() {
            return /*#__PURE__*/ _react.default.createElement(_HorizontalTabsstyles.StyledArrow, {
                type: "button",
                "aria-label": "Следующий таб",
                onClick: onNext,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled,
                isFilled: isFilled
            }, /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureRight, {
                size: getIconSize(size),
                color: "inherit"
            }));
        }, [
            onNext,
            size,
            disabled,
            isFilled
        ]);
        var handleScroll = (0, _react.useCallback)(function(event) {
            event.stopPropagation();
            var scrollElStyle = getComputedStyle(event.currentTarget);
            var minScrollLeft = parseInt(scrollElStyle.paddingLeft, 10);
            var maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth - parseInt(scrollElStyle.paddingRight, 10);
            var scrollLeft = Math.round(event.currentTarget.scrollLeft);
            setFirstItemVisible(scrollLeft <= minScrollLeft);
            setLastItemVisible(scrollLeft >= maxScrollLeft);
        }, [
            setFirstItemVisible,
            setLastItemVisible
        ]);
        var onKeyDown = (0, _react.useCallback)(function(event) {
            if (index === undefined) {
                return;
            }
            var minIndex = 0;
            var maxIndex = refs.items.length - 1;
            var nextIndex;
            switch(event.keyCode){
                case 35:
                    nextIndex = maxIndex;
                    break;
                case 37:
                    nextIndex = index > minIndex ? index - 1 : index;
                    break;
                case 39:
                    nextIndex = index < maxIndex ? index + 1 : index;
                    break;
                case 36:
                    nextIndex = minIndex;
                    break;
                default:
                    return;
            }
            if (nextIndex !== index) {
                var _refs_items_nextIndex_current, _refs_items_nextIndex_current1;
                event.preventDefault();
                (_refs_items_nextIndex_current = refs.items[nextIndex].current) === null || _refs_items_nextIndex_current === void 0 ? void 0 : _refs_items_nextIndex_current.focus();
                (_refs_items_nextIndex_current1 = refs.items[nextIndex].current) === null || _refs_items_nextIndex_current1 === void 0 ? void 0 : _refs_items_nextIndex_current1.scrollIntoView({
                    block: 'nearest',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, [
            index
        ]);
        (0, _react.useLayoutEffect)(function() {
            var _scrollRef_current, _scrollRef_current1;
            setLastItemVisible(((_scrollRef_current = scrollRef.current) === null || _scrollRef_current === void 0 ? void 0 : _scrollRef_current.scrollWidth) === ((_scrollRef_current1 = scrollRef.current) === null || _scrollRef_current1 === void 0 ? void 0 : _scrollRef_current1.clientWidth));
        }, [
            clip
        ]);
        // Этот хук компенсирует появление левой стрелки при прокрутке
        (0, _react.useLayoutEffect)(function() {
            if (firstItemVisible || !shouldTriggerAdditionalScroll || !scrollRef.current || !leftArrowRef.current) {
                return;
            }
            var style = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                left: Math.round(scrollRef.current.scrollLeft + leftArrowRef.current.clientWidth + parseInt(style.paddingLeft, 10))
            });
            setShouldTriggerAdditionalScroll(false);
        }, [
            firstItemVisible,
            shouldTriggerAdditionalScroll,
            scrollRef,
            leftArrowRef
        ]);
        return /*#__PURE__*/ _react.default.createElement(_TabsContext.TabsContext.Provider, {
            value: refs
        }, /*#__PURE__*/ _react.default.createElement(Root, _object_spread({
            view: view,
            role: "tablist",
            // TODO: убрать каст any, когда будут удалены deprecated props
            size: size,
            pilled: pilled,
            id: tabsId,
            ref: outerRef,
            disabled: disabled,
            className: (0, _utils.cx)(pilledClass, stretchClass, hasLeftArrowClass, hasRightArrowClass, noDividerClass, className),
            onKeyDown: onKeyDown
        }, rest), !firstItemVisible && clip === 'scroll' && PreviousButton, /*#__PURE__*/ _react.default.createElement(_HorizontalTabsstyles.StyledContentWrapper, {
            className: (0, _utils.cx)(clipScrollClass, clipShowAllClass),
            ref: scrollRef,
            onScroll: handleScroll
        }, /*#__PURE__*/ _react.default.createElement(_HorizontalTabsstyles.StyledContent, {
            ref: trackRef
        }, children)), !lastItemVisible && clip === 'scroll' && NextButton));
    });
};
var horizontalTabsConfig = {
    name: 'HorizontalTabs',
    tag: 'div',
    layout: horizontalTabsRoot,
    base: _HorizontalTabsstyles.base,
    variations: {
        size: {
            css: _base.base
        },
        view: {
            css: _base1.base
        },
        disabled: {
            css: _base2.base,
            attrs: true
        },
        stretch: {
            css: _base4.base,
            attrs: true
        },
        pilled: {
            css: _base3.base
        }
    },
    defaults: {
        view: 'clear',
        size: 'xs'
    }
};
