// #region Imports
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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { ScrollerServiceLocator } from '../../../../Dom/Scroller';
import { getSlotElements } from '../../../../Dom/Slot';
import { on } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { DropDownable } from '../../../Behaviors/DropDownable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { ClickOutsideController } from '../../../Controllers/ClickOutsideController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { QueryChild } from '../../../Decorators/QueryChildDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { Appearance } from '../../../Types/Appearance';
import { Key } from '../../../Types/Key';
import { SelectionMode } from '../../../Types/SelectionMode';
import { Variant } from '../../../Types/Variant';
import { TextBoxElement } from '../../Inputs/TextBox/TextBoxElement';
import { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { MultiSelectorElement } from '../Abstracts/MultiSelector/MultiSelectorElement';
import { comboElementTemplate } from './ComboElementTemplate';
import { ComboItemElement } from './ComboItemElement';
import { comboElementJoyStyle } from './Themes/ComboElement.Joy';
import { comboElementRetroStyle } from './Themes/ComboElement.Retro';
import { comboElementCosmopolitanStyle } from './Themes/ComboElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
import { Slottable } from '../../../Behaviors/Slottable';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { ComboElementIntl } from './ComboElementIntl';
import { IntlController } from '../../../../Intl/IntlController';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { EmptyStateElement } from '../../States/Empty/EmptyStateElement';
import { TextAlignment } from '../../../Types/TextAlignment';
// #endregion
/**
 * Combo - A user interface component that combines multiple elements or options into a single selectable unit.
 *
 * @element mosaik-combo
 *
 * @description
 * The Combo component is a versatile UI element that allows users to choose from a set of options or elements presented together within a single unit. It often consists of a dropdown or pop-up menu that displays a list of available choices when activated. Combos are commonly used for selecting items from a list, applying filters, or choosing configurations.
 *
 * @category Selectors
 *
 * @fires selectionChanged - Fired when the selection has changed.
 *
 * @keyhandle UpArrow - Selects the previous item.
 * @keyhandle DownArrow - Selects the next item.
 * @keyhandle Space - Toggles the dropdown.
 * @keyhandle Enter - Toggles the dropdown.
 * @keyhandle Escape - Closes the dropdown if it is open, otherwise clears the value.
 * @keyhandle Tab - Closes the dropdown.
 *
 * @dependency {ComboItemElement} mosaik-combo-item - ComboItemElement
 * @dependency {TextBoxElement} mosaik-text-box - TextBoxElement
 * @dependency {TextBoxElement} mosaik-text-box - TextBoxElement
 * @dependency {ButtonElement} mosaik-button - ButtonElement
 * @dependency {FloatingElement} mosaik-floating - FloatingElement
 * @dependency {PortalElement} mosaik-portal - PortalElement
 * @dependency {EmptyStateElement} mosaik-empty-state - EmptyStateElement
 *
 * @example
 * ```html
 * <mosaik-combo label="Select a Color">
 *     <mosaik-combo-item value="red" label="Red"></mosaik-combo-item>
 *     <mosaik-combo-item value="green" label="Green"></mosaik-combo-item>
 *     <mosaik-combo-item value="blue" label="Blue"></mosaik-combo-item>
 * </mosaik-combo>
 * ```
 *
 * @public
 */
let ComboElement = class ComboElement extends Slottable(Themeable(DropDownable(Appearanceable(Variantable(Labelable(Clearable(Disableable(Invalidable(Valueable(MultiSelectorElement)))))))))) {
    // #region Fields
    _inputElement;
    _popupElement;
    _clickOutsideController;
    _intl;
    _itemsClickSubscriptions;
    _selectionMode;
    _value;
    _placeholder;
    _required;
    _textAlign;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._selectionMode = SelectionMode.Single;
        this._value = null;
        this._placeholder = '';
        this._required = false;
        this._textAlign = TextAlignment.Left;
        this._itemsClickSubscriptions = new Array();
        this._clickOutsideController = new ClickOutsideController(this, {
            skipInitial: true,
            callback: () => this.close()
        });
        this._intl = new IntlController(this, {
            factory: () => new ComboElementIntl()
        });
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-combo';
    }
    /**
     * Gets or sets the `selectionMode` property.
     *
     * @public
     * @attr
     */
    get selectionMode() {
        return this._selectionMode;
    }
    set selectionMode(value) {
        if (this._selectionMode !== value) {
            this._selectionMode = value;
            this.requestUpdate('selectionMode');
        }
    }
    /**
     * Gets or sets the `value` property.
     *
     * @override
     * @public
     * @attr
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Determines whether the component is required or not.
     * If `true`, the component will require a value when submitted.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Determines the text alignment of the component.
     *
     * @public
     * @attr
     */
    get textAlign() {
        return this._textAlign;
    }
    set textAlign(value) {
        if (this._textAlign !== value) {
            this._textAlign = value;
            this.requestUpdate('textAlign');
        }
    }
    /**
     * Gets the items of the Combo.
     *
     * @remark
     * It is important to override the base class property to ensure that only
     * {@link ComboItemElement} instances are returned.
     *
     * @public
     * @readonly
     * @ignore
     */
    get items() {
        return super.items.filter((x) => x instanceof ComboItemElement);
    }
    /**
     * Returns the `intl` property.
     *
     * @public
     * @readonly
     */
    get intl() {
        return this._intl.intl;
    }
    // #endregion
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     */
    reset() {
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement?.checkValidity() ?? true
            : true;
    }
    /**
     * Clears the value of the element but not the validation.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            this.emit('input', {
                bubbles: true,
                composed: true
            });
            this.emit('change', {
                bubbles: true,
                composed: true
            });
        }
        return isCleared;
    }
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this.keyboard
            .add([Key.UpArrow], () => this.selectPrevious(), undefined, { preventDefault: true })
            .add([Key.DownArrow], () => this.selectNext(), undefined, { preventDefault: true })
            .add([Key.Space, Key.Enter], () => this.toggle(), undefined, { preventDefault: true })
            .add([Key.Escape], () => {
            if (this.isDropDownOpen) {
                this.close();
            }
            else {
                this.clear();
            }
        }, undefined, { preventDefault: true })
            .add([Key.Tab], () => this.close());
    }
    /**
     * @protected
     * @override
     */
    onItemsChanged() {
        super.onItemsChanged();
        // reset all click handler if items are changed.
        this._itemsClickSubscriptions.forEach((x) => x.dispose());
        this.items.forEach((x) => {
            this._itemsClickSubscriptions.push(on(x, 'click', () => {
                if (x.disabled) {
                    return;
                }
                this.onSelectItem(x);
                // when a child is clicked, the popup closes, so we need to focus the input.
                requestAnimationFrame(() => {
                    this._inputElement?.focus();
                });
            }, false));
        });
        const current = this.tryGetPossibleItem();
        if (current) {
            this.onSelectItem(current);
        }
    }
    /**
     * @protected
     * @override
     */
    onSelectionChanged(oldIndex, newIndex) {
        super.onSelectionChanged(oldIndex, newIndex, () => {
            const current = this.selectedItem;
            // unselect siblings
            // this.items.forEach(y => y.isActive = false);
            if (current) {
                current.isActive = true;
                // check if the the value is null (means no item is selected); otherwise, add the selected item to the value.
                if (this.value === null || this.value === undefined) {
                    // initialize the value and set it to the selected item.
                    this.value = [String(current.value ?? current.label)];
                }
                else {
                    // set the value to the selected item.
                    this.value.push(String(current.value ?? current.label));
                }
            }
        });
        this.requestUpdate();
        this.close();
    }
    /**
     * @protected
     */
    onSelectionModePropertyChanged(prev, next) {
        if (prev !== next) {
            if (next) {
                // request update children changed
                this.items.forEach((x) => x.requestUpdate());
            }
        }
    }
    /**
     * @protected
     */
    onVariantPropertyChanged(_prev, next) {
        const items = getSlotElements(this.shadowRoot, undefined, ComboItemElement);
        if (next) {
            items.forEach((x) => x.variant = next);
        }
    }
    /**
     * @protected
     */
    onAppearancePropertyChanged(_prev, _next) {
        const items = getSlotElements(this.shadowRoot, undefined, ComboItemElement);
        // if (next) {
        //     items.forEach(x => {
        //         x.appearance = next;
        //     });
        // }
    }
    /**
     * @protected
     */
    onDisabledPropertyChanged(_prev, next) {
        this.items.forEach((x) => x.disabled = next ?? false);
        if (next) {
            this.close();
        }
    }
    /**
     * @protected
     */
    onIsDropDownOpenPropertyChanged(_prev, next) {
        if (next) {
            this._clickOutsideController.observe();
        }
        else {
            this._clickOutsideController.unobserve();
        }
    }
    /**
     * @param active - A value indicating whether the floating is active.
     *
     * @private
     * @template
     */
    onFloatingActiveChanged(active) {
        // when the floating opens, we want to scroll to the selected item.
        if (active) {
            const activeItem = this.items.find((x) => x.isActive);
            const scrollable = this._popupElement?.getScrollableElement();
            if (activeItem && scrollable) {
                requestAnimationFrame(() => {
                    ScrollerServiceLocator.current.scrollToElementInContainer(scrollable, activeItem, { behavior: 'instant' });
                });
            }
        }
    }
    /**
     * @param item - The item to select.
     * @param force - A value indicating whether to force the selection.
     *
     * @private
     */
    onSelectItem(item, force) {
        if (!item.isActive || force) {
            this.select(item);
            this.requestUpdate();
            this.close();
        }
    }
    /**
     * @private
     */
    tryGetPossibleItem() {
        const possibleItem = this.items.find((x) => x.isActive || x.isSelected || this.value?.includes(x.label) || (x.value && this.value?.includes(x.value.toString())));
        return possibleItem ?? null;
    }
};
__decorate([
    QueryChild('[part="input"]'),
    __metadata("design:type", HTMLInputElement)
], ComboElement.prototype, "_inputElement", void 0);
__decorate([
    QueryChild('[part="popup"]'),
    __metadata("design:type", FloatingElement)
], ComboElement.prototype, "_popupElement", void 0);
__decorate([
    Attribute({ type: SelectionMode }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ComboElement.prototype, "selectionMode", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], ComboElement.prototype, "value", null);
__decorate([
    Property({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ComboElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ComboElement.prototype, "required", null);
__decorate([
    Attribute({ type: TextAlignment }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ComboElement.prototype, "textAlign", null);
__decorate([
    Watch('selectionMode', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ComboElement.prototype, "onSelectionModePropertyChanged", null);
__decorate([
    Watch('variant', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ComboElement.prototype, "onVariantPropertyChanged", null);
__decorate([
    Watch('appearance', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ComboElement.prototype, "onAppearancePropertyChanged", null);
__decorate([
    Watch('disabled', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], ComboElement.prototype, "onDisabledPropertyChanged", null);
__decorate([
    Watch('isDropDownOpen', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], ComboElement.prototype, "onIsDropDownOpenPropertyChanged", null);
ComboElement = __decorate([
    Component({
        selector: 'mosaik-combo',
        template: comboElementTemplate,
        themes: {
            joy: comboElementJoyStyle,
            retro: comboElementRetroStyle,
            cosmopolitan: comboElementCosmopolitanStyle
        },
        imports: [
            ComboItemElement,
            // ComboItemGroupElement,
            TextBoxElement,
            ButtonElement,
            PortalElement,
            FloatingElement,
            EmptyStateElement
        ]
    }),
    __metadata("design:paramtypes", [])
], ComboElement);
export { ComboElement };
//# sourceMappingURL=ComboElement.js.map