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;
};
import React from 'react';
import invariant from 'invariant';
import { getRandomID, isNonNullable } from '../../lib/utils.js';
import { Radio } from '../Radio/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { FocusTrap } from '../../internal/FocusTrap/index.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { getVisualStateDataAttributes } from '../../internal/CommonWrapper/utils/getVisualStateDataAttributes.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './RadioGroup.styles.js';
import { Prevent } from './Prevent.js';
import { RadioGroupContext } from './RadioGroupContext.js';
export var RadioGroupDataTids = {
    root: 'RadioGroup__root',
};
/** Группирует радиокнопки. Контейнер для компонента [Radio](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-radio--docs). */
var RadioGroup = /** @class */ (function (_super) {
    __extends(RadioGroup, _super);
    function RadioGroup(props) {
        var _this = _super.call(this, props) || this;
        _this.name = getRandomID();
        _this.getProps = createPropsGetter(RadioGroup_1.defaultProps);
        _this.getRadioGroupContextValue = function () {
            return {
                activeItem: _this.getValue(),
                onSelect: _this.handleSelect,
                name: _this.getName(),
                disabled: _this.props.disabled,
                error: _this.props.error,
                warning: _this.props.warning,
            };
        };
        _this.getValue = function () { return (_this.isControlled() ? _this.props.value : _this.state.activeItem); };
        _this.getName = function () { return _this.props.name || _this.name; };
        _this.isControlled = function () { return isNonNullable(_this.props.value); };
        _this.handleSelect = function (value) {
            if (!_this.isControlled()) {
                _this.setState({ activeItem: value });
            }
            if (_this.props.onValueChange) {
                _this.props.onValueChange(value);
            }
        };
        _this.renderRadio = function (itemValue, data, index) {
            var _a;
            var itemProps = {
                key: _this.getKeyByItem(itemValue),
                className: _this.cx((_a = {},
                    _a[_this.styles.item()] = true,
                    _a[_this.styles.itemFirst()] = index === 0,
                    _a[_this.styles.itemInline()] = !!_this.props.inline,
                    _a)),
            };
            return (React.createElement("span", __assign({}, itemProps, { role: "presentation" }),
                React.createElement(Radio, { value: itemValue }, _this.getProps().renderItem(itemValue, data))));
        };
        _this.getKeyByItem = function (itemValue) {
            if (_this.props.toKey) {
                return _this.props.toKey(itemValue);
            }
            return typeof itemValue === 'string' || typeof itemValue === 'number' ? itemValue : undefined;
        };
        _this.ref = function (element) {
            _this.node = element;
        };
        _this.state = {
            activeItem: _this.props.defaultValue,
        };
        return _this;
    }
    RadioGroup_1 = RadioGroup;
    RadioGroup.prototype.render = function () {
        var _a;
        var _b = this.props, width = _b.width, onMouseLeave = _b.onMouseLeave, onMouseOver = _b.onMouseOver, onMouseEnter = _b.onMouseEnter, onBlur = _b.onBlur, ariaDescribedby = _b["aria-describedby"], disabled = _b.disabled;
        var style = {
            width: width !== null && width !== void 0 ? width : 'auto',
        };
        var handlers = {
            onMouseOver: onMouseOver,
            onMouseEnter: onMouseEnter,
            onMouseLeave: onMouseLeave,
        };
        this.styles = getStyles(this.emotion);
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props, getVisualStateDataAttributes({ disabled: disabled })),
            React.createElement(FocusTrap, { onBlur: onBlur },
                React.createElement("span", __assign({ "data-tid": RadioGroupDataTids.root, ref: this.ref, style: style, className: this.cx((_a = {},
                        _a[this.styles.root()] = true,
                        _a)), role: "radiogroup" }, handlers, { "aria-describedby": ariaDescribedby }),
                    React.createElement(RadioGroupContext.Provider, { value: this.getRadioGroupContextValue() }, this.renderChildren())))));
    };
    /** Программно устанавливает фокус на радиокнопку. Появляется фокусная обводка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
     * @public
     */
    RadioGroup.prototype.focus = function () {
        var node = this.node;
        if (!node) {
            return;
        }
        var radio = node.querySelector('input[type="radio"]:checked');
        // If no checked radios, try get first radio
        if (!radio || radio.disabled) {
            radio = node.querySelector('input[type="radio"]:not([disabled])');
        }
        if (radio) {
            radio.focus();
        }
    };
    RadioGroup.prototype.renderChildren = function () {
        var _a = this.props, items = _a.items, children = _a.children;
        invariant((!items && children) || (items && !children), 'Either items or children must be passed, not both');
        return items ? mapItems(this.renderRadio, items) : children;
    };
    var RadioGroup_1;
    RadioGroup.__KONTUR_REACT_UI__ = 'RadioGroup';
    RadioGroup.displayName = 'RadioGroup';
    RadioGroup.defaultProps = {
        renderItem: renderItem,
    };
    RadioGroup.Prevent = Prevent;
    RadioGroup = RadioGroup_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], RadioGroup);
    return RadioGroup;
}(React.Component));
export { RadioGroup };
function renderItem(_value, data) {
    return data;
}
function mapItems(fn, items) {
    var result = [];
    var index = 0;
    for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
        var entry = items_1[_i];
        var _a = normalizeEntry(entry), value = _a[0], data = _a[1];
        result.push(fn(value, data, index));
        ++index;
    }
    return result;
}
function normalizeEntry(entry) {
    if (!Array.isArray(entry)) {
        return [entry, entry];
    }
    return entry;
}
//# sourceMappingURL=RadioGroup.js.map