"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 getChildNodes () {
        return getChildNodes;
    },
    get segmentGroupConfig () {
        return segmentGroupConfig;
    },
    get segmentGroupRoot () {
        return segmentGroupRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../../../utils");
const _Icon = require("../../../_Icon");
const _tokens = require("../../tokens");
const _SegmentProvider = require("../../SegmentProvider/SegmentProvider");
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/_filledBackgound/base");
const _base5 = require("./variations/_stretch/base");
const _base6 = require("./variations/_orientation/base");
const _SegmentGroupstyles = require("./SegmentGroup.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 getChildNodes = (wrapper)=>{
    const container = wrapper?.firstChild;
    return container ? Array.from(container?.childNodes) : [];
};
const segmentGroupRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)((props, outerRef)=>{
        const { id, selectionMode, pilled, stretch, clip = true, orientation = 'horizontal', filledBackground = false, hasBackground = false, hasDivider = false, disabled = false, size, view, children, ...rest } = props;
        const scrollRef = (0, _react.useRef)(null);
        const trackRef = (0, _react.useRef)(null);
        const leftArrowRef = (0, _react.useRef)(null);
        const { setSelectionMode, setDisabledGroup, setHasDivider, setOrientation } = (0, _SegmentProvider.useSegmentInner)();
        const [firstItemVisible, setFirstItemVisible] = (0, _react.useState)(true);
        const [lastItemVisible, setLastItemVisible] = (0, _react.useState)(true);
        const uniqId = (0, _utils.safeUseId)();
        const segmentGroupId = id || uniqId;
        const canClip = clip && !stretch;
        const isVertical = orientation === 'vertical';
        const stretchClass = (clip ? firstItemVisible && lastItemVisible : true) && stretch ? _tokens.classes.segmentStretch : undefined;
        const orientationClass = isVertical ? _tokens.classes.segmentVertical : undefined;
        const clipScrollClass = canClip ? _tokens.classes.segmentGroupClipScroll : undefined;
        const pilledAttr = (view !== 'clear' || hasBackground) && pilled;
        const filledBackgroundAttr = view !== 'clear' && filledBackground || hasBackground;
        const pilledClass = pilledAttr ? _tokens.classes.segmentPilled : undefined;
        const filledClass = filledBackgroundAttr ? _tokens.classes.segmentGroupFilledBackground : undefined;
        const onPrev = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const childNodes = getChildNodes(scrollRef.current);
            const scrollLeft = Math.round(scrollRef.current.scrollLeft);
            const firstOverflowingTab = childNodes.slice().reverse().find((child)=>{
                if (!child || child.offsetLeft === undefined) {
                    return;
                }
                const tabStartX = child.offsetLeft;
                return tabStartX < scrollLeft;
            });
            firstOverflowingTab?.scrollIntoView({
                block: 'nearest',
                inline: 'nearest'
            });
        }, [
            disabled,
            scrollRef
        ]);
        const onNext = (0, _react.useCallback)(()=>{
            if (disabled || !scrollRef.current) {
                return;
            }
            const scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
            const childNodes = getChildNodes(scrollRef.current);
            const lastOverflowingChild = childNodes.find((child)=>{
                if (!child || child.offsetLeft === undefined) {
                    return;
                }
                const tabEndX = child.offsetLeft + child.offsetWidth;
                return tabEndX > scrollRight;
            });
            lastOverflowingChild?.scrollIntoView({
                block: 'nearest',
                inline: 'nearest'
            });
        }, [
            disabled,
            scrollRef
        ]);
        const onKeyDown = (0, _react.useCallback)((event)=>{
            const childNodes = getChildNodes(scrollRef?.current);
            const index = childNodes.findIndex((child)=>document.activeElement === child);
            const minIndex = 0;
            const maxIndex = childNodes.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();
                childNodes[nextIndex]?.focus();
                childNodes[nextIndex]?.scrollIntoView({
                    block: 'center',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, []);
        const handleScroll = (0, _react.useCallback)((event)=>{
            event.stopPropagation?.();
            if (!canClip) {
                setFirstItemVisible(true);
                setLastItemVisible(true);
                return;
            }
            if (isVertical) {
                const maxScrollTop = event.currentTarget.scrollHeight - event.currentTarget.clientHeight;
                const scrollTop = Math.round(event.currentTarget.scrollTop);
                setFirstItemVisible(scrollTop <= 0);
                setLastItemVisible(scrollTop >= maxScrollTop);
                return;
            }
            const maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth;
            const scrollLeft = Math.round(event.currentTarget.scrollLeft);
            setFirstItemVisible(scrollLeft <= 0);
            setLastItemVisible(scrollLeft >= maxScrollLeft);
        }, [
            isVertical,
            canClip
        ]);
        (0, _react.useEffect)(()=>{
            handleScroll({
                currentTarget: scrollRef.current
            });
        }, [
            handleScroll
        ]);
        (0, _react.useEffect)(()=>{
            if (!canClip) {
                setLastItemVisible(true);
                return;
            }
            setLastItemVisible(isVertical ? scrollRef.current?.scrollHeight === scrollRef.current?.clientHeight : scrollRef.current?.scrollWidth === scrollRef.current?.clientWidth);
        }, [
            isVertical,
            canClip
        ]);
        // Этот хук компенсирует появление левой/верхней стрелки при прокрутке
        (0, _react.useEffect)(()=>{
            if (firstItemVisible || !scrollRef.current || !leftArrowRef.current) {
                return;
            }
            if (isVertical) {
                scrollRef.current.scrollTo({
                    top: Math.round(scrollRef.current.scrollTop + leftArrowRef.current.clientHeight)
                });
                return;
            }
            scrollRef.current.scrollTo({
                left: Math.round(scrollRef.current.scrollLeft + leftArrowRef.current.clientWidth)
            });
        }, [
            firstItemVisible,
            isVertical
        ]);
        const PreviousButton = (0, _react.useMemo)(()=>{
            const ArrowNode = isVertical ? _SegmentGroupstyles.StyledTopArrow : _SegmentGroupstyles.StyledLeftArrow;
            return /*#__PURE__*/ _react.default.createElement(ArrowNode, {
                type: "button",
                "aria-label": "Предыдущий сегмент",
                onClick: onPrev,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled
            }, isVertical ? /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureUpWithOffset, {
                color: `var(${_tokens.tokens.arrowColor})`,
                size: "s"
            }) : /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureLeftWithOffset, {
                color: `var(${_tokens.tokens.arrowColor})`
            }));
        }, [
            onPrev,
            isVertical
        ]);
        const NextButton = (0, _react.useMemo)(()=>{
            const ArrowNode = isVertical ? _SegmentGroupstyles.StyledBottomArrow : _SegmentGroupstyles.StyledRightArrow;
            return /*#__PURE__*/ _react.default.createElement(ArrowNode, {
                type: "button",
                "aria-label": "Следующий сегмент",
                onClick: onNext,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled
            }, isVertical ? /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureDownWithOffset, {
                color: `var(${_tokens.tokens.arrowColor})`,
                size: "s"
            }) : /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureRightWithOffset, {
                color: `var(${_tokens.tokens.arrowColor})`
            }));
        }, [
            onNext,
            isVertical
        ]);
        (0, _react.useEffect)(()=>{
            selectionMode && setSelectionMode(selectionMode);
            setDisabledGroup(disabled);
            setHasDivider(hasDivider);
            setOrientation(orientation);
        }, [
            selectionMode,
            disabled,
            hasDivider,
            orientation
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            view: view,
            size: size,
            orientation: orientation,
            id: segmentGroupId,
            ref: outerRef,
            filledBackground: filledBackgroundAttr,
            disabled: disabled,
            pilled: pilledAttr,
            className: (0, _utils.cx)(pilledClass, filledClass, stretchClass, orientationClass),
            onKeyDown: onKeyDown,
            ...rest
        }, !firstItemVisible && PreviousButton, /*#__PURE__*/ _react.default.createElement(_SegmentGroupstyles.StyledContentWrapper, {
            className: (0, _utils.cx)(clipScrollClass),
            ref: scrollRef,
            onScroll: handleScroll
        }, /*#__PURE__*/ _react.default.createElement(_SegmentGroupstyles.StyledContent, {
            ref: trackRef
        }, children)), !lastItemVisible && NextButton);
    });
const segmentGroupConfig = {
    name: 'SegmentGroup',
    tag: 'div',
    layout: segmentGroupRoot,
    base: _SegmentGroupstyles.base,
    variations: {
        size: {
            css: _base.base
        },
        view: {
            css: _base1.base
        },
        disabled: {
            css: _base2.base,
            attrs: true
        },
        pilled: {
            css: _base3.base,
            attrs: true
        },
        stretch: {
            css: _base5.base,
            attrs: true
        },
        orientation: {
            css: _base6.base
        },
        filledBackground: {
            css: _base4.base,
            attrs: true
        }
    },
    defaults: {
        view: 'clear',
        size: 'xs'
    }
};
