"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 verticalTabsConfig () {
        return verticalTabsConfig;
    },
    get verticalTabsRoot () {
        return verticalTabsRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../../../../utils");
const _tokens = require("../../../tokens");
const _TabsContext = require("../../../TabsContext");
const _Icon = require("../../../../_Icon");
const _utils1 = require("../../../utils");
const _VerticalTabsstyles = require("./VerticalTabs.styles");
const _base = require("./variations/_size/base");
const _base1 = require("./variations/_view/base");
const _base2 = require("./variations/_disabled/base");
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;
}
var Keys = /*#__PURE__*/ function(Keys) {
    Keys[Keys["end"] = 35] = "end";
    Keys[Keys["home"] = 36] = "home";
    Keys[Keys["up"] = 38] = "up";
    Keys[Keys["down"] = 40] = "down";
    return Keys;
}(Keys || {});
const verticalTabsRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, outerRef)=>{
        const { id, disabled = false, clip = 'showAll', size, view, children, index, className, orientation, hasDivider = true, ...rest } = props;
        const [firstItemVisible, setFirstItemVisible] = (0, _react.useState)(true);
        const [lastItemVisible, setLastItemVisible] = (0, _react.useState)(false);
        // Триггер доп. скролла при появлении левой стрелки, которая отъедает ширину scroll-контейнера
        const [shouldTriggerAdditionalScroll, setShouldTriggerAdditionalScroll] = (0, _react.useState)(false);
        const refs = (0, _react.useMemo)(()=>new _TabsContext.TabItemRefs(index), []);
        const uniqId = (0, _utils.safeUseId)();
        const tabsId = id || uniqId;
        const noDividerClass = !hasDivider ? _tokens.classes.tabsNoDivider : undefined;
        const hasTopArrowClass = !firstItemVisible ? _tokens.classes.tabsHasTopArrow : undefined;
        const hasBottomArrowClass = !lastItemVisible ? _tokens.classes.tabsHasBottomArrow : undefined;
        const clipScrollClass = clip === 'scroll' ? _tokens.classes.tabsClipScroll : undefined;
        const clipShowAllClass = clip === 'showAll' ? _tokens.classes.tabsClipShowAll : undefined;
        const scrollRef = (0, _react.useRef)(null);
        const trackRef = (0, _react.useRef)(null);
        const upArrowRef = (0, _react.useRef)(null);
        const onPrev = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const { scrollTop } = scrollRef.current;
            const firstOverflowingTab = (0, _utils1.getFirstOverflowingTab)(refs.items.slice().reverse(), scrollTop, orientation);
            if (!firstOverflowingTab?.current) {
                return;
            }
            const scrollElStyle = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                top: firstOverflowingTab.current.offsetTop - parseInt(scrollElStyle.paddingTop, 10)
            });
        }, [
            disabled,
            scrollRef,
            refs
        ]);
        const onNext = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const scrollBottom = Math.round(scrollRef.current.scrollTop + scrollRef.current.clientHeight);
            const lastOverflowingTab = (0, _utils1.getLastOverflowingTab)(refs.items, scrollBottom, orientation);
            if (!lastOverflowingTab?.current) {
                return;
            }
            if (firstItemVisible) {
                setShouldTriggerAdditionalScroll(true);
            }
            const scrollElStyle = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                top: Math.round(lastOverflowingTab.current.offsetTop + lastOverflowingTab.current.offsetHeight - scrollRef.current.clientHeight + parseInt(scrollElStyle.paddingTop, 10))
            });
        }, [
            firstItemVisible,
            disabled,
            scrollRef,
            refs
        ]);
        const PreviousButton = /*#__PURE__*/ _react.default.createElement(_VerticalTabsstyles.StyledArrow, {
            type: "button",
            "aria-label": "Предыдущий таб",
            onClick: onPrev,
            tabIndex: disabled ? -1 : 0,
            disabled: disabled,
            ref: upArrowRef
        }, /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureLeft, {
            color: "inherit"
        }));
        const NextButton = /*#__PURE__*/ _react.default.createElement(_VerticalTabsstyles.StyledArrow, {
            type: "button",
            "aria-label": "Следующий таб",
            onClick: onNext,
            tabIndex: disabled ? -1 : 0,
            disabled: disabled
        }, /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureRight, {
            color: "inherit"
        }));
        const handleScroll = (0, _react.useCallback)((event)=>{
            event.stopPropagation();
            const scrollElStyle = getComputedStyle(event.currentTarget);
            const minScrollTop = parseInt(scrollElStyle.paddingLeft, 10);
            const maxScrollTop = event.currentTarget.scrollHeight - event.currentTarget.clientHeight - parseInt(scrollElStyle.paddingTop, 10);
            const scrollTop = Math.round(event.currentTarget.scrollTop);
            setFirstItemVisible(scrollTop <= minScrollTop);
            setLastItemVisible(scrollTop >= maxScrollTop);
        }, [
            setFirstItemVisible,
            setLastItemVisible
        ]);
        const onKeyDown = (0, _react.useCallback)((event)=>{
            if (index === undefined) {
                return;
            }
            const minIndex = 0;
            const maxIndex = refs.items.length - 1;
            let nextIndex;
            switch(event.keyCode){
                case 35:
                    nextIndex = maxIndex;
                    break;
                case 38:
                    nextIndex = index > minIndex ? index - 1 : index;
                    break;
                case 40:
                    nextIndex = index < maxIndex ? index + 1 : index;
                    break;
                case 36:
                    nextIndex = minIndex;
                    break;
                default:
                    return;
            }
            if (nextIndex !== index) {
                event.preventDefault();
                refs.items[nextIndex].current?.focus();
                refs.items[nextIndex].current?.scrollIntoView({
                    block: 'nearest',
                    inline: 'nearest',
                    behavior: 'smooth'
                });
            }
        }, [
            index
        ]);
        (0, _react.useLayoutEffect)(()=>{
            setLastItemVisible(scrollRef.current?.scrollHeight === scrollRef.current?.clientHeight);
        }, [
            clip
        ]);
        // Этот хук компенсирует появление верхней стрелки при прокрутке
        (0, _react.useLayoutEffect)(()=>{
            if (firstItemVisible || !shouldTriggerAdditionalScroll || !scrollRef.current || !upArrowRef.current) {
                return;
            }
            const style = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                top: Math.round(scrollRef.current.scrollTop + upArrowRef.current.clientHeight + parseInt(style.paddingTop, 10))
            });
            setShouldTriggerAdditionalScroll(false);
        }, [
            firstItemVisible,
            shouldTriggerAdditionalScroll,
            scrollRef,
            upArrowRef
        ]);
        return /*#__PURE__*/ _react.default.createElement(_TabsContext.TabsContext.Provider, {
            value: refs
        }, /*#__PURE__*/ _react.default.createElement(Root, {
            view: view,
            role: "tablist",
            size: size,
            id: tabsId,
            ref: outerRef,
            disabled: disabled,
            className: (0, _utils.cx)(hasTopArrowClass, hasBottomArrowClass, noDividerClass, className),
            onKeyDown: onKeyDown,
            orientation: orientation,
            ...rest
        }, !firstItemVisible && clip === 'scroll' && PreviousButton, /*#__PURE__*/ _react.default.createElement(_VerticalTabsstyles.StyledContentWrapper, {
            className: (0, _utils.cx)(clipScrollClass, clipShowAllClass),
            ref: scrollRef,
            onScroll: handleScroll
        }, /*#__PURE__*/ _react.default.createElement(_VerticalTabsstyles.StyledContent, {
            ref: trackRef
        }, children)), !lastItemVisible && clip === 'scroll' && NextButton));
    });
const verticalTabsConfig = {
    name: 'VerticalTabs',
    tag: 'div',
    layout: verticalTabsRoot,
    base: _VerticalTabsstyles.base,
    variations: {
        size: {
            css: _base.base
        },
        view: {
            css: _base1.base
        },
        disabled: {
            css: _base2.base,
            attrs: true
        }
    },
    defaults: {
        view: 'divider',
        size: 'xs'
    }
};
