import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { _ as __decorate, a as __metadata } from './tslib.es6.js';
import { a as ariaBooleanToString } from './aria.js';
import { i as inheritAttributes } from './attributes.js';
import { B as BEM } from './bem.js';
import { d as defaultBalAriaForm } from './form.js';
import { s as stopEventBubbling } from './form-input.js';
import { i as isDescendant, o as hasTagName } from './helpers.js';
import { L as Logger } from './log.js';
import { d as defineCustomElement$3 } from './bal-radio2.js';
import { d as defineCustomElement$2 } from './bal-radio-icon2.js';
import { L as ListenToFocus } from './focus.decorator.js';
import { L as ListenToMutation } from './mutation.decorator.js';

const balRadioGroupCss = ".bal-radio-group{display:inline-block;position:relative;width:100%}.bal-radio-group__inner{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-align:stretch;align-items:stretch;-ms-flex-wrap:wrap;flex-wrap:wrap;gap:var(--bal-space-normal)}.bal-radio-group__inner--button{-ms-flex-direction:column;flex-direction:column;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex:1;flex:1;gap:var(--bal-space-x-small)}@media screen and (min-width: 769px),print{.bal-radio-group__inner--button{-ms-flex-direction:row;flex-direction:row}}.bal-radio-group__inner--expanded{-ms-flex-align:stretch;align-items:stretch}.bal-radio-group__inner--expanded .bal-radio{-ms-flex:1;flex:1}@media screen and (max-width: 768px){.bal-radio-group__inner--expanded .bal-radio{width:100%}}.bal-radio-group__inner--button.bal-radio-group__inner--vertical{gap:var(--bal-space-x-small)}.bal-radio-group__inner--vertical{-ms-flex-direction:column;flex-direction:column;border-radius:var(--bal-radius-normal);gap:0}@media screen and (min-width: 769px),print{.bal-radio-group__inner--vertical{-ms-flex-align:start;align-items:flex-start}}@media screen and (max-width: 768px){.bal-radio-group__inner--vertical-mobile{-ms-flex-direction:column;flex-direction:column;border-radius:var(--bal-radius-normal);gap:0}}";

