var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import React from 'react';
import { isKeyArrowHorizontal, isKeyArrowLeft, isKeyEnter } from '../../lib/events/keyboard/identifiers.js';
import { getButtonCorners, Group } from '../Group/index.js';
import { Button } from '../Button/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './Switcher.styles.js';
import { getSwitcherTheme } from './switcherTheme.js';
import { mod } from './helpers.js';
export var SwitcherDataTids = {
    root: 'Switcher__root',
};
/**
 * Переключатель `Switcher` — это замена RadioGroup.
 *
 * Не используйте переключатель в качестве навигации, для этого лучше подходят Tabs.
 */
var Switcher = /** @class */ (function (_super) {
    __extends(Switcher, _super);
    function Switcher() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            focusedIndex: null,
        };
        _this.selectItem = function (value) {
            if (_this.props.onValueChange) {
                _this.props.onValueChange(value);
            }
        };
        _this._extractPropsFromItem = function (item) {
            return typeof item === 'object' ? item : { label: item, value: item };
        };
        _this._extractValuesFromItems = function () {
            return _this.props.items.map(function (item) {
                var value = _this._extractPropsFromItem(item).value;
                return value;
            });
        };
        _this._focus = function (index) {
            _this.setState({ focusedIndex: index });
        };
        _this.handleKey = function (e) {
            var focusedIndex = _this.state.focusedIndex;
            if (typeof focusedIndex !== 'number') {
                return;
            }
            if (isKeyEnter(e)) {
                if (_this.props.onValueChange) {
                    var _a = _this._extractPropsFromItem(_this.props.items[focusedIndex]), value = _a.value, buttonProps = _a.buttonProps;
                    if (!(buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.disabled)) {
                        _this.selectItem(value);
                    }
                }
                return;
            }
            if (isKeyArrowHorizontal(e)) {
                e.preventDefault();
                _this.move(isKeyArrowLeft(e));
            }
        };
        _this.move = function (left) {
            var selectedIndex = _this.state.focusedIndex;
            if (typeof selectedIndex !== 'number') {
                return;
            }
            var newFocusedIndex = _this._getNextFocusedIndex(left, selectedIndex);
            _this._focus(newFocusedIndex);
        };
        _this._getNextFocusedIndex = function (left, focusedIndex) {
            var _a = _this.props, items = _a.items, disabled = _a.disabled;
            if (disabled) {
                return focusedIndex;
            }
            for (var i = 1; i < items.length; i++) {
                var index = mod(focusedIndex + (left ? -i : i), items.length);
                var buttonProps = _this._extractPropsFromItem(items[index]).buttonProps;
                if (!(buttonProps === null || buttonProps === void 0 ? void 0 : buttonProps.disabled)) {
                    return index;
                }
            }
            return focusedIndex;
        };
        _this._handleFocus = function () {
            var value = _this.props.value;
            var items = _this._extractValuesFromItems();
            var currentIndex = __spreadArray([], items, true).indexOf(value);
            var index = currentIndex > -1 ? currentIndex : 0;
            _this.setState({ focusedIndex: index });
        };
        _this._handleBlur = function () {
            _this.setState({ focusedIndex: null });
        };
        _this._renderItems = function () {
            var _a = _this.props, items = _a.items, value = _a.value, size = _a.size, width = _a.width, disabled = _a.disabled, role = _a.role, renderItem = _a.renderItem;
            return items.map(function (item, i) {
                var _a = _this._extractPropsFromItem(item), ariaLabel = _a["aria-label"], label = _a.label, itemValue = _a.value, customButtonProps = _a.buttonProps;
                var isChecked = value === itemValue;
                var commonButtonProps = {
                    'aria-checked': isChecked,
                    role: role,
                    checked: isChecked,
                    visuallyFocused: _this.state.focusedIndex === i,
                    onClick: function () {
                        _this.selectItem(itemValue);
                    },
                    disableFocus: true,
                    size: size,
                    disabled: disabled,
                    corners: getButtonCorners(i === 0, i === items.length - 1),
                };
                var buttonProps = __assign(__assign({}, commonButtonProps), customButtonProps);
                if (!buttonProps.width && width) {
                    buttonProps.width = '100%';
                }
                var renderDefault = function () { return _this.renderDefaultItem(label, itemValue, buttonProps, ariaLabel); };
                return renderItem ? renderItem(label, itemValue, buttonProps, renderDefault, ariaLabel) : renderDefault();
            });
        };
        _this.renderDefaultItem = function (label, value, buttonProps, ariaLabel) { return (React.createElement(Button, __assign({ "aria-label": ariaLabel, key: value }, buttonProps), label)); };
        _this.getLabelSizeClassName = function () {
            switch (_this.props.size) {
                case 'large':
                    return _this.styles.captionLarge(_this.theme);
                case 'medium':
                    return _this.styles.captionMedium(_this.theme);
                case 'small':
                default:
                    return _this.styles.captionSmall(_this.theme);
            }
        };
        return _this;
    }
    Switcher.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = getSwitcherTheme(theme);
            return React.createElement(ThemeContext.Provider, { value: _this.theme }, _this.renderMain());
        }));
    };
    Switcher.prototype.renderMain = function () {
        var _a;
        var inputProps = {
            type: 'checkbox',
            onKeyDown: this.handleKey,
            onFocus: this._handleFocus,
            onBlur: this._handleBlur,
            className: this.styles.input(),
        };
        var items = React.createElement(Group, { width: '100%' }, this._renderItems());
        var captionClassName = this.cx(this.styles.caption(this.theme), this.getLabelSizeClassName());
        var wrapperClassName = this.cx(this.styles.wrap(), (_a = {},
            _a[this.styles.error(this.theme)] = this.props.error,
            _a[this.styles.wrapCustomWidth()] = this.props.width !== undefined,
            _a));
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement("div", { "data-tid": SwitcherDataTids.root, className: this.styles.root(), style: { width: this.props.width } },
                this.props.caption ? React.createElement("div", { className: captionClassName }, this.props.caption) : null,
                React.createElement("div", { className: wrapperClassName },
                    React.createElement("input", __assign({}, inputProps)),
                    items))));
    };
    Switcher.__KONTUR_REACT_UI__ = 'Switcher';
    Switcher.displayName = 'Switcher';
    Switcher.defaultProps = {
        role: 'switch',
    };
    Switcher = __decorate([
        withRenderEnvironment,
        rootNode
    ], Switcher);
    return Switcher;
}(React.Component));
export { Switcher };
//# sourceMappingURL=Switcher.js.map