// #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);
};
var ComboElement_1;
import { on } from '@breadstone/mosaik-elements';
import { ScrollerServiceLocator } from '../../../../Dom/Scroller';
import { getSlotElements } from '../../../../Dom/Slot';
import { IntlController } from '../../../../Intl/IntlController';
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 { Slottable } from '../../../Behaviors/Slottable';
import { Themeable } from '../../../Behaviors/Themeable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { ClickOutsideController } from '../../../Controllers/ClickOutsideController';
import { addInheritanceProviderController } from '../../../Controllers/InheritanceProviderController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { Appearance } from '../../../Types/Appearance';
import { Key } from '../../../Types/Key';
import { SelectionMode } from '../../../Types/SelectionMode';
import { TextAlignment } from '../../../Types/TextAlignment';
import { Variant } from '../../../Types/Variant';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { TextBoxElement } from '../../Inputs/TextBox/TextBoxElement';
import { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
import { EmptyStateElement } from '../../States/Empty/EmptyStateElement';
import { MultiSelectorElement } from '../Abstracts/MultiSelector/MultiSelectorElement';
import { ComboElementIntl } from './ComboElementIntl';
import { comboElementTemplate } from './ComboElementTemplate';
import { COMBO_INHERITANCE_CONTEXT } from './ComboInheritanceContext';
import { ComboItemElement } from './ComboItemElement';
import { comboElementCosmopolitanStyle } from './Themes/ComboElement.Cosmopolitan';
import { comboElementJoyStyle } from './Themes/ComboElement.Joy';
import { comboElementMemphisStyle } from './Themes/ComboElement.Memphis';
// #endregion
/**
 * Combo - A dropdown selection component that combines text input with a list of selectable options.
 *
 * Provides users with a searchable dropdown interface for selecting from predefined options
 * or entering custom values. Supports single and multiple selection modes with filtering,
 * autocomplete functionality, and customizable dropdown positioning.
 *
 * @name ComboElement
 * @element mosaik-combo
 * @category Selectors
 *
 * @slot - Default content area for combo items and options
 * @slot prefix - Leading content before the input (icons, labels)
 * @slot suffix - Trailing content after the input (actions, indicators)
 *
 * @csspart empty - The empty part.
 * @csspart icon - The icon part.
 * @csspart input - Text input field for typing and selection display
 * @csspart popup - The popup part.
 * @csspart portal - The portal part.
 * @csspart projection - The projection part.
 *
 * @cssprop {String} --combo-focus-ring-active-width - The focus ring active width CSS custom property.
 * @cssprop {Color} --combo-focus-ring-color - Focus ring color for accessibility
 * @cssprop {String} --combo-focus-ring-inward-offset - The focus ring inward offset CSS custom property.
 * @cssprop {String} --combo-focus-ring-outward-offset - The focus ring outward offset CSS custom property.
 * @cssprop {String} --combo-font-family - The font family CSS custom property.
 * @cssprop {String} --combo-font-letter-spacing - The font letter spacing CSS custom property.
 * @cssprop {String} --combo-font-line-height - The font line height CSS custom property.
 * @cssprop {String} --combo-font-size - The font size CSS custom property.
 * @cssprop {String} --combo-font-text-decoration - The font text decoration CSS custom property.
 * @cssprop {String} --combo-font-text-transform - The font text transform CSS custom property.
 * @cssprop {String} --combo-font-weight - The font weight CSS custom property.
 * @cssprop {String} --combo-foreground-color - The foreground color CSS custom property.
 * @cssprop {String} --combo-gap - The gap CSS custom property.
 * @cssprop {String} --combo-padding-bottom - The padding bottom CSS custom property.
 * @cssprop {String} --combo-padding-left - The padding left CSS custom property.
 * @cssprop {String} --combo-padding-right - The padding right CSS custom property.
 * @cssprop {String} --combo-padding-top - The padding top CSS custom property.
 * @cssprop {String} --combo-shadow - The shadow CSS custom property.
 * @cssprop {String} --combo-shadow-blur - The shadow blur CSS custom property.
 * @cssprop {String} --combo-shadow-color - The shadow color CSS custom property.
 * @cssprop {String} --combo-shadow-offset-x - The shadow offset x CSS custom property.
 * @cssprop {String} --combo-shadow-offset-y - The shadow offset y CSS custom property.
 * @cssprop {String} --combo-shadow-spread - The shadow spread CSS custom property.
 * @cssprop {String} --combo-transition-duration - The transition duration CSS custom property.
 * @cssprop {String} --combo-transition-mode - The transition mode CSS custom property.
 * @cssprop {String} --combo-transition-property - The transition property CSS custom property.
 * @cssprop {String} --combo-translate - The translate CSS custom property.
 *
 * @fires cleared {ClearedEvent} - Dispatched when the selection is cleared by user action
 * @fires selectionChanged {SelectionChangedEvent} - Dispatched when the selected value(s) change
 *
 * @dependency mosaik-button - The Button element.
 * @dependency mosaik-empty-state - The Empty State element.
 * @dependency mosaik-floating - The Floating element.
 * @dependency mosaik-portal - The Portal element.
 * @dependency mosaik-textbox - The Textbox element.
 *
 * @example
 * ```html
 * <!-- Simple dropdown selection -->
 * <mosaik-combo>
 *   <mosaik-combo-item value="us">United States</mosaik-combo-item>
 *   <mosaik-combo-item value="ca">Canada</mosaik-combo-item>
 *   <mosaik-combo-item value="uk">United Kingdom</mosaik-combo-item>
 * </mosaik-combo>
 *
 * <!-- Multi-select combo -->
 * <mosaik-combo selection-mode="multiple">
 *   <mosaik-combo-item value="html">HTML</mosaik-combo-item>
 *   <mosaik-combo-item value="css">CSS</mosaik-combo-item>
 *   <mosaik-combo-item value="js">JavaScript</mosaik-combo-item>
 *   <mosaik-combo-item value="react">React</mosaik-combo-item>
 *   <mosaik-combo-item value="angular">Angular</mosaik-combo-item>
 * </mosaik-combo>
 *
 * <!-- Combo with grouped options and footer -->
 * <mosaik-combo>
 *   <div slot="dropdown-header">
 *     <mosaik-text variant="caption">Frontend Frameworks</mosaik-text>
 *   </div>
 *   <mosaik-combo-item value="react">React</mosaik-combo-item>
 *   <mosaik-combo-item value="angular">Angular</mosaik-combo-item>
 *   <mosaik-combo-item value="vue">Vue.js</mosaik-combo-item>
 * </mosaik-combo>
 * ```
 *
 * @public
 *
 * @keyhandle UpArrow - Navigates to the previous option in the dropdown
 * @keyhandle DownArrow - Navigates to the next option in the dropdown
 * @keyhandle Space - Opens the dropdown or selects the focused option
 * @keyhandle Enter - Selects the focused option and closes dropdown
 * @keyhandle Escape - Closes the dropdown without selection
 * @keyhandle Home - Navigates to the first option
 * @keyhandle End - Navigates to the last option
 */
let ComboElement = ComboElement_1 = class ComboElement extends Slottable(DropDownable(Appearanceable(Variantable(Labelable(Clearable(Invalidable(Disableable(Valueable(Themeable(MultiSelectorElement)))))))))) {
    // #region Fields
    _provider = addInheritanceProviderController(this, {
        context: COMBO_INHERITANCE_CONTEXT,
        values: () => ({
            disabled: this.disabled,
            variant: this.variant
        })
    });
    _inputElement;
    _floatingElement;
    _clickOutsideController;
    _intl;
    _projectionController;
    _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, {
            ignored: () => [this._floatingElement],
            skipInitial: true,
            callback: () => this.close()
        });
        this._intl = new IntlController(this, {
            factory: () => new ComboElementIntl()
        });
        this._projectionController = new ProjectionController(this, {
            slotName: '',
            targetSelector: '[part="projection"]',
            projecting: (element) => {
                element.setAttribute(`${ComboElement_1.is}-projection`, '');
            }
        });
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     * The `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
     * `ComboItemElement` instances are returned.
     *
     * @public
     * @readonly
     * @ignore
     */
    get items() {
        return this._projectionController.elements
            .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;
    }
    /**
     * Clears the value of the element but not the validation.
     * Also clears the selected items and resets the active state.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            // Clear selected items array
            this.selectedItems.length = 0;
            // Reset isActive state for all items
            this.items.forEach((item) => {
                item.isActive = false;
                item.isChecked = false;
            });
            this.requestUpdate('selectedItems');
            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
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
        this._floatingElement = this.getTemplatePart('popup');
    }
    /**
     * @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));
        });
        this.initialSelection();
    }
    /**
     * @protected
     * @override
     */
    onSelectionChanged(oldIndex, newIndex) {
        // Get the item that is being toggled
        const toggledItem = this.items[newIndex];
        // Check if item is currently in selectedItems before the super call modifies it
        const isCurrentlySelected = toggledItem ? this.selectedItems.includes(toggledItem) : false;
        super.onSelectionChanged(oldIndex, newIndex, () => {
            if (toggledItem) {
                const itemValue = String(toggledItem.value ?? toggledItem.label);
                if (isCurrentlySelected) {
                    // Item was selected, now being deselected
                    toggledItem.isActive = false;
                    // Remove from value array
                    if (this.value && Array.isArray(this.value)) {
                        const valueIndex = this.value.indexOf(itemValue);
                        if (valueIndex > -1) {
                            this.value.splice(valueIndex, 1);
                            // Trigger reactivity by reassigning
                            this.value = [...this.value];
                        }
                    }
                }
                else {
                    // Item was not selected, now being selected
                    toggledItem.isActive = true;
                    // Add to value array
                    if (this.value === null || this.value === undefined) {
                        this.value = [itemValue];
                    }
                    else {
                        this.value = [...this.value, itemValue];
                    }
                }
            }
        });
        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._floatingElement?.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) {
        // In single selection mode, toggle the selection state
        if (this.selectionMode === SelectionMode.Single) {
            if (item.isActive && !force) {
                // Deselect the currently active item
                this.deselectItem(item);
            }
            else {
                this.select(item);
            }
        }
        else {
            // For multiple selection, always toggle
            this.select(item);
        }
        this.requestUpdate();
        this.close();
    }
    /**
     * Deselects the given item and clears the value.
     *
     * @param item - The item to deselect.
     *
     * @private
     */
    deselectItem(item) {
        item.isActive = false;
        item.isChecked = false;
        // Remove from selectedItems
        const selectedIndex = this.selectedItems.indexOf(item);
        if (selectedIndex > -1) {
            this.selectedItems.splice(selectedIndex, 1);
        }
        // Remove from value array
        const itemValue = String(item.value ?? item.label);
        if (this.value && Array.isArray(this.value)) {
            const valueIndex = this.value.indexOf(itemValue);
            if (valueIndex > -1) {
                this.value.splice(valueIndex, 1);
                this.value = this.value.length > 0 ? [...this.value] : null;
            }
        }
        this.requestUpdate('selectedItems');
        this.emit('input', {
            bubbles: true,
            composed: true
        });
        this.emit('change', {
            bubbles: true,
            composed: true
        });
    }
    /**
     * @private
     */
    initialSelection() {
        void this.updateComplete.then(() => {
            const item = this.items.find((x) => x.isActive || x.isSelected || this.value?.includes(x.label) || (x.value && this.value?.includes(x.value.toString())));
            if (item) {
                this.onSelectItem(item, true);
            }
        });
    }
};
__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 = ComboElement_1 = __decorate([
    Component({
        selector: 'mosaik-combo',
        template: comboElementTemplate,
        themes: {
            joy: comboElementJoyStyle,
            memphis: comboElementMemphisStyle,
            cosmopolitan: comboElementCosmopolitanStyle
        },
        imports: [
            ComboItemElement,
            // ComboItemGroupElement,
            TextBoxElement,
            ButtonElement,
            PortalElement,
            FloatingElement,
            EmptyStateElement
        ]
    }),
    __metadata("design:paramtypes", [])
], ComboElement);
export { ComboElement };
//# sourceMappingURL=ComboElement.js.map