const RadioGroup = /*@__PURE__*/ proxyCustomElement(class RadioGroup extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.balChange = createEvent(this, "balChange", 7);
        this.balFocus = createEvent(this, "balFocus", 7);
        this.balBlur = createEvent(this, "balBlur", 7);
        this.inputId = `bal-rg-${radioGroupIds++}`;
        this.inheritedAttributes = {};
        this.ariaForm = defaultBalAriaForm;
        /**
         * Defines the layout of the radio button
         */
        this.interface = undefined;
        /**
         * If `true`, the radios can be deselected.
         */
        this.allowEmptySelection = false;
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.inputId;
        /**
         * Displays the checkboxes vertically
         */
        this.vertical = false;
        /**
         * If `true`, the controls will be vertically on mobile devices.
         */
        this.verticalOnMobile = false;
        /**
         * Uses the whole width
         */
        this.expanded = false;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.invalid = undefined;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.disabled = undefined;
        /**
         * If `true` the element can not mutated, meaning the user can not edit the control.
         */
        this.readonly = undefined;
        /**
         * Defines the column size like the grid.
         */
        this.columns = 1;
        /**
         * Defines the column size for tablet and bigger like the grid.
         */
        this.columnsTablet = 1;
        /**
         * Defines the column size for mobile and bigger like the grid.
         */
        this.columnsMobile = 1;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        /**
         * LISTENERS
         * ------------------------------------------------------
         */
        this.hasFocus = false;
        this.mutationObserverActive = true;
        this.onOptionChange = async () => {
            this.setRadioTabindex(this.value);
            this.setRadioChecked();
        };
        /**
         * PRIVATE METHODS
         * ------------------------------------------------------
         */
        this.setRadioTabindex = (value) => {
            const radios = this.getRadios();
            // Get the first radio that is not disabled and the checked one
            const first = radios.find(radio => !radio.disabled);
            const checked = radios.find(radio => radio.value === value && !radio.disabled);
            if (!first && !checked) {
                return;
            }
            // If an enabled checked radio exists, set it to be the focusable radio
            // otherwise we default to focus the first radio
            const focusable = checked || first;
            for (const radio of radios) {
                const tabindex = radio === focusable ? 0 : -1;
                radio.setButtonTabindex(tabindex);
            }
        };
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        this.onClick = (ev) => {
            const element = ev.target;
            if (element.href) {
                return;
            }
            ev.preventDefault();
            const selectedRadio = ev.target && ev.target.closest('bal-radio');
            if (selectedRadio && !selectedRadio.disabled && !selectedRadio.readonly) {
                const currentValue = this.value;
                const newValue = selectedRadio.value;
                if (newValue !== currentValue) {
                    this.value = newValue;
                }
                else if (this.allowEmptySelection) {
                    this.value = undefined;
                }
                this.balChange.emit(this.value);
            }
        };
    }
    createLogger(log) {
        this.log = log;
    }
    async optionChanged() {
        this.onOptionChange();
        this.mutationObserverActive = this.options === undefined;
    }
    invalidChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.invalid = value;
            });
        }
    }
    disabledChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.disabled = value;
            });
        }
    }
    readonlyChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.readonly = value;
            });
        }
    }
    valueChanged() {
        this.onOptionChange();
    }
    columnsChanged(value) {
        this.getRadios().forEach(radio => (radio.colSize = value));
    }
    columnsTabletChanged(value) {
        this.getRadios().forEach(radio => (radio.colSizeTablet = value));
    }
    columnsMobileChanged(value) {
        this.getRadios().forEach(radio => (radio.colSizeMobile = value));
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        this.initialValue = this.value;
        this.mutationObserverActive = this.options === undefined;
    }
    componentWillLoad() {
        this.setRadioInterface();
        this.disabledChanged(this.disabled);
        this.readonlyChanged(this.readonly);
        this.invalidChanged(this.invalid);
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
        this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']);
    }
    focusInListener(ev) {
        this.balFocus.emit(ev);
    }
    focusOutListener(ev) {
        this.balBlur.emit(ev);
    }
    mutationListener() {
        this.setRadioInterface();
        this.disabledChanged(this.disabled);
        this.readonlyChanged(this.readonly);
        this.invalidChanged(this.invalid);
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
    }
    listenOnClick(ev) {
        if (isDescendant(this.el, ev.target)) {
            stopEventBubbling(ev);
        }
    }
    radioFocusListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-radio')) {
            stopEventBubbling(ev);
        }
    }
    radioBlurListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-radio')) {
            stopEventBubbling(ev);
        }
    }
    resetListener(ev) {
        const formElement = ev.target;
        if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) {
            this.value = this.initialValue;
        }
    }
    onKeydown(ev) {
        if (ev.target && !this.el.contains(ev.target)) {
            return;
        }
        // Get all radios inside of the radio group and then
        // filter out disabled radios since we need to skip those
        const radios = this.getRadios().filter(radio => !radio.disabled);
        const targetRadio = ev.target.closest('bal-radio');
        // Only move the radio if the current focus is in the radio group
        if (targetRadio && radios.includes(targetRadio)) {
            const index = radios.findIndex(radio => radio === targetRadio);
            const current = radios[index];
            let next;
            // If hitting arrow down or arrow right, move to the next radio
            // If we're on the last radio, move to the first radio
            if (['ArrowDown', 'ArrowRight'].includes(ev.code)) {
                next = index === radios.length - 1 ? radios[0] : radios[index + 1];
            }
            // If hitting arrow up or arrow left, move to the previous radio
            // If we're on the first radio, move to the last radio
            if (['ArrowUp', 'ArrowLeft'].includes(ev.code)) {
                next = index === 0 ? radios[radios.length - 1] : radios[index - 1];
            }
            if (next && radios.includes(next)) {
                next.setFocus(ev);
                this.value = next.value;
                this.balChange.emit(this.value);
            }
            // Update the radio group value when a user presses the
            // space bar on top of a selected radio
            if (['Space'].includes(ev.code)) {
                this.value = this.allowEmptySelection && this.value !== undefined ? undefined : current.value;
                this.balChange.emit(this.value);
                // Prevent browsers from jumping
                // to the bottom of the screen
                ev.preventDefault();
            }
        }
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /** @internal */
    async setValue(value) {
        this.value = value;
    }
    /**
     * Find the options properties by its value
     */
    async getOptionByValue(value) {
        const options = this.options;
        if (options) {
            return options.find(option => option.value === value);
        }
        return undefined;
    }
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    setRadioInterface() {
        this.getRadios().forEach((radio) => {
            if (this.interface) {
                radio.interface = this.interface;
            }
        });
    }
    setRadioChecked() {
        this.getRadios().forEach((radio) => {
            if (radio.updateState) {
                radio.updateState();
            }
        });
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    getRadios() {
        return Array.from(this.el.querySelectorAll('bal-radio'));
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = BEM.block('radio-group');
        const innerEl = block.element('inner');
        const rawOptions = this.options || [];
        const options = rawOptions.map(option => {
            if (typeof option.html === 'function') {
                return Object.assign(Object.assign({}, option), { html: option.html() });
            }
            return option;
        });
        return (h(Host, Object.assign({ class: Object.assign({}, block.class()), role: "radiogroup", "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-disabled": ariaBooleanToString(this.disabled), onClick: this.onClick }, this.inheritedAttributes), h("div", { class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, innerEl.class()), innerEl.modifier('vertical-mobile').class(this.verticalOnMobile)), innerEl.modifier('vertical').class(this.vertical)), innerEl.modifier('expanded').class(this.expanded)), innerEl.modifier('button').class(this.interface === 'button')) }, h("slot", null), options.map(option => (h("bal-radio", { key: option.value, name: option.name || this.name, value: option.value, labelHidden: option.labelHidden, flat: option.flat, interface: option.interface, disabled: option.disabled, readonly: option.readonly, required: option.required, nonSubmit: !!option.nonSubmit, invalid: option.invalid, innerHTML: option.html }))))));
    }
    get el() { return this; }
    static get watchers() { return {
        "options": ["optionChanged"],
        "invalid": ["invalidChanged"],
        "disabled": ["disabledChanged"],
        "readonly": ["readonlyChanged"],
        "value": ["valueChanged"],
        "columns": ["columnsChanged"],
        "columnsTablet": ["columnsTabletChanged"],
        "columnsMobile": ["columnsMobileChanged"]
    }; }
    static get style() { return balRadioGroupCss; }
}, [260, "bal-radio-group", {
        "options": [16],
        "interface": [1],
        "allowEmptySelection": [4, "allow-empty-selection"],
        "name": [1],
        "vertical": [4],
        "verticalOnMobile": [4, "vertical-on-mobile"],
        "expanded": [4],
        "invalid": [4],
        "disabled": [4],
        "readonly": [4],
        "value": [1032],
        "columns": [2],
        "columnsTablet": [2, "columns-tablet"],
        "columnsMobile": [2, "columns-mobile"],
        "autoInvalidOff": [516, "auto-invalid-off"],
        "ariaForm": [32],
        "setValue": [64],
        "getOptionByValue": [64],
        "setAriaForm": [64]
    }, [[6, "balChange", "listenOnClick"], [6, "balFocus", "radioFocusListener"], [6, "balBlur", "radioBlurListener"], [6, "reset", "resetListener"], [4, "keydown", "onKeydown"]], {
        "options": ["optionChanged"],
        "invalid": ["invalidChanged"],
        "disabled": ["disabledChanged"],
        "readonly": ["readonlyChanged"],
        "value": ["valueChanged"],
        "columns": ["columnsChanged"],
        "columnsTablet": ["columnsTabletChanged"],
        "columnsMobile": ["columnsMobileChanged"]
    }]);
__decorate([
    Logger('bal-radio-group'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "createLogger", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "focusInListener", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "focusOutListener", null);
__decorate([
    ListenToMutation({ tags: ['bal-radio-group', 'bal-radio'], attributes: false, characterData: false }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "mutationListener", null);
let radioGroupIds = 0;
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["bal-radio-group", "bal-radio", "bal-radio-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "bal-radio-group":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, RadioGroup);
            }
            break;
        case "bal-radio":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "bal-radio-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}

const BalRadioGroup = RadioGroup;
const defineCustomElement = defineCustomElement$1;

export { BalRadioGroup, defineCustomElement };
