'use strict';

var index = require('./index-feA4skrY.js');
var tslib_es6 = require('./tslib.es6-DrfCPgT9.js');
var bem = require('./bem-p0PWVN8n.js');
var focusVisible = require('./focus-visible-DFZa8IIA.js');
var form = require('./form-BSlIiqcR.js');
var formInput = require('./form-input-BwFB4Rej.js');
var helpers = require('./helpers-HuaiWXrB.js');
var log = require('./log-CXDMiw7o.js');
var keyboard_helpers = require('./keyboard.helpers-BkZpVT-9.js');
var focus_decorator = require('./focus.decorator-BL2kLsNv.js');
var animation_decorator = require('./animation.decorator-B4NJvcMF.js');
var visibility_decorator = require('./visibility.decorator-DTARY-5M.js');
var windowResize_decorator = require('./window-resize.decorator-CFAzpxMB.js');
var breakpoints_decorator = require('./breakpoints.decorator-C7C_2t01.js');
var attributes = require('./attributes-Cp0kpySW.js');
require('./browser-BwmkTmm8.js');
require('./config.utils-Civnz2jT.js');
require('./listener-DspXpqzY.js');
require('./breakpoints.subject-CXJYXMpo.js');
require('./device-CoogBamh.js');
require('./tokens.esm-wVc8fBNC.js');

const balSegmentCss = ":root{--bal-segment-background:var(--bal-color-grey-2);--bal-segment-background-invalid:var(--bal-color-danger-1);--bal-segment-item-focus-border:var(--bal-color-border-primary);--bal-segment-item-text-color:var(--bal-body-color);--bal-segment-item-text-color-checked:var(--bal-body-color);--bal-segment-item-text-color-checked-hovered:var(--bal-color-text-primary-hovered);--bal-segment-item-text-color-checked-pressed:var(--bal-color-text-primary-pressed);--bal-segment-item-text-color-invalid:var(--bal-color-text-danger);--bal-segment-item-text-color-invalid-hovered:var(--bal-color-text-danger-hovered);--bal-segment-item-text-color-invalid-pressed:var(--bal-color-text-danger-pressed);--bal-segment-item-text-color-disabled:var(--bal-color-text-grey);--bal-segment-item-text-color-disabled-checked:var(--bal-color-text-grey-dark);--bal-segment-item-divider-background:var(--bal-color-grey);--bal-segment-item-divider-background-invalid:var(--bal-color-danger-2);--bal-segment-item-indicator-background:var(--bal-color-purple-2);--bal-segment-item-indicator-background-invalid:var(--bal-color-danger-4);--bal-segment-item-indicator-background-disabled:var(--bal-color-grey-3)}.bal-segment{display:-ms-flexbox;display:flex;background:var(--bal-segment-background);border-radius:var(--bal-radius-normal);gap:.125rem;gap:.125rem;padding:.25rem;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.bal-segment--invalid{background:var(--bal-segment-background-invalid)}.bal-segment--vertical{-ms-flex-direction:column;flex-direction:column;width:100%}.bal-segment--vertical .bal-segment-item__button{width:100%;-ms-flex:1;flex:1}.bal-segment--vertical.bal-segment--scrollable{overflow:auto;max-height:240px}.bal-segment--expanded{width:100%;min-width:100%;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-align:center;align-items:center}.bal-segment--expanded .bal-segment-item,.bal-segment--expanded .bal-segment-item>button{-ms-flex:1;flex:1;width:100%}.bal-segment--expanded .bal-segment-item .bal-content,.bal-segment--expanded .bal-segment-item>button .bal-content{-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}";

const Segment = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.balFocus = index.createEvent(this, "balFocus");
        this.balBlur = index.createEvent(this, "balBlur");
        this.balChange = index.createEvent(this, "balChange");
        this.balSelect = index.createEvent(this, "balSelect");
        this.balVertical = index.createEvent(this, "balVertical");
        this.keyboardMode = true;
        this.isVertical = false;
        this.isMobile = false;
        this.maxWidth = 0;
        this.ariaForm = form.defaultBalAriaForm;
        /**
         * PUBLIC PROPERTY API
         * ------------------------------------------------------
         */
        /**
         * If `true`, the segment is shown red.
         */
        this.invalid = false;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        /**
         * If `true`, the user cannot interact with the segment.
         */
        this.disabled = false;
        /**
         * If `true`, the segment items are presented vertical as a list.
         */
        this.vertical = false;
        /**
         * If `true`, and is vertical then the list height is limited and scrollable.
         */
        this.scrollable = false;
        /**
         * If `true`, the element uses the whole width
         */
        this.expanded = false;
        /**
         * LISTENERS
         * ------------------------------------------------------
         */
        this.hasFocus = false;
        this.getSegmentItem = (selector) => {
            var _a, _b;
            const items = this.allItems.filter(item => !item.disabled);
            const currIndex = items.findIndex(item => item === document.activeElement.closest('bal-segment-item'));
            switch (selector) {
                case 'current':
                    return items[currIndex];
                case 'first':
                    return items[0];
                case 'last':
                    return items[items.length - 1];
                case 'next':
                    return (_a = items[currIndex + 1]) !== null && _a !== void 0 ? _a : items[0];
                case 'previous':
                    return (_b = items[currIndex - 1]) !== null && _b !== void 0 ? _b : items[items.length - 1];
                default:
                    return null;
            }
        };
        /**
         * PRIVATE EVENT HANDLERS
         * ------------------------------------------------------
         */
        this.onPointerDown = () => {
            this.keyboardMode = false;
        };
        this.onSlottedItemsChange = () => {
            /**
             * When the slotted segment buttons change we need to
             * ensure that the new segment buttons are checked if
             * the value matches the segment button value.
             */
            this.valueChanged(this.value);
            this.defineWidth();
        };
        this.onClick = (ev) => {
            if (this.disabled) {
                return;
            }
            const current = ev.target;
            const previous = this.checked;
            // If the current element is a segment then that means
            // the user tried to swipe to a segment button and
            // click a segment button at the same time so we should
            // not update the checked segment button
            if (current.tagName === 'BAL-SEGMENT') {
                return;
            }
            if (current && current.setFocus) {
                current.setFocus();
            }
            if (previous) {
                this.checkButton(previous, current);
            }
            else {
                this.setCheckedClasses();
                this.checkButton(current, current);
            }
            if (current !== previous) {
                this.emitValueChange();
            }
        };
    }
    createLogger(log) {
        this.log = log;
    }
    invalidChanged() {
        this.allItems.map(item => (item.invalid = this.invalid));
    }
    disabledChanged() {
        this.allItems.map(item => (item.disabled = this.disabled));
    }
    valueChanged(value) {
        /**
         * `balSelect` is emitted every time the value changes (internal or external changes).
         * Used by `bal-segment-item` to determine if the button should be checked.
         */
        this.balSelect.emit(value);
        this.setCheckedClasses();
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        this.el.addEventListener('touchstart', this.onPointerDown);
        this.el.addEventListener('mousedown', this.onPointerDown);
        this.disabledChanged();
        this.isVertical = this.vertical;
    }
    disconnectedCallback() {
        this.el.removeEventListener('touchstart', this.onPointerDown);
        this.el.removeEventListener('mousedown', this.onPointerDown);
    }
    async componentDidLoad() {
        this.setCheckedClasses();
        this.defineWidth();
    }
    focusInListener(ev) {
        this.balFocus.emit(ev);
    }
    focusOutListener(ev) {
        this.balBlur.emit(ev);
    }
    animationListener() {
        const childRect = this.el.getBoundingClientRect();
        this.maxWidth = childRect.width;
        this.windowResizeListener();
    }
    visibilityListener() {
        const childRect = this.el.getBoundingClientRect();
        this.maxWidth = childRect.width;
        this.windowResizeListener();
    }
    breakpointListener(breakpoints) {
        this.isMobile = breakpoints.mobile;
    }
    windowResizeListener() {
        if (this.vertical === false && this.maxWidth > 0) {
            const parent = this.el.parentElement.getBoundingClientRect();
            if (parent.width < this.maxWidth) {
                //
                // element in horizontal is to big
                this.emitVerticalChange(true);
            }
            else {
                //
                // element has enough space in parent element
                this.emitVerticalChange(false);
            }
        }
        else {
            this.emitVerticalChange(true);
        }
    }
    listenOnKeyDownOutside() {
        this.keyboardMode = true;
    }
    listenOnKeyDown(ev) {
        this.keyboardMode = focusVisible.FOCUS_KEYS.includes(ev.key);
        let forceChange = false;
        let current;
        if (keyboard_helpers.isSpaceKey(ev) || keyboard_helpers.isEnterKey(ev)) {
            formInput.stopEventBubbling(ev);
            current = this.getSegmentItem('current');
            forceChange = this.value !== current.value;
            this.value = current.value;
        }
        else if (keyboard_helpers.isArrowUpKey(ev) || keyboard_helpers.isArrowLeftKey(ev)) {
            formInput.stopEventBubbling(ev);
            current = this.getSegmentItem('previous');
        }
        else if (keyboard_helpers.isArrowDownKey(ev) || keyboard_helpers.isArrowRightKey(ev)) {
            formInput.stopEventBubbling(ev);
            current = this.getSegmentItem('next');
        }
        else if (keyboard_helpers.isHomeKey(ev)) {
            formInput.stopEventBubbling(ev);
            current = this.getSegmentItem('first');
        }
        else if (keyboard_helpers.isEndKey(ev)) {
            formInput.stopEventBubbling(ev);
            current = this.getSegmentItem('last');
        }
        if (!current) {
            return;
        }
        const previous = this.checked;
        if (current !== previous || forceChange) {
            this.checkButton(previous, current);
            this.emitValueChange();
        }
        if (current) {
            current.setFocus();
        }
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    get allItems() {
        return Array.from(this.el.querySelectorAll('bal-segment-item'));
    }
    get checked() {
        return this.allItems.find(item => item.value === this.value);
    }
    /**
     * PRIVATE METHODS
     * ------------------------------------------------------
     */
    emitValueChange() {
        this.balChange.emit(this.value);
    }
    emitVerticalChange(isVertical) {
        if (this.isVertical !== isVertical) {
            this.isVertical = isVertical;
            this.balVertical.emit(this.isVertical);
        }
    }
    defineWidth() {
        helpers.raf(() => {
            if (this.isVertical === false) {
                const childRect = this.el.getBoundingClientRect();
                this.maxWidth = childRect.width;
            }
            this.windowResizeListener();
        });
    }
    getIndicator(item) {
        if (item) {
            const root = item.shadowRoot || item;
            return root.querySelector('.bal-segment-item__indicator');
        }
        return null;
    }
    checkButton(previous, current) {
        const previousIndicator = this.getIndicator(previous);
        const currentIndicator = this.getIndicator(current);
        if (previousIndicator === null || currentIndicator === null) {
            return;
        }
        const previousClientRect = previousIndicator.getBoundingClientRect();
        const currentClientRect = currentIndicator.getBoundingClientRect();
        const widthDelta = previousClientRect.width / currentClientRect.width;
        const xPosition = previousClientRect.left - currentClientRect.left;
        // Scale the indicator width to match the previous indicator width
        // and translate it on top of the previous indicator
        let transform = `translate3d(${xPosition}px, 0, 0) scaleX(${widthDelta})`;
        if (this.isVertical) {
            const heightDelta = previousClientRect.height / currentClientRect.height;
            const yPosition = previousClientRect.top - currentClientRect.top;
            // Scale the indicator width to match the previous indicator width
            // and translate it on top of the previous indicator
            transform = `translate3d(0, ${yPosition}px, 0) scaleY(${heightDelta})`;
        }
        index.writeTask(() => {
            // Remove the transition before positioning on top of the previous indicator
            currentIndicator.classList.remove('bal-segment-item__indicator--animated');
            currentIndicator.style.setProperty('transform', transform);
            // Force a repaint to ensure the transform happens
            currentIndicator.getBoundingClientRect();
            // Add the transition to move the indicator into place
            currentIndicator.classList.add('bal-segment-item__indicator--animated');
            // Remove the transform to slide the indicator back to the button clicked
            currentIndicator.style.setProperty('transform', '');
        });
        this.value = current.value;
        this.setCheckedClasses();
    }
    setCheckedClasses() {
        const items = this.allItems;
        const index = items.findIndex(item => item.value === this.value);
        const next = index + 1;
        const previous = index - 1;
        for (const item of items) {
            item.classList.remove('bal-segment-item--after-checked');
            item.classList.remove('bal-segment-item--before-checked');
        }
        if (next < items.length) {
            items[next].classList.add('bal-segment-item--after-checked');
        }
        if (previous < items.length && previous >= 0) {
            items[previous].classList.add('bal-segment-item--before-checked');
        }
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const { invalid, isVertical, scrollable, keyboardMode, expanded, isMobile, disabled } = this;
        const block = bem.BEM.block('segment');
        return (index.h(index.Host, { key: '08fb99b658d704d85ab181d55d7bdbce7ee40fd8', role: "radiogroup", id: this.ariaForm.controlId, "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, block.class()), block.modifier('invalid').class(invalid)), block.modifier('vertical').class(isVertical)), block.modifier('scrollable').class(scrollable)), block.modifier('keyboard').class(keyboardMode)), block.modifier('disabled').class(disabled)), block.modifier('expanded').class((expanded || isMobile) && !isVertical)), onClick: this.onClick }, index.h("slot", { key: '432741fe51dc5c83ea241506687de13469afc149', onSlotchange: this.onSlottedItemsChange })));
    }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "invalid": ["invalidChanged"],
        "disabled": ["disabledChanged"],
        "value": ["valueChanged"]
    }; }
};
tslib_es6.__decorate([
    log.Logger('bal-segment'),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Function]),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "createLogger", null);
