"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;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../../../utils");
var _Icon = require("../../../_Icon");
var _tokens = require("../../tokens");
var _SegmentProvider = require("../../SegmentProvider/SegmentProvider");
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/_filledBackgound/base");
var _base5 = require("./variations/_stretch/base");
var _base6 = require("./variations/_orientation/base");
var _SegmentGroupstyles = require("./SegmentGroup.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 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) : [];
};
var segmentGroupRoot = function segmentGroupRoot(Root) {
    return /*#__PURE__*/ (0, _react.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 = (0, _react.useRef)(null);
        var trackRef = (0, _react.useRef)(null);
        var leftArrowRef = (0, _react.useRef)(null);
        var _useSegmentInner = (0, _SegmentProvider.useSegmentInner)(), setSelectionMode = _useSegmentInner.setSelectionMode, setDisabledGroup = _useSegmentInner.setDisabledGroup;
        var _useState = _sliced_to_array((0, _react.useState)(true), 2), firstItemVisible = _useState[0], setFirstItemVisible = _useState[1];
        var _useState1 = _sliced_to_array((0, _react.useState)(true), 2), lastItemVisible = _useState1[0], setLastItemVisible = _useState1[1];
        var uniqId = (0, _utils.safeUseId)();
        var segmentGroupId = id || uniqId;
        var canClip = clip && !stretch;
        var isVertical = orientation === 'vertical';
        var stretchClass = (clip ? firstItemVisible && lastItemVisible : true) && stretch ? _tokens.classes.segmentStretch : undefined;
        var orientationClass = isVertical ? _tokens.classes.segmentVertical : undefined;
        var clipScrollClass = canClip ? _tokens.classes.segmentGroupClipScroll : undefined;
        var pilledAttr = (view !== 'clear' || hasBackground) && pilled;
        var filledBackgroundAttr = view !== 'clear' && filledBackground || hasBackground;
        var pilledClass = pilledAttr ? _tokens.classes.segmentPilled : undefined;
        var filledClass = filledBackgroundAttr ? _tokens.classes.segmentGroupFilledBackground : undefined;
        var onPrev = (0, _react.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 = (0, _react.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 = (0, _react.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 = (0, _react.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
        ]);
        (0, _react.useEffect)(function() {
            handleScroll({
                currentTarget: scrollRef.current
            });
        }, [
            handleScroll
        ]);
        (0, _react.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
        ]);
        // Этот хук компенсирует появление левой/верхней стрелки при прокрутке
        (0, _react.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 = (0, _react.useMemo)(function() {
            var 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(".concat(_tokens.tokens.arrowColor, ")"),
                size: "s"
            }) : /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureLeftWithOffset, {
                color: "var(".concat(_tokens.tokens.arrowColor, ")")
            }));
        }, [
            onPrev,
            isVertical
        ]);
        var NextButton = (0, _react.useMemo)(function() {
            var 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(".concat(_tokens.tokens.arrowColor, ")"),
                size: "s"
            }) : /*#__PURE__*/ _react.default.createElement(_Icon.IconDisclosureRightWithOffset, {
                color: "var(".concat(_tokens.tokens.arrowColor, ")")
            }));
        }, [
            onNext,
            isVertical
        ]);
        (0, _react.useEffect)(function() {
            selectionMode && setSelectionMode(selectionMode);
            setDisabledGroup(disabled);
        }, [
            selectionMode,
            disabled
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, _object_spread({
            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);
    });
};
var 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'
    }
};
