"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;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../../../../utils");
const _Icon = require("../../../../_Icon");
const _tokens = require("../../../tokens");
const _TabsContext = require("../../../TabsContext");
const _utils1 = require("../../../utils");
const _base = require("./variations/_size/base");
const _base1 = require("./variations/_view/base");
const _base2 = require("./variations/_disabled/base");
const _base3 = require("./variations/_pilled/base");
const _base4 = require("./variations/_stretch/base");
const _HorizontalTabsstyles = require("./HorizontalTabs.styles");
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["left"] = 37] = "left";
    Keys[Keys["right"] = 39] = "right";
    return Keys;
}(Keys || {});
const getIconSize = (size)=>{
    return size === 'h1' || size === 'h2' ? 'm' : 's';
};
const horizontalTabsRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, outerRef)=>{
        const { id, stretch = false, disabled = false, clip = 'scroll', size, view, children, pilled = false, index, className, 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 isFilled = view === 'filled'; // outer padding is only for filled view
        const pilledAttr = view !== 'clear' && pilled;
        const pilledClass = pilledAttr ? _tokens.classes.tabsPilled : undefined;
        const noDividerClass = !hasDivider ? _tokens.classes.tabsNoDivider : undefined;
        const stretchClass = firstItemVisible && lastItemVisible && stretch ? _tokens.classes.tabsStretch : undefined;
        const hasLeftArrowClass = !firstItemVisible ? _tokens.classes.tabsHasLeftArrow : undefined;
        const hasRightArrowClass = !lastItemVisible ? _tokens.classes.tabsHasRightArrow : 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 leftArrowRef = (0, _react.useRef)(null);
        const onPrev = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const { scrollLeft } = scrollRef.current;
            const firstOverflowingTab = (0, _utils1.getFirstOverflowingTab)(refs.items.slice().reverse(), scrollLeft, rest.orientation);
            if (!firstOverflowingTab?.current) {
                return;
            }
            const scrollElStyle = getComputedStyle(scrollRef.current);
            scrollRef.current.scrollTo({
                left: firstOverflowingTab.current.offsetLeft - parseInt(scrollElStyle.paddingLeft, 10)
            });
        }, [
            disabled,
            scrollRef,
            refs
        ]);
        const onNext = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
            const lastOverflowingTab = (0, _utils1.getLastOverflowingTab)(refs.items, scrollRight, rest.orientation);
            if (!lastOverflowingTab?.current) {
                return;
            }
            if (firstItemVisible) {
                setShouldTriggerAdditionalScroll(true);
            }
            const 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
        ]);
        const PreviousButton = (0, _react.useMemo)(()=>/*#__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
        ]);
        const NextButton = (0, _react.useMemo)(()=>/*#__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
        ]);
        const handleScroll = (0, _react.useCallback)((event)=>{
            event.stopPropagation();
            const scrollElStyle = getComputedStyle(event.currentTarget);
            const minScrollLeft = parseInt(scrollElStyle.paddingLeft, 10);
            const maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth - parseInt(scrollElStyle.paddingRight, 10);
            const scrollLeft = Math.round(event.currentTarget.scrollLeft);
            setFirstItemVisible(scrollLeft <= minScrollLeft);
            setLastItemVisible(scrollLeft >= maxScrollLeft);
        }, [
            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 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) {
                event.preventDefault();
                refs.items[nextIndex].current?.focus();
                refs.items[nextIndex].current?.scrollIntoView({
                    block: 'nearest',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, [
            index
        ]);
        (0, _react.useLayoutEffect)(()=>{
            setLastItemVisible(scrollRef.current?.scrollWidth === scrollRef.current?.clientWidth);
        }, [
            clip
        ]);
        // Этот хук компенсирует появление левой стрелки при прокрутке
        (0, _react.useLayoutEffect)(()=>{
            if (firstItemVisible || !shouldTriggerAdditionalScroll || !scrollRef.current || !leftArrowRef.current) {
                return;
            }
            const 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, {
            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));
    });
const 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'
    }
};