tslib_es6.__decorate([
    focus_decorator.ListenToFocus(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Object]),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "focusInListener", null);
tslib_es6.__decorate([
    focus_decorator.ListenToFocus(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Object]),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "focusOutListener", null);
tslib_es6.__decorate([
    animation_decorator.ListenToAnimation(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", []),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "animationListener", null);
tslib_es6.__decorate([
    visibility_decorator.ListenToVisibility(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", []),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "visibilityListener", null);
tslib_es6.__decorate([
    breakpoints_decorator.ListenToBreakpoints(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Object]),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "breakpointListener", null);
tslib_es6.__decorate([
    windowResize_decorator.ListenToWindowResize(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", []),
    tslib_es6.__metadata("design:returntype", void 0)
], Segment.prototype, "windowResizeListener", null);
Segment.style = balSegmentCss;

const balSegmentItemCss = ":root{--bal-segment-background:var(--bal-color-grey-2);--bal-segment-background-invalid:var(--bal-color-danger-1);--bal-segment-item-focus-border:var(--bal-color-border-primary);--bal-segment-item-text-color:var(--bal-body-color);--bal-segment-item-text-color-checked:var(--bal-body-color);--bal-segment-item-text-color-checked-hovered:var(--bal-color-text-primary-hovered);--bal-segment-item-text-color-checked-pressed:var(--bal-color-text-primary-pressed);--bal-segment-item-text-color-invalid:var(--bal-color-text-danger);--bal-segment-item-text-color-invalid-hovered:var(--bal-color-text-danger-hovered);--bal-segment-item-text-color-invalid-pressed:var(--bal-color-text-danger-pressed);--bal-segment-item-text-color-disabled:var(--bal-color-text-grey);--bal-segment-item-text-color-disabled-checked:var(--bal-color-text-grey-dark);--bal-segment-item-divider-background:var(--bal-color-grey);--bal-segment-item-divider-background-invalid:var(--bal-color-danger-2);--bal-segment-item-indicator-background:var(--bal-color-purple-2);--bal-segment-item-indicator-background-invalid:var(--bal-color-danger-4);--bal-segment-item-indicator-background-disabled:var(--bal-color-grey-3)}.bal-segment-item{display:block;position:relative;height:auto;text-decoration:none;text-overflow:ellipsis;text-decoration:none;text-overflow:ellipsis;white-space:nowrap;cursor:pointer;grid-row:1;-webkit-font-kerning:none;font-kerning:none}.bal-segment-item--disabled{cursor:default !important;pointer-events:none !important}.bal-segment-item__button{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;min-height:2.5rem;min-width:3rem;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;-ms-flex-positive:1;flex-grow:1;padding-top:.375rem;padding-bottom:.375rem;padding-left:20px;padding-right:20px;outline:none;border-color:rgba(0,0,0,0);border-width:var(--bal-border-width-normal);border-style:solid;border-radius:var(--bal-radius-normal);background:rgba(0,0,0,0);font-size:var(--bal-text-size-normal);font-weight:var(--bal-font-weight-bold);color:var(--bal-segment-item-text-color);overflow:hidden;position:relative;contain:content;pointer-events:none;cursor:pointer;z-index:2}.bal-segment-item__button--vertical{padding-left:.75rem;padding-right:.75rem}.bal-segment-item__button span{font-size:var(--bal-text-size-small);font-weight:var(--bal-font-weight-regular)}.bal-segment-item__button{will-change:color,padding;-webkit-transition:color 160ms cubic-bezier(0.4, 0, 0.2, 1);transition:color 160ms cubic-bezier(0.4, 0, 0.2, 1);-webkit-transition:padding 160ms cubic-bezier(0.4, 0, 0.2, 1);transition:padding 160ms cubic-bezier(0.4, 0, 0.2, 1)}.bal-segment-item:not(.bal-segment-item--checked):not(.bal-segment-item--last):not(.bal-segment-item--before-checked)::after{content:\"\";position:absolute;background:var(--bal-segment-item-divider-background);border-radius:var(--bal-radius-normal)}.bal-segment-item:not(.bal-segment-item--vertical):not(.bal-segment-item--checked):not(.bal-segment-item--last):not(.bal-segment-item--before-checked)::after{top:2px;bottom:2px;right:-1px;width:2px}.bal-segment-item.bal-segment-item--vertical:not(.bal-segment-item--checked):not(.bal-segment-item--last):not(.bal-segment-item--before-checked)::after{left:2px;right:2px;bottom:-1px;height:2px}.bal-segment-item--invalid:not(.bal-segment-item--checked):not(.bal-segment-item--last):not(.bal-segment-item--before-checked)::after{background:var(--bal-segment-item-divider-background-invalid)}.bal-segment-item__indicator{-webkit-transform-origin:left;transform-origin:left;position:absolute;opacity:0;-webkit-box-sizing:border-box;box-sizing:border-box;pointer-events:none;border-radius:var(--bal-radius-normal);background:var(--bal-segment-item-indicator-background);top:0;left:0}.bal-segment-item__indicator--vertical{-webkit-transform-origin:top;transform-origin:top}.bal-segment-item__indicator--invalid{background:var(--bal-segment-item-indicator-background-invalid)}.bal-segment-item__indicator--background{min-width:100%;min-height:100%;-webkit-transform:none;transform:none;pointer-events:none}.bal-segment-item__indicator--animated{will-change:transform,opacity,top,bottom,left,right,min-width,min-heigth;-webkit-transition:min-width 100ms ease,min-height 100ms ease,top 100ms ease,left 100ms ease,bottom 100ms ease,right 100ms ease,-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1);transition:min-width 100ms ease,min-height 100ms ease,top 100ms ease,left 100ms ease,bottom 100ms ease,right 100ms ease,-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1);transition:transform 260ms cubic-bezier(0.4, 0, 0.2, 1),min-width 100ms ease,min-height 100ms ease,top 100ms ease,left 100ms ease,bottom 100ms ease,right 100ms ease;transition:transform 260ms cubic-bezier(0.4, 0, 0.2, 1),min-width 100ms ease,min-height 100ms ease,top 100ms ease,left 100ms ease,bottom 100ms ease,right 100ms ease,-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1)}.bal-segment-item__indicator--checked{opacity:1}.bal-segment-item:active .bal-segment-item__indicator{min-width:calc(100% - 4px);min-height:calc(100% - 4px);top:2px !important;bottom:2px !important;left:2px !important;right:2px !important}.bal-segment-item__button__icon{position:absolute !important;opacity:0;width:0 !important;-webkit-transform:translateX(0.1rem);transform:translateX(0.1rem);pointer-events:none !important;cursor:inherit;will-change:transform,opacity}.bal-segment-item__button__icon:not(.bal-segment-item__button__icon--vertical){left:10px}.bal-segment-item__button__icon--vertical{right:10px}.bal-segment-item__button__icon--animated{opacity:1;width:.875rem !important;-webkit-transform:translateX(-4px);transform:translateX(-4px);-webkit-transition:opacity 260ms cubic-bezier(0.4, 0, 0.2, 1),-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1);transition:opacity 260ms cubic-bezier(0.4, 0, 0.2, 1),-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1);transition:opacity 260ms cubic-bezier(0.4, 0, 0.2, 1),transform 260ms cubic-bezier(0.4, 0, 0.2, 1);transition:opacity 260ms cubic-bezier(0.4, 0, 0.2, 1),transform 260ms cubic-bezier(0.4, 0, 0.2, 1),-webkit-transform 260ms cubic-bezier(0.4, 0, 0.2, 1)}.bal-segment-item__button--checked{color:var(--bal-segment-item-text-color-checked);padding-right:40px}.bal-segment-item__button--checked:not(.bal-segment-item__button--vertical){padding-left:26px;padding-right:12px}@media (hover: hover)and (pointer: fine){.bal-segment-item:not(.bal-segment-item--disabled):hover .bal-segment-item__button:not(.bal-segment-item__button--checked){color:var(--bal-segment-item-text-color-hovered)}}.bal-segment-item:not(.bal-segment-item--disabled):active .bal-segment-item__button:not(.bal-segment-item__button--checked){color:var(--bal-segment-item-text-color-pressed)}.bal-segment--keyboard .bal-segment-item__button:not(.bal-segment-item__button--disabled):focus-visible,.bal-segment--keyboard .bal-segment-item__button--focused:not(.bal-segment-item__button--disabled){border-color:var(--bal-segment-item-focus-border);border-width:var(--bal-border-width-normal);border-style:solid;-webkit-transition:border 300ms ease-in-out;transition:border 300ms ease-in-out}.bal-segment-item.bal-segment-item--invalid:not(.bal-segment-item--disabled) .bal-segment-item__button:not(.bal-segment-item__button--checked){color:var(--bal-segment-item-text-color-invalid)}@media (hover: hover)and (pointer: fine){.bal-segment-item.bal-segment-item--invalid:not(.bal-segment-item--disabled):hover .bal-segment-item__button:not(.bal-segment-item__button--checked){color:var(--bal-segment-item-text-color-invalid-hovered)}}.bal-segment-item.bal-segment-item--invalid:not(.bal-segment-item--disabled):active .bal-segment-item__button:not(.bal-segment-item__button--checked){color:var(--bal-segment-item-text-color-invalid-pressed)}.bal-segment-item__button--invalid.bal-segment-item__button--checked{color:var(--bal-color-text-white)}.bal-segment-item__button--disabled{background:rgba(0,0,0,0);color:var(--bal-segment-item-text-color-disabled)}.bal-segment-item__button--disabled.bal-segment-item__button--checked{background:var(--bal-segment-item-indicator-background-disabled);color:var(--bal-segment-item-text-color-disabled-checked)}.bal-segment-item__button__slot--hidden{display:none !important}";

let SegmentItemIds = 0;
const SegmentItem = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.segmentEl = null;
        this.inheritedAttributes = {};
        this.internalId = SegmentItemIds++;
        this.inputId = `bal-si-${this.internalId}`;
        this.hasSlotContent = false;
        this.isFocusable = false;
        this.isVertical = false;
        this.isLast = false;
        this.isFirst = false;
        this.hasEmptyValue = true;
        this.ariaForm = form.defaultBalAriaForm;
        /**
         * If `true`, the user cannot interact with the segment button.
         */
        this.disabled = false;
        /**
         * If `true`, the segment is shown in red.
         */
        this.invalid = false;
        /**
         * @internal
         * Sets focus state for key navigation
         */
        this.focused = false;
        /**
         * @internal
         * Sets checked state for key navigation
         */
        this.checked = false;
        /**
         * Label of the segment control
         */
        this.label = '';
        /**
         * The value of the segment button.
         */
        this.value = 'bal-si-' + this.internalId;
        this.updateVertical = (ev) => {
            this.isVertical = ev.detail;
        };
        this.updateState = () => {
            const { segmentEl } = this;
            if (segmentEl) {
                if (segmentEl.value === '' || segmentEl.value === undefined || segmentEl.value === null) {
                    const items = this.allAvailableOptions;
                    if (items.length > 0) {
                        const first = items[0];
                        this.checked = false;
                        this.isFocusable = first === this.el;
                    }
                }
                else {
                    this.checked = segmentEl.value === this.value;
                    this.isFocusable = segmentEl.value === this.value;
                }
                if (segmentEl.disabled) {
                    this.disabled = true;
                }
                if (segmentEl.invalid) {
                    this.invalid = true;
                }
                this.isLast = segmentEl.lastElementChild === this.el;
                this.isFirst = segmentEl.firstElementChild === this.el;
                this.calculateEmptyValue();
            }
        };
        this.onSlottedItemsChange = () => {
            /**
             * When the slotted segment buttons change we need to
             * ensure that the new segment buttons are checked if
             * the value matches the segment button value.
             */
            this.checkSlotContent();
        };
    }
    valueChanged(newValue, oldValue) {
        if (newValue !== oldValue) {
            this.updateState();
        }
    }
    componentWillLoad() {
        this.inheritedAttributes = Object.assign({}, attributes.inheritAttributes(this.el, ['aria-label']));
    }
    connectedCallback() {
        const segmentEl = (this.segmentEl = this.el.closest('bal-segment'));
        if (segmentEl && segmentEl.vertical) {
            this.isVertical = segmentEl.vertical;
        }
    }
    componentDidLoad() {
        const segmentEl = (this.segmentEl = this.el.closest('bal-segment'));
        if (segmentEl) {
            helpers.addEventListener(segmentEl, 'balSelect', this.updateState);
            helpers.addEventListener(segmentEl, 'balVertical', this.updateVertical);
        }
        helpers.raf(() => {
            this.checkSlotContent();
            this.updateState();
        });
    }
    disconnectedCallback() {
        const segmentEl = this.segmentEl;
        if (segmentEl) {
            helpers.removeEventListener(segmentEl, 'balSelect', this.updateState);
            helpers.removeEventListener(segmentEl, 'balVertical', this.updateVertical);
            this.segmentEl = null;
        }
    }
    calculateEmptyValue() {
        if (this.segmentEl) {
            const segments = Array.from(this.segmentEl.querySelectorAll('bal-segment-item'));
            this.hasEmptyValue = !segments.some(item => item.value === this.segmentEl.value);
        }
        else {
            this.hasEmptyValue = false;
        }
    }
    /**
     * @internal
     * Focuses the native <button> element
     * inside of ion-segment-button.
     */
    async setFocus() {
        const { nativeEl } = this;
        if (nativeEl !== undefined) {
            nativeEl.focus();
        }
    }
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    get allAvailableOptions() {
        return this.allOptions.filter(item => !item.disabled);
    }
    get allOptions() {
        const { segmentEl } = this;
        if (segmentEl) {
            return Array.from(segmentEl.querySelectorAll('bal-segment-item'));
        }
        return [];
    }
    checkSlotContent() {
        const slot = this.el.querySelector('[part="slot"]');
        const children = slot ? slot.innerHTML.trim() : '';
        this.hasSlotContent = children.length > 0;
    }
    render() {
        const { checked, focused, segmentEl, label, isFocusable, isFirst, hasEmptyValue } = this;
        const block = bem.BEM.block('segment-item');
        const buttonBem = block.element('button');
        const indicatorBem = block.element('indicator');
        const invalid = this.invalid || (segmentEl && segmentEl.invalid);
        const disabled = this.disabled || (segmentEl && segmentEl.disabled);
        const vertical = this.isVertical;
        const hasTabindex = (hasEmptyValue && isFirst) || (isFocusable && !disabled);
        const id = (hasTabindex && this.ariaForm.controlId) || this.inputId;
        let buttonAttributes = {};
        if (hasTabindex) {
            buttonAttributes = {
                'aria-labelledby': this.ariaForm.labelId,
                'aria-describedby': this.ariaForm.messageId,
            };
        }
        return (index.h(index.Host, { key: '54ab8ce0ab290fcbc238087789ce0bca3caedddc', class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, block.class()), block.modifier('vertical').class(vertical)), block.modifier('disabled').class(disabled)), block.modifier('checked').class(checked)), block.modifier('invalid').class(invalid)), block.modifier('last').class(this.isLast && !checked)) }, index.h("button", Object.assign({ key: 'be4e31f8a5b0da8cc9f70a867e546920127ba4b2', id: id, role: "radio", "aria-checked": checked ? 'true' : 'false' }, buttonAttributes, { class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, buttonBem.class()), buttonBem.modifier('checked').class(checked)), buttonBem.modifier('invalid').class(invalid)), buttonBem.modifier('disabled').class(disabled)), buttonBem.modifier('focused').class(focused)), buttonBem.modifier('vertical').class(vertical)), type: 'button', tabIndex: hasTabindex ? 0 : -1, part: "native", disabled: disabled, ref: el => (this.nativeEl = el) }, this.inheritedAttributes), index.h("bal-icon", { key: 'f6d56f256041be2a97822dcc424d887844bacc0e', name: "check", size: "small", class: Object.assign(Object.assign(Object.assign({}, buttonBem.element('icon').class()), buttonBem.element('icon').modifier('animated').class(checked)), buttonBem.element('icon').modifier('vertical').class(vertical)), color: disabled ? 'grey-dark' : invalid ? 'white' : 'primary' }), index.h("bal-stack", { key: '15df166b0d0d2b6a6b9447506755b9de3581c77d', space: "x-small", layout: 'horizontal' }, index.h("bal-content", { key: '056ba7bfb5d4f456f03f70e9f86e0269bd44a78b', space: "none" }, index.h("bal-label", { key: '055ca1dd2f698e5b3758fbc5535a221801d90642', htmlId: `bal-si-${this.internalId}-label` }, label), index.h("span", { key: '5a4ea620046a856959a811110f9c8ec5dfefa156', part: "slot", class: Object.assign({}, buttonBem.element('slot').modifier('hidden').class(!this.hasSlotContent)) }, ' ', index.h("slot", { key: 'ceeb6506e86bde765a45497987759479b450c16f', onSlotchange: this.onSlottedItemsChange }))))), index.h("div", { key: '7384e9bec0b8c8337191b79a54a18cf5cc89a55b', class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, indicatorBem.class()), indicatorBem.modifier('animated').class()), indicatorBem.modifier('background').class()), indicatorBem.modifier('disabled').class(disabled)), indicatorBem.modifier('invalid').class(invalid)), indicatorBem.modifier('checked').class(checked)), indicatorBem.modifier('vertical').class(vertical)) })));
    }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "value": ["valueChanged"]
    }; }
};
SegmentItem.style = balSegmentItemCss;

exports.bal_segment = Segment;
exports.bal_segment_item = SegmentItem;
