// #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 { 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 { 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 { comboElementMemphisStyle } from './Themes/ComboElement.Memphis';
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';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
// #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)
 * @slot dropdown-header - Header content at the top of the dropdown
 * @slot dropdown-footer - Footer content at the bottom of the dropdown
 *
 * @csspart input - Text input field for typing and selection display
 * @csspart dropdown - Dropdown container for options list
 * @csspart options - Options list container within the dropdown
 * @csspart trigger - Dropdown trigger button or indicator
 * @csspart selected - Container for displaying selected items (multi-select)
 * @csspart clear - Clear button for removing selections
 *
 * @cssprop --combo-input-padding - Internal padding for the input field
 * @cssprop --combo-dropdown-max-height - Maximum height for the dropdown list
 * @cssprop --combo-option-padding - Padding for individual dropdown options
 * @cssprop --combo-selected-item-margin - Margin between selected items
 * @cssprop --combo-border-radius - Border radius for the combo component
 * @cssprop --combo-focus-ring-color - Focus ring color for accessibility
 *
 * @fires cleared - Dispatched when the selection is cleared by user action
 * @fires selectionChanged - Dispatched when the selected value(s) change
 *
 * @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
 *
 * @dependency TextBoxElement - For text input and editing functionality
 * @dependency FloatingElement - For dropdown positioning and overlay management
 * @dependency ComboItemElement - For individual selectable options
 * @dependency ButtonElement - For dropdown trigger and action buttons
 * @dependency EmptyStateElement - For displaying no options available state
 * @dependency PortalElement - For dropdown portal rendering
 *
 * @example
 * ```html
 * <!-- Simple dropdown selection -->
 * <mosaik-combo label="Select Country" placeholder="Choose a country">
 *   <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>
 *
 * <!-- Searchable combo with custom options -->
 * <mosaik-combo
 *   label="Programming Language"
 *   filterable="true"
 *   allow-custom="true">
 *   <mosaik-combo-item value="javascript">JavaScript</mosaik-combo-item>
 *   <mosaik-combo-item value="typescript">TypeScript</mosaik-combo-item>
 *   <mosaik-combo-item value="python">Python</mosaik-combo-item>
 *   <mosaik-combo-item value="rust">Rust</mosaik-combo-item>
 * </mosaik-combo>
 *
 * <!-- Multi-select combo -->
 * <mosaik-combo
 *   label="Select Skills"
 *   selection-mode="multiple"
 *   max-selected="5">
 *   <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 -->
 * <mosaik-combo label="Select Framework">
 *   <div slot="dropdown-header">
 *     <mosaik-text variant="caption">Frontend Frameworks</mosaik-text>
 *   </div>
 *   <mosaik-combo-item value="react" group="frontend">React</mosaik-combo-item>
 *   <mosaik-combo-item value="angular" group="frontend">Angular</mosaik-combo-item>
 *   <mosaik-combo-item value="vue" group="frontend">Vue.js</mosaik-combo-item>
 *   <mosaik-divider></mosaik-divider>
 *   <mosaik-combo-item value="express" group="backend">Express.js</mosaik-combo-item>
 *   <mosaik-combo-item value="nestjs" group="backend">NestJS</mosaik-combo-item>
 * </mosaik-combo>
 * ```
 *
 * @public
 */
let ComboElement = ComboElement_1 = class ComboElement extends Slottable(DropDownable(Appearanceable(Variantable(Labelable(Clearable(Invalidable(Disableable(Valueable(Themeable(MultiSelectorElement)))))))))) {
    // #region Fields
    _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 `{@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 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.
     *
     * @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
     */
    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) {
        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._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) {
        if (!item.isActive || force) {
            this.select(item);
            this.requestUpdate();
            this.close();
        }
    }
    /**
     * @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