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 _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);
}
import React, { forwardRef, useCallback, useMemo, useState, useEffect, useRef } from "react";
import { safeUseId, cx } from "../../../../utils";
import { IconDisclosureLeftWithOffset, IconDisclosureRightWithOffset, IconDisclosureDownWithOffset, IconDisclosureUpWithOffset } from "../../../_Icon";
import { classes, tokens } from "../../tokens";
import { useSegmentInner } from "../../SegmentProvider/SegmentProvider";
import { base as sizeCSS } from "./variations/_size/base";
import { base as viewCSS } from "./variations/_view/base";
import { base as disabledCSS } from "./variations/_disabled/base";
import { base as pilledCSS } from "./variations/_pilled/base";
import { base as filledBackgroundCSS } from "./variations/_filledBackgound/base";
import { base as stretchCSS } from "./variations/_stretch/base";
import { base as orientationCSS } from "./variations/_orientation/base";
import { StyledContent, StyledContentWrapper, base, StyledLeftArrow, StyledRightArrow, StyledTopArrow, StyledBottomArrow } from "./SegmentGroup.styles";
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 || {});
export var getChildNodes = function getChildNodes(wrapper) {
    var container = wrapper === null || wrapper === void 0 ? void 0 : wrapper.firstChild;
    return container ? Array.from(container === null || container === void 0 ? void 0 : container.childNodes) : [];
};
export var segmentGroupRoot = function segmentGroupRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(props, outerRef) {
        var id = props.id, selectionMode = props.selectionMode, pilled = props.pilled, stretch = props.stretch, _props_clip = props.clip, clip = _props_clip === void 0 ? true : _props_clip, _props_orientation = props.orientation, orientation = _props_orientation === void 0 ? 'horizontal' : _props_orientation, _props_filledBackground = props.filledBackground, filledBackground = _props_filledBackground === void 0 ? false : _props_filledBackground, _props_hasBackground = props.hasBackground, hasBackground = _props_hasBackground === void 0 ? false : _props_hasBackground, _props_disabled = props.disabled, disabled = _props_disabled === void 0 ? false : _props_disabled, size = props.size, view = props.view, children = props.children, rest = _object_without_properties(props, [
            "id",
            "selectionMode",
            "pilled",
            "stretch",
            "clip",
            "orientation",
            "filledBackground",
            "hasBackground",
            "disabled",
            "size",
            "view",
            "children"
        ]);
        var scrollRef = useRef(null);
        var trackRef = useRef(null);
        var leftArrowRef = useRef(null);
        var _useSegmentInner = useSegmentInner(), setSelectionMode = _useSegmentInner.setSelectionMode, setDisabledGroup = _useSegmentInner.setDisabledGroup;
        var _useState = _sliced_to_array(useState(true), 2), firstItemVisible = _useState[0], setFirstItemVisible = _useState[1];
        var _useState1 = _sliced_to_array(useState(true), 2), lastItemVisible = _useState1[0], setLastItemVisible = _useState1[1];
        var uniqId = safeUseId();
        var segmentGroupId = id || uniqId;
        var canClip = clip && !stretch;
        var isVertical = orientation === 'vertical';
        var stretchClass = (clip ? firstItemVisible && lastItemVisible : true) && stretch ? classes.segmentStretch : undefined;
        var orientationClass = isVertical ? classes.segmentVertical : undefined;
        var clipScrollClass = canClip ? classes.segmentGroupClipScroll : undefined;
        var pilledAttr = (view !== 'clear' || hasBackground) && pilled;
        var filledBackgroundAttr = view !== 'clear' && filledBackground || hasBackground;
        var pilledClass = pilledAttr ? classes.segmentPilled : undefined;
        var filledClass = filledBackgroundAttr ? classes.segmentGroupFilledBackground : undefined;
        var onPrev = useCallback(function() {
            if (disabled || !scrollRef.current) {
                return;
            }
            var childNodes = getChildNodes(scrollRef.current);
            var scrollLeft = Math.round(scrollRef.current.scrollLeft);
            var firstOverflowingTab = childNodes.slice().reverse().find(function(child) {
                if (!child || child.offsetLeft === undefined) {
                    return;
                }
                var tabStartX = child.offsetLeft;
                return tabStartX < scrollLeft;
            });
            firstOverflowingTab === null || firstOverflowingTab === void 0 ? void 0 : firstOverflowingTab.scrollIntoView({
                block: 'nearest',
                inline: 'nearest'
            });
        }, [
            disabled,
            scrollRef
        ]);
        var onNext = useCallback(function() {
            if (disabled || !scrollRef.current) {
                return;
            }
            var scrollRight = Math.round(scrollRef.current.scrollLeft + scrollRef.current.clientWidth);
            var childNodes = getChildNodes(scrollRef.current);
            var lastOverflowingChild = childNodes.find(function(child) {
                if (!child || child.offsetLeft === undefined) {
                    return;
                }
                var tabEndX = child.offsetLeft + child.offsetWidth;
                return tabEndX > scrollRight;
            });
            lastOverflowingChild === null || lastOverflowingChild === void 0 ? void 0 : lastOverflowingChild.scrollIntoView({
                block: 'nearest',
                inline: 'nearest'
            });
        }, [
            disabled,
            scrollRef
        ]);
        var onKeyDown = useCallback(function(event) {
            var childNodes = getChildNodes(scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current);
            var index = childNodes.findIndex(function(child) {
                return document.activeElement === child;
            });
            var minIndex = 0;
            var maxIndex = childNodes.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 _childNodes_nextIndex, _childNodes_nextIndex1;
                event.preventDefault();
                (_childNodes_nextIndex = childNodes[nextIndex]) === null || _childNodes_nextIndex === void 0 ? void 0 : _childNodes_nextIndex.focus();
                (_childNodes_nextIndex1 = childNodes[nextIndex]) === null || _childNodes_nextIndex1 === void 0 ? void 0 : _childNodes_nextIndex1.scrollIntoView({
                    block: 'center',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, []);
        var handleScroll = useCallback(function(event) {
            var _event_stopPropagation;
            (_event_stopPropagation = event.stopPropagation) === null || _event_stopPropagation === void 0 ? void 0 : _event_stopPropagation.call(event);
            if (!canClip) {
                setFirstItemVisible(true);
                setLastItemVisible(true);
                return;
            }
            if (isVertical) {
                var maxScrollTop = event.currentTarget.scrollHeight - event.currentTarget.clientHeight;
                var scrollTop = Math.round(event.currentTarget.scrollTop);
                setFirstItemVisible(scrollTop <= 0);
                setLastItemVisible(scrollTop >= maxScrollTop);
                return;
            }
            var maxScrollLeft = event.currentTarget.scrollWidth - event.currentTarget.clientWidth;
            var scrollLeft = Math.round(event.currentTarget.scrollLeft);
            setFirstItemVisible(scrollLeft <= 0);
            setLastItemVisible(scrollLeft >= maxScrollLeft);
        }, [
            isVertical,
            canClip
        ]);
        useEffect(function() {
            handleScroll({
                currentTarget: scrollRef.current
            });
        }, [
            handleScroll
        ]);
        useEffect(function() {
            var _scrollRef_current, _scrollRef_current1, _scrollRef_current2, _scrollRef_current3;
            if (!canClip) {
                setLastItemVisible(true);
                return;
            }
            setLastItemVisible(isVertical ? ((_scrollRef_current = scrollRef.current) === null || _scrollRef_current === void 0 ? void 0 : _scrollRef_current.scrollHeight) === ((_scrollRef_current1 = scrollRef.current) === null || _scrollRef_current1 === void 0 ? void 0 : _scrollRef_current1.clientHeight) : ((_scrollRef_current2 = scrollRef.current) === null || _scrollRef_current2 === void 0 ? void 0 : _scrollRef_current2.scrollWidth) === ((_scrollRef_current3 = scrollRef.current) === null || _scrollRef_current3 === void 0 ? void 0 : _scrollRef_current3.clientWidth));
        }, [
            isVertical,
            canClip
        ]);
        // Этот хук компенсирует появление левой/верхней стрелки при прокрутке
        useEffect(function() {
            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
        ]);
        var PreviousButton = useMemo(function() {
            var ArrowNode = isVertical ? StyledTopArrow : StyledLeftArrow;
            return /*#__PURE__*/ React.createElement(ArrowNode, {
                type: "button",
                "aria-label": "Предыдущий сегмент",
                onClick: onPrev,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled
            }, isVertical ? /*#__PURE__*/ React.createElement(IconDisclosureUpWithOffset, {
                color: "var(".concat(tokens.arrowColor, ")"),
                size: "s"
            }) : /*#__PURE__*/ React.createElement(IconDisclosureLeftWithOffset, {
                color: "var(".concat(tokens.arrowColor, ")")
            }));
        }, [
            onPrev,
            isVertical
        ]);
        var NextButton = useMemo(function() {
            var ArrowNode = isVertical ? StyledBottomArrow : StyledRightArrow;
            return /*#__PURE__*/ React.createElement(ArrowNode, {
                type: "button",
                "aria-label": "Следующий сегмент",
                onClick: onNext,
                tabIndex: disabled ? -1 : 0,
                disabled: disabled
            }, isVertical ? /*#__PURE__*/ React.createElement(IconDisclosureDownWithOffset, {
                color: "var(".concat(tokens.arrowColor, ")"),
                size: "s"
            }) : /*#__PURE__*/ React.createElement(IconDisclosureRightWithOffset, {
                color: "var(".concat(tokens.arrowColor, ")")
            }));
        }, [
            onNext,
            isVertical
        ]);
        useEffect(function() {
            selectionMode && setSelectionMode(selectionMode);
            setDisabledGroup(disabled);
        }, [
            selectionMode,
            disabled
        ]);
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            view: view,
            size: size,
            orientation: orientation,
            id: segmentGroupId,
            ref: outerRef,
            filledBackground: filledBackgroundAttr,
            disabled: disabled,
            pilled: pilledAttr,
            className: cx(pilledClass, filledClass, stretchClass, orientationClass),
            onKeyDown: onKeyDown
        }, rest), !firstItemVisible && PreviousButton, /*#__PURE__*/ React.createElement(StyledContentWrapper, {
            className: cx(clipScrollClass),
            ref: scrollRef,
            onScroll: handleScroll
        }, /*#__PURE__*/ React.createElement(StyledContent, {
            ref: trackRef
        }, children)), !lastItemVisible && NextButton);
    });
};
export var segmentGroupConfig = {
    name: 'SegmentGroup',
    tag: 'div',
    layout: segmentGroupRoot,
    base: base,
    variations: {
        size: {
            css: sizeCSS
        },
        view: {
            css: viewCSS
        },
        disabled: {
            css: disabledCSS,
            attrs: true
        },
        pilled: {
            css: pilledCSS,
            attrs: true
        },
        stretch: {
            css: stretchCSS,
            attrs: true
        },
        orientation: {
            css: orientationCSS
        },
        filledBackground: {
            css: filledBackgroundCSS,
            attrs: true
        }
    },
    defaults: {
        view: 'clear',
        size: 'xs'
    }
};
