import { MXSelectionValueComponent, MXLookComponent, AXHotkeysService, convertArrayToDataSource, AX_SELECTION_DATA_TOKEN, AXDataSource, AXComponent, AXFocusableComponent, AXValuableComponent, AXClearableComponent, AXClosableComponent, AXSearchableComponent, MXSelectionBridgeService, AXCommonModule } from '@acorex/cdk/common';
import { AXDecoratorGenericComponent, AXDecoratorCloseButtonComponent, AXDecoratorModule } from '@acorex/components/decorators';
import { MXDropdownBoxBaseComponent, AXDropdownBoxComponent, AXDropdownModule } from '@acorex/components/dropdown';
import { AXListComponent, AXListModule } from '@acorex/components/list';
import { AXLoadingComponent, AXLoadingModule } from '@acorex/components/loading';
import { AXSearchBoxComponent } from '@acorex/components/search-box';
import { AXTranslatorPipe, AXTranslationModule } from '@acorex/core/translation';
import { AXUnsubscriber } from '@acorex/core/utils';
import { NgTemplateOutlet, NgClass, AsyncPipe, CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { input, inject, signal, linkedSignal, afterNextRender, forwardRef, HostListener, ViewChild, ContentChild, Input, ViewEncapsulation, ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import * as i1 from '@angular/forms';
import { FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
import { isEqual, last, findLastIndex, get, nth } from 'lodash-es';
import { classes } from 'polytype';
import { AXBadgeModule } from '@acorex/components/badge';
import { AXCheckBoxModule } from '@acorex/components/check-box';
import { AXPopoverModule } from '@acorex/components/popover';
import { A11yModule } from '@angular/cdk/a11y';
import { AXTextBoxModule } from '@acorex/components/text-box';

/**
 * The Button is a component which detects user interaction and triggers a corresponding event
 * @category
 */
class AXSelectBoxComponent extends classes(MXDropdownBoxBaseComponent, MXSelectionValueComponent, MXLookComponent) {
    constructor() {
        super(...arguments);
        /**
         * Determines if an item is truncated.
         *
         * @defaultValue true
         */
        this.isItemTruncated = input(true, ...(ngDevMode ? [{ debugName: "isItemTruncated" }] : []));
        /**
         * Determines if a tooltip is shown for an item.
         *
         * @defaultValue false
         */
        this.showItemTooltip = input(false, ...(ngDevMode ? [{ debugName: "showItemTooltip" }] : []));
        /** Height of each list item in pixels, or 'auto' to let list measure. */
        this.itemHeight = input(40, ...(ngDevMode ? [{ debugName: "itemHeight" }] : []));
        /** Maximum number of visible items before scrolling. */
        this.maxVisibleItems = input(5, ...(ngDevMode ? [{ debugName: "maxVisibleItems" }] : []));
        /** @ignore */
        this.hotKeyService = inject(AXHotkeysService);
        /** @ignore */
        this.isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : []));
        /** @ignore */
        this.searchValue = signal('', ...(ngDevMode ? [{ debugName: "searchValue" }] : []));
        /** @ignore */
        this.renderList = signal(false, ...(ngDevMode ? [{ debugName: "renderList" }] : []));
        /** @ignore */
        this._dropdownWidth = linkedSignal(() => this.dropdownWidth(), ...(ngDevMode ? [{ debugName: "_dropdownWidth" }] : []));
        /** @ignore */
        this._dropdownHeight = signal('auto', ...(ngDevMode ? [{ debugName: "_dropdownHeight" }] : []));
        /** @ignore */
        this._listDataSource = convertArrayToDataSource([], {
            key: this.valueField,
            pageSize: 10,
        });
        this.#init = afterNextRender(() => {
            const formField = this.getHostElement().closest('ax-form-field');
            if (formField?.classList.contains('ax-state-floating-label')) {
                this.getHostElement().classList.add('ax-float-label');
            }
        });
        /**
         * The width of the dropdown in pixels.
         * @defaultValue null
         */
        this.dropdownWidth = input(null, ...(ngDevMode ? [{ debugName: "dropdownWidth" }] : []));
        this.searchBoxAutoFocus = input(true, ...(ngDevMode ? [{ debugName: "searchBoxAutoFocus" }] : []));
        /**
         * Service for managing selection data, injected via `AX_SELECTION_DATA_TOKEN`.
         */
        this.selectionService = inject(AX_SELECTION_DATA_TOKEN);
        /** @ignore */
        this._unsubscriber = inject(AXUnsubscriber);
    }
    #init;
    /**
     * Gets the data source for the component, which can be either an `AXDataSource` or an array of items.
     * @returns {AXDataSource<any> | any[]}
     */
    get dataSource() {
        return this._originalDataSource;
    }
    /**
     * Sets the data source, either as an `AXDataSource` or an array.
     * @param {AXDataSource<any> | any[]} v
     */
    set dataSource(v) {
        // check if the data source is the same
        if (Array.isArray(v) && Array.isArray(this._originalDataSource) && isEqual(v, this._originalDataSource)) {
            return;
        }
        if (v instanceof AXDataSource && v == this._originalDataSource) {
            return;
        }
        //
        this._originalDataSource = v;
        if (Array.isArray(v)) {
            this._listDataSource = convertArrayToDataSource(v, {
                key: this.valueField,
                pageSize: 10,
            });
        }
        else {
            this._listDataSource = this.dataSource;
        }
        //
        this.onChangedSubscription?.unsubscribe();
        this.onChangedSubscription = this._listDataSource.onChanged
            .pipe(this._unsubscriber.takeUntilDestroy)
            .subscribe(() => {
            this.updateDropdownSize();
            // Force refresh of selected items when data source changes
            this.forceRefreshSelectedItems();
        });
        //
        this.onLoadingChangedSubscription?.unsubscribe();
        this.onLoadingChangedSubscription = this._listDataSource.onLoadingChanged
            .pipe(this._unsubscriber.takeUntilDestroy)
            .subscribe((loading) => {
            this.isLoading.set(loading);
        });
        // After setting data source, try to fetch item data if needed
        setTimeout(() => this.fetchItemDataIfNeeded(), 0);
    }
    /** @ignore */
    ngOnInit() {
        super.ngOnInit();
        //
        this.registerValidation();
        // Proactively fetch item data if we have a value but no corresponding item
        this.fetchItemDataIfNeeded();
    }
    /**
     * Proactively fetches item data if the component has a value but no corresponding item data.
     * This prevents showing "loading..." when the component has a value.
     */
    async fetchItemDataIfNeeded() {
        if (this.value && this._listDataSource && !this.selectedItems?.length) {
            try {
                const item = await this.getItemByKey(this.value);
                if (item) {
                    // Force refresh to update the display
                    this.forceRefreshSelectedItems();
                }
            }
            catch (error) {
                console.warn('Failed to fetch item data:', error);
            }
        }
    }
    /** @ignore */
    ngOnDestroy() {
        this.searchBox?.onKeyDown.unsubscribe();
        this.onChangedSubscription?.unsubscribe();
        this.onLoadingChangedSubscription?.unsubscribe();
    }
    /**
     * Retrieves an item by its key.
     * @param {any} key
     */
    getItemByKey(key) {
        // Use the data source's byKey method if available
        if (this._listDataSource && typeof this._listDataSource.byKey === 'function') {
            return this._listDataSource.byKey(key);
        }
        // Fallback to find method if byKey is not available
        if (this._listDataSource && typeof this._listDataSource.find === 'function') {
            return this._listDataSource.find(key);
        }
        // If neither method is available, return null
        console.warn('No byKey or find method available on data source');
        return null;
    }
    /** @ignore */
    _handleOnOpenedEvent(e) {
        if (!this.renderList()) {
            this.renderList.set(true);
            this.list?.render();
        }
        else if (!this._listDataSource.totalCount || this._listDataSource.totalCount == 0) {
            this.list?.refresh(false);
        }
        this._handleFocus();
        //
        this.onOpened.emit({
            component: this,
            isUserInteraction: e.isUserInteraction,
        });
        this.updateDropdownSize();
        // Force refresh of selected items when opening to show updated text
        this.forceRefreshSelectedItems();
    }
    /** @ignore */
    _handleOnClosedEvent(e) {
        //this.input.focus();
        this.onClosed.emit({
            component: this,
            isUserInteraction: e.isUserInteraction,
        });
        this._unsubscriber.unsubscribe();
    }
    /** @ignore */
    _handleFocus() {
        setTimeout(() => {
            if (this.searchBox) {
                this.searchBox.look = 'flat';
                if (this.searchBoxAutoFocus()) {
                    this.searchBox.focus();
                }
                //TODO: unsubscribe
                this.hotKeyService
                    .addShortcut({ keys: 'Control.f', element: this.panel.nativeElement })
                    .pipe(this._unsubscriber.takeUntilDestroy)
                    .subscribe(() => {
                    this.searchBox.focus();
                });
                this.searchBox.onKeyDown.pipe(this._unsubscriber.takeUntilDestroy).subscribe((e) => {
                    if (e.nativeEvent.code === 'ArrowDown' || e.nativeEvent.key === 'ArrowDown') {
                        this.list?.focus();
                        e.nativeEvent.preventDefault();
                    }
                });
            }
            else {
                this.list?.focus();
            }
        });
    }
    /** @ignore */
    _handleBadgeRemove(e, item) {
        this.unselectItems(item);
        e.stopPropagation();
    }
    /** @ignore */
    _handleValueChanged(e) {
        if (e.isUserInteraction) {
            if (!this.multiple) {
                this.close();
            }
            this.commitValue(e.component.selectedItems, true);
        }
    }
    /** @ignore */
    _handleItemClick(e) {
        this.onItemClick.emit(e);
        if (!this.multiple) {
            this.close();
        }
    }
    /** @ignore */
    _handleItemSelected(e) {
        this.onItemSelected.emit(e);
        if (!this.multiple) {
            this.close();
        }
    }
    /** @ignore */
    setDropdownSize(count = 0) {
        if (this.dropdown.isActionsheetStyle) {
            const itemPx = typeof this.itemHeight() === 'number' ? this.itemHeight() : 40;
            this._dropdownHeight.set(['auto', '0px'].includes(this._dropdownHeight()) ? `${Math.min(15, count) * itemPx}px` : this._dropdownHeight());
            this._dropdownWidth.set('100%');
        }
        else {
            const hostWidth = Math.max(this.getHostElement().offsetWidth, Number(this.dropdownWidth()));
            const itemPx = typeof this.itemHeight() === 'number' ? this.itemHeight() : 40;
            const maxItems = Number(this.maxVisibleItems());
            this._dropdownWidth.set(`${hostWidth}px`);
            this._dropdownHeight.set(count == 0 ? 'auto' : `${Math.min(maxItems, count) * itemPx}px`);
        }
        setTimeout(() => {
            this.dropdown.updatePosition();
        });
    }
    updateDropdownPosition() {
        setTimeout(() => {
            this.dropdown.updatePosition();
        });
    }
    updateDropdownSize() {
        setTimeout(() => {
            this.setDropdownSize(this._listDataSource.totalCount);
            this.updateDropdownPosition();
            this.list?.render();
        });
    }
    internalValueChanged(value) {
        super.internalValueChanged(value);
        this.updateDropdownPosition();
        // Try to fetch item data when value changes
        setTimeout(() => this.fetchItemDataIfNeeded(), 0);
    }
    /** @ignore */
    _handleKeydown(e) {
        if (e.code === 'ArrowDown' || e.code === 'ArrowUp') {
            this.selectItemByNav(e.code === 'ArrowDown' ? 1 : -1);
            e.preventDefault();
        }
        else if (e.code === 'Backspace') {
            this.unselectItems(this.selectedItems.pop());
            e.preventDefault();
        }
        // if ((e.code === 'Space' || e.code === 'Enter') && this.hasItems) {
        //     if (this.readonly || this.disabled) {
        //         e.preventDefault();
        //         e.stopPropagation();
        //         return;
        //     }
        //     const id = document.activeElement?.closest('li')?.dataset?.id;
        //     this.toggleSelect(id);
        //     e.preventDefault();
        //     e.stopPropagation()
        // }
    }
    /** @ignore */
    selectItemByNav(sign) {
        if (Array.isArray(this.dataSource) && !this.multiple) {
            const items = this.normalizeItemsList(this.dataSource);
            const _last = last(this.selectedItems);
            let i = -1;
            if (_last) {
                i = findLastIndex(items, [this.valueField, get(_last, this.valueField)]);
            }
            i += sign;
            if (i < 0 || i >= items.length)
                return;
            const next = nth(items, i);
            if (next) {
                this.selectItems(next);
            }
        }
        else {
            this.open();
        }
    }
    /**
     * Filters the data source based on the provided search term.
     * @param {string} term
     */
    search(term) {
        this.searchValue.set(term);
        if (term) {
            this._listDataSource.filter({
                field: this.textField,
                value: term,
                operator: { type: 'contains' },
            });
        }
        else {
            this._listDataSource.clearFilter();
        }
        this._listDataSource.refresh();
    }
    /**
     * Refreshes the component by resetting state, clearing selection cache, refreshing the list, and closing the component.
     */
    refresh() {
        this.reset(false);
        this.clearSelectionCache();
        this.list?.refresh();
        this.close();
    }
    hostClickListener() {
        this.toggle();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.3", type: AXSelectBoxComponent, isStandalone: true, selector: "ax-select-box", inputs: { disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: false, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: false, isRequired: false, transformFunction: null }, tabIndex: { classPropertyName: "tabIndex", publicName: "tabIndex", isSignal: false, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: false, isRequired: false, transformFunction: null }, minValue: { classPropertyName: "minValue", publicName: "minValue", isSignal: false, isRequired: false, transformFunction: null }, maxValue: { classPropertyName: "maxValue", publicName: "maxValue", isSignal: false, isRequired: false, transformFunction: null }, value: { classPropertyName: "value", publicName: "value", isSignal: false, isRequired: false, transformFunction: null }, state: { classPropertyName: "state", publicName: "state", isSignal: false, isRequired: false, transformFunction: null }, name: { classPropertyName: "name", publicName: "name", isSignal: false, isRequired: false, transformFunction: null }, id: { classPropertyName: "id", publicName: "id", isSignal: false, isRequired: false, transformFunction: null }, type: { classPropertyName: "type", publicName: "type", isSignal: false, isRequired: false, transformFunction: null }, look: { classPropertyName: "look", publicName: "look", isSignal: false, isRequired: false, transformFunction: null }, multiple: { classPropertyName: "multiple", publicName: "multiple", isSignal: false, isRequired: false, transformFunction: null }, valueField: { classPropertyName: "valueField", publicName: "valueField", isSignal: false, isRequired: false, transformFunction: null }, textField: { classPropertyName: "textField", publicName: "textField", isSignal: false, isRequired: false, transformFunction: null }, disabledField: { classPropertyName: "disabledField", publicName: "disabledField", isSignal: false, isRequired: false, transformFunction: null }, textTemplate: { classPropertyName: "textTemplate", publicName: "textTemplate", isSignal: false, isRequired: false, transformFunction: null }, selectedItems: { classPropertyName: "selectedItems", publicName: "selectedItems", isSignal: false, isRequired: false, transformFunction: null }, isItemTruncated: { classPropertyName: "isItemTruncated", publicName: "isItemTruncated", isSignal: true, isRequired: false, transformFunction: null }, showItemTooltip: { classPropertyName: "showItemTooltip", publicName: "showItemTooltip", isSignal: true, isRequired: false, transformFunction: null }, itemHeight: { classPropertyName: "itemHeight", publicName: "itemHeight", isSignal: true, isRequired: false, transformFunction: null }, maxVisibleItems: { classPropertyName: "maxVisibleItems", publicName: "maxVisibleItems", isSignal: true, isRequired: false, transformFunction: null }, dataSource: { classPropertyName: "dataSource", publicName: "dataSource", isSignal: false, isRequired: false, transformFunction: null }, minRecordsForSearch: { classPropertyName: "minRecordsForSearch", publicName: "minRecordsForSearch", isSignal: false, isRequired: false, transformFunction: null }, caption: { classPropertyName: "caption", publicName: "caption", isSignal: false, isRequired: false, transformFunction: null }, itemTemplate: { classPropertyName: "itemTemplate", publicName: "itemTemplate", isSignal: false, isRequired: false, transformFunction: null }, selectedTemplate: { classPropertyName: "selectedTemplate", publicName: "selectedTemplate", isSignal: false, isRequired: false, transformFunction: null }, emptyTemplate: { classPropertyName: "emptyTemplate", publicName: "emptyTemplate", isSignal: false, isRequired: false, transformFunction: null }, loadingTemplate: { classPropertyName: "loadingTemplate", publicName: "loadingTemplate", isSignal: false, isRequired: false, transformFunction: null }, dropdownWidth: { classPropertyName: "dropdownWidth", publicName: "dropdownWidth", isSignal: true, isRequired: false, transformFunction: null }, searchBoxAutoFocus: { classPropertyName: "searchBoxAutoFocus", publicName: "searchBoxAutoFocus", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { valueChange: "valueChange", stateChange: "stateChange", onValueChanged: "onValueChanged", onBlur: "onBlur", onFocus: "onFocus", readonlyChange: "readonlyChange", disabledChange: "disabledChange", onOpened: "onOpened", onClosed: "onClosed", onItemSelected: "onItemSelected", onItemClick: "onItemClick" }, host: { attributes: { "ngSkipHydration": "true" }, listeners: { "keydown": "_handleKeydown($event)", "click": "hostClickListener()" } }, providers: [
            { provide: AXComponent, useExisting: AXSelectBoxComponent },
            { provide: AXFocusableComponent, useExisting: AXSelectBoxComponent },
            { provide: AXValuableComponent, useExisting: AXSelectBoxComponent },
            { provide: AXClearableComponent, useExisting: AXSelectBoxComponent },
            { provide: AXClosableComponent, useExisting: AXSelectBoxComponent },
            { provide: AXSearchableComponent, useExisting: AXSelectBoxComponent },
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => AXSelectBoxComponent),
                multi: true,
            },
            {
                provide: AX_SELECTION_DATA_TOKEN,
                useClass: MXSelectionBridgeService,
            },
            AXUnsubscriber,
        ], queries: [{ propertyName: "searchBox", first: true, predicate: AXSearchBoxComponent, descendants: true }], viewQueries: [{ propertyName: "panel", first: true, predicate: ["panel"], descendants: true }, { propertyName: "list", first: true, predicate: AXListComponent, descendants: true }, { propertyName: "dropdown", first: true, predicate: AXDropdownBoxComponent, descendants: true, static: true }], usesInheritance: true, ngImport: i0, template: "<ax-dropdown-box\n  [class.ax-state-multiple]=\"multiple\"\n  (onOpened)=\"_handleOnOpenedEvent($event)\"\n  (onClosed)=\"_handleOnClosedEvent($event)\"\n  (focus)=\"emitOnFocusEvent($event)\"\n  (blur)=\"emitOnBlurEvent($event)\"\n  [disabled]=\"disabled\"\n  [look]=\"look\"\n  [popoverWidth]=\"dropdownWidth()\"\n>\n  <ng-container input>\n    <ng-content select=\"ax-prefix\"> </ng-content>\n    <div\n      class=\"ax-editor ax-chips-container ax-content ax-input\"\n      [class.ax-state-multiple]=\"multiple\"\n      [tabindex]=\"tabIndex\"\n    >\n      @if (selectedItems.length === 0) {\n        <div class=\"ax-placeholder\" role=\"textbox\" area-readonly=\"true\">\n          {{ placeholder | translate | async }}\n        </div>\n      }\n      @for (item of selectedItems; track $index) {\n        @if (selectedTemplate) {\n          <ng-template\n            [ngTemplateOutlet]=\"selectedTemplate\"\n            [ngTemplateOutletContext]=\"{ $implicit: { data: item } }\"\n          ></ng-template>\n        } @else {\n          <div class=\"ax-chips\">\n            {{ getDisplayText(item) | translate | async }}\n            @if (!disabled && !readonly && multiple) {\n              <span class=\"ax-icon ax-icon-close\" (click)=\"_handleBadgeRemove($event, item)\"> </span>\n            }\n          </div>\n        }\n      }\n    </div>\n    @if (selectedItems?.length && !disabled && !readonly) {\n      <ng-content select=\"ax-clear-button\"></ng-content>\n    }\n    <button type=\"button\" [disabled]=\"disabled\" [tabIndex]=\"-1\" class=\"ax-editor-button\">\n      @if (isLoading()) {\n        <ax-loading></ax-loading>\n      } @else {\n        <span\n          class=\"ax-icon\"\n          [ngClass]=\"{\n            'ax-icon-chevron-down': !isOpen,\n            'ax-icon-chevron-up': isOpen,\n          }\"\n        ></span>\n      }\n    </button>\n    <ng-content select=\"ax-suffix\"> </ng-content>\n    <ng-template #search>\n      <ng-content select=\"ax-search-box\"> </ng-content>\n    </ng-template>\n  </ng-container>\n  <ng-container panel>\n    <div #panel class=\"ax-select-box-panel\" [style.min-width]=\"_dropdownWidth()\">\n      @if (dropdown.isActionsheetStyle) {\n        <ax-header class=\"ax-solid\">\n          <ax-title>{{ caption || placeholder || '@acorex:selectbox.popover.title' | translate | async }}</ax-title>\n          <ax-close-button [icon]=\"multiple ? 'ax-icon ax-icon-check' : 'ax-icon ax-icon-close'\"></ax-close-button>\n        </ax-header>\n      }\n      @if (searchBox && (!minRecordsForSearch || _listDataSource.totalCount >= minRecordsForSearch || searchValue())) {\n        <div class=\"ax-search-container\">\n          <ng-template [ngTemplateOutlet]=\"search\"></ng-template>\n        </div>\n      }\n      @if (renderList()) {\n        <ax-list\n          [ngModel]=\"value\"\n          [readonly]=\"readonly\"\n          [multiple]=\"multiple\"\n          [textField]=\"textField\"\n          [selectionMode]=\"'item'\"\n          [valueField]=\"valueField\"\n          [itemHeight]=\"itemHeight()\"\n          [itemTemplate]=\"itemTemplate\"\n          [textTemplate]=\"textTemplate\"\n          [dataSource]=\"_listDataSource\"\n          [style.height]=\"_dropdownHeight()\"\n          [loadingTemplate]=\"loadingTemplate\"\n          [isItemTruncated]=\"isItemTruncated()\"\n          [showItemTooltip]=\"showItemTooltip()\"\n          (onItemClick)=\"_handleItemClick($event)\"\n          [emptyTemplate]=\"emptyTemplate ?? empty\"\n          (onValueChanged)=\"_handleValueChanged($event)\"\n          (onItemSelected)=\"_handleItemSelected($event)\"\n        >\n        </ax-list>\n        <ng-template #empty>\n          {{ '@acorex:common.general.no-result-found' | translate | async }}\n        </ng-template>\n      }\n\n      @if (isLoading()) {\n        @if (loadingTemplate) {\n          <ng-template [ngTemplateOutlet]=\"loadingTemplate\"></ng-template>\n        }\n      }\n\n      <ng-content select=\"ax-footer\"> </ng-content>\n    </div>\n  </ng-container>\n</ax-dropdown-box>\n<ng-content select=\"ax-validation-rule\"> </ng-content>\n", styles: [".ax-editor-container.ax-fill .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-surfaceest);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-surface-high)}.ax-editor-container.ax-flat .ax-chips,.ax-editor-container.ax-outline .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-surface);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-surface-high)}.ax-editor-container.ax-solid .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-light-surface);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-light-surface)}ax-select-box .ax-chips-container{outline:0px solid transparent}.ax-xs ax-select-box,ax-select-box.ax-xs{--ax-comp-select-box-chips-padding-x: .25rem;--ax-comp-select-box-chips-padding-y: .125rem;--ax-comp-select-box-chips-font-size: .625rem;--ax-comp-editor-placeholder-space-x: .375rem}.ax-sm ax-select-box,ax-select-box.ax-sm{--ax-comp-select-box-chips-padding-x: .25rem;--ax-comp-select-box-chips-padding-y: .125rem;--ax-comp-select-box-chips-font-size: .75rem;--ax-comp-editor-placeholder-space-x: .5rem}ax-select-box,ax-select-box.ax-md{--ax-comp-select-box-chips-padding-x: .5rem;--ax-comp-select-box-chips-padding-y: .25rem;--ax-comp-select-box-chips-font-size: .875rem;--ax-comp-editor-placeholder-space-x: .75rem}.ax-lg ax-select-box,ax-select-box.ax-lg{--ax-comp-select-box-chips-padding-x: .75rem;--ax-comp-select-box-chips-padding-y: .5rem;--ax-comp-select-box-chips-font-size: 1rem;--ax-comp-editor-placeholder-space-x: .75rem}.ax-xl ax-select-box,ax-select-box.ax-xl{--ax-comp-select-box-chips-padding-x: .875rem;--ax-comp-select-box-chips-padding-y: .75rem;--ax-comp-select-box-chips-font-size: 1.125rem;--ax-comp-editor-placeholder-space-x: .75rem}ax-select-box{display:block;width:100%;border-radius:var(--ax-sys-border-radius)}ax-select-box.ax-float-label .ax-editor{padding-top:1.75rem!important}ax-select-box .ax-state-disabled{opacity:.5;cursor:not-allowed}ax-select-box .ax-state-disabled .ax-content,ax-select-box .ax-state-disabled .ax-editor-button{cursor:not-allowed}ax-select-box .ax-state-disabled .ax-chips-container{cursor:not-allowed!important}ax-select-box ax-dropdown-box{border-radius:inherit!important}ax-select-box ax-dropdown-box.ax-state-multiple{height:auto;min-height:var(--ax-comp-editor-height);--ax-comp-editor-space-start-size: 0}ax-select-box ax-dropdown-box.ax-state-multiple .ax-placeholder{padding:0 var(--ax-comp-editor-placeholder-space-x)}ax-select-box .ax-chips-container{display:flex;flex:1 1 0%;min-width:0;cursor:pointer!important;-webkit-user-select:none;user-select:none;flex-wrap:wrap;align-items:center;justify-content:flex-start;gap:var(--ax-comp-select-box-chips-gap, .25rem);min-height:var(--ax-sys-size-base)}ax-select-box .ax-chips-container .ax-chips{display:block;overflow:hidden;text-wrap:nowrap;line-height:normal;text-overflow:ellipsis;padding:0 var(--ax-comp-editor-padding-x, .25rem);color:rgb(var(--ax-comp-select-box-chips-text-color));font-size:var(--ax-comp-select-box-chips-font-size)}ax-select-box .ax-chips-container.ax-state-multiple .ax-chips{background-color:rgb(var(--ax-comp-select-box-chips-bg-color));border-radius:var(--ax-comp-select-box-chips-border-radius, 999rem);border-width:var(--ax-comp-select-box-chips-border-width, 0px);padding:var(--ax-comp-select-box-chips-padding-y, .25rem) var(--ax-comp-select-box-chips-padding-x, .5rem)}ax-select-box .ax-chips-container.ax-state-multiple .ax-chips .ax-icon-close{cursor:pointer;margin-inline-start:var(--ax-comp-select-box-chips-padding-x)}ax-select-box .ax-chips-container .ax-selectbox-input{width:0px;opacity:0}ax-select-box .ax-chips-container.ax-state-multiple:has(.ax-chips){padding:var(--ax-comp-select-box-chips-container-padding, .25rem)}.ax-select-box-panel{height:fit-content}.ax-select-box-panel .ax-select-box-loading-container{display:flex;align-items:center;justify-content:center;padding:1rem}.ax-select-box-panel>ax-header .ax-icon-check{color:rgba(var(--ax-sys-color-primary-500))}.ax-select-box-panel>ax-header.ax-solid{border-bottom-width:1px;border-color:rgba(var(--ax-sys-color-border-lightest-surface))}.ax-select-box-panel>ax-header.ax-solid ax-title{font-size:1rem;line-height:1.5rem;font-weight:500}\n"], dependencies: [{ kind: "component", type: AXDropdownBoxComponent, selector: "ax-dropdown-box", inputs: ["disabled", "look", "hasInput", "popoverWidth"], outputs: ["disabledChange", "onBlur", "onFocus", "onClick", "onOpened", "onClosed"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "component", type: AXDecoratorGenericComponent, selector: "ax-footer, ax-header, ax-content, ax-divider, ax-form-hint, ax-prefix, ax-suffix, ax-text, ax-title, ax-subtitle, ax-placeholder, ax-overlay" }, { kind: "component", type: AXDecoratorCloseButtonComponent, selector: "ax-close-button", inputs: ["closeAll", "icon"] }, { kind: "component", type: AXListComponent, selector: "ax-list", inputs: ["id", "name", "disabled", "readonly", "valueField", "textField", "textTemplate", "disabledField", "multiple", "selectionMode", "isItemTruncated", "showItemTooltip", "dataSource", "itemHeight", "itemTemplate", "emptyTemplate", "loadingTemplate", "checkbox"], outputs: ["onValueChanged", "disabledChange", "readonlyChange", "onBlur", "onFocus", "onItemClick", "onItemSelected", "onScrolledIndexChanged"] }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: AXLoadingComponent, selector: "ax-loading", inputs: ["visible", "type", "context"], outputs: ["visibleChange"] }, { kind: "pipe", type: AsyncPipe, name: "async" }, { kind: "pipe", type: AXTranslatorPipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-select-box', inputs: [
                        'disabled',
                        'readonly',
                        'tabIndex',
                        'placeholder',
                        'minValue',
                        'maxValue',
                        'value',
                        'state',
                        'name',
                        'id',
                        'type',
                        'look',
                        'multiple',
                        'valueField',
                        'textField',
                        'disabledField',
                        'textTemplate',
                        'selectedItems',
                    ], outputs: [
                        'valueChange',
                        'stateChange',
                        'onValueChanged',
                        'onBlur',
                        'onFocus',
                        'readonlyChange',
                        'disabledChange',
                        'onOpened',
                        'onClosed',
                        'onItemSelected',
                        'onItemClick',
                    ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [
                        { provide: AXComponent, useExisting: AXSelectBoxComponent },
                        { provide: AXFocusableComponent, useExisting: AXSelectBoxComponent },
                        { provide: AXValuableComponent, useExisting: AXSelectBoxComponent },
                        { provide: AXClearableComponent, useExisting: AXSelectBoxComponent },
                        { provide: AXClosableComponent, useExisting: AXSelectBoxComponent },
                        { provide: AXSearchableComponent, useExisting: AXSelectBoxComponent },
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => AXSelectBoxComponent),
                            multi: true,
                        },
                        {
                            provide: AX_SELECTION_DATA_TOKEN,
                            useClass: MXSelectionBridgeService,
                        },
                        AXUnsubscriber,
                    ], host: { ngSkipHydration: 'true' }, imports: [
                        AXDropdownBoxComponent,
                        NgTemplateOutlet,
                        NgClass,
                        AXDecoratorGenericComponent,
                        AXDecoratorCloseButtonComponent,
                        AXListComponent,
                        FormsModule,
                        AXLoadingComponent,
                        AsyncPipe,
                        AXTranslatorPipe,
                    ], template: "<ax-dropdown-box\n  [class.ax-state-multiple]=\"multiple\"\n  (onOpened)=\"_handleOnOpenedEvent($event)\"\n  (onClosed)=\"_handleOnClosedEvent($event)\"\n  (focus)=\"emitOnFocusEvent($event)\"\n  (blur)=\"emitOnBlurEvent($event)\"\n  [disabled]=\"disabled\"\n  [look]=\"look\"\n  [popoverWidth]=\"dropdownWidth()\"\n>\n  <ng-container input>\n    <ng-content select=\"ax-prefix\"> </ng-content>\n    <div\n      class=\"ax-editor ax-chips-container ax-content ax-input\"\n      [class.ax-state-multiple]=\"multiple\"\n      [tabindex]=\"tabIndex\"\n    >\n      @if (selectedItems.length === 0) {\n        <div class=\"ax-placeholder\" role=\"textbox\" area-readonly=\"true\">\n          {{ placeholder | translate | async }}\n        </div>\n      }\n      @for (item of selectedItems; track $index) {\n        @if (selectedTemplate) {\n          <ng-template\n            [ngTemplateOutlet]=\"selectedTemplate\"\n            [ngTemplateOutletContext]=\"{ $implicit: { data: item } }\"\n          ></ng-template>\n        } @else {\n          <div class=\"ax-chips\">\n            {{ getDisplayText(item) | translate | async }}\n            @if (!disabled && !readonly && multiple) {\n              <span class=\"ax-icon ax-icon-close\" (click)=\"_handleBadgeRemove($event, item)\"> </span>\n            }\n          </div>\n        }\n      }\n    </div>\n    @if (selectedItems?.length && !disabled && !readonly) {\n      <ng-content select=\"ax-clear-button\"></ng-content>\n    }\n    <button type=\"button\" [disabled]=\"disabled\" [tabIndex]=\"-1\" class=\"ax-editor-button\">\n      @if (isLoading()) {\n        <ax-loading></ax-loading>\n      } @else {\n        <span\n          class=\"ax-icon\"\n          [ngClass]=\"{\n            'ax-icon-chevron-down': !isOpen,\n            'ax-icon-chevron-up': isOpen,\n          }\"\n        ></span>\n      }\n    </button>\n    <ng-content select=\"ax-suffix\"> </ng-content>\n    <ng-template #search>\n      <ng-content select=\"ax-search-box\"> </ng-content>\n    </ng-template>\n  </ng-container>\n  <ng-container panel>\n    <div #panel class=\"ax-select-box-panel\" [style.min-width]=\"_dropdownWidth()\">\n      @if (dropdown.isActionsheetStyle) {\n        <ax-header class=\"ax-solid\">\n          <ax-title>{{ caption || placeholder || '@acorex:selectbox.popover.title' | translate | async }}</ax-title>\n          <ax-close-button [icon]=\"multiple ? 'ax-icon ax-icon-check' : 'ax-icon ax-icon-close'\"></ax-close-button>\n        </ax-header>\n      }\n      @if (searchBox && (!minRecordsForSearch || _listDataSource.totalCount >= minRecordsForSearch || searchValue())) {\n        <div class=\"ax-search-container\">\n          <ng-template [ngTemplateOutlet]=\"search\"></ng-template>\n        </div>\n      }\n      @if (renderList()) {\n        <ax-list\n          [ngModel]=\"value\"\n          [readonly]=\"readonly\"\n          [multiple]=\"multiple\"\n          [textField]=\"textField\"\n          [selectionMode]=\"'item'\"\n          [valueField]=\"valueField\"\n          [itemHeight]=\"itemHeight()\"\n          [itemTemplate]=\"itemTemplate\"\n          [textTemplate]=\"textTemplate\"\n          [dataSource]=\"_listDataSource\"\n          [style.height]=\"_dropdownHeight()\"\n          [loadingTemplate]=\"loadingTemplate\"\n          [isItemTruncated]=\"isItemTruncated()\"\n          [showItemTooltip]=\"showItemTooltip()\"\n          (onItemClick)=\"_handleItemClick($event)\"\n          [emptyTemplate]=\"emptyTemplate ?? empty\"\n          (onValueChanged)=\"_handleValueChanged($event)\"\n          (onItemSelected)=\"_handleItemSelected($event)\"\n        >\n        </ax-list>\n        <ng-template #empty>\n          {{ '@acorex:common.general.no-result-found' | translate | async }}\n        </ng-template>\n      }\n\n      @if (isLoading()) {\n        @if (loadingTemplate) {\n          <ng-template [ngTemplateOutlet]=\"loadingTemplate\"></ng-template>\n        }\n      }\n\n      <ng-content select=\"ax-footer\"> </ng-content>\n    </div>\n  </ng-container>\n</ax-dropdown-box>\n<ng-content select=\"ax-validation-rule\"> </ng-content>\n", styles: [".ax-editor-container.ax-fill .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-surfaceest);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-surface-high)}.ax-editor-container.ax-flat .ax-chips,.ax-editor-container.ax-outline .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-surface);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-surface-high)}.ax-editor-container.ax-solid .ax-chips{--ax-comp-select-box-chips-bg-color: var(--ax-sys-color-light-surface);--ax-comp-select-box-chips-text-color: var(--ax-sys-color-on-light-surface)}ax-select-box .ax-chips-container{outline:0px solid transparent}.ax-xs ax-select-box,ax-select-box.ax-xs{--ax-comp-select-box-chips-padding-x: .25rem;--ax-comp-select-box-chips-padding-y: .125rem;--ax-comp-select-box-chips-font-size: .625rem;--ax-comp-editor-placeholder-space-x: .375rem}.ax-sm ax-select-box,ax-select-box.ax-sm{--ax-comp-select-box-chips-padding-x: .25rem;--ax-comp-select-box-chips-padding-y: .125rem;--ax-comp-select-box-chips-font-size: .75rem;--ax-comp-editor-placeholder-space-x: .5rem}ax-select-box,ax-select-box.ax-md{--ax-comp-select-box-chips-padding-x: .5rem;--ax-comp-select-box-chips-padding-y: .25rem;--ax-comp-select-box-chips-font-size: .875rem;--ax-comp-editor-placeholder-space-x: .75rem}.ax-lg ax-select-box,ax-select-box.ax-lg{--ax-comp-select-box-chips-padding-x: .75rem;--ax-comp-select-box-chips-padding-y: .5rem;--ax-comp-select-box-chips-font-size: 1rem;--ax-comp-editor-placeholder-space-x: .75rem}.ax-xl ax-select-box,ax-select-box.ax-xl{--ax-comp-select-box-chips-padding-x: .875rem;--ax-comp-select-box-chips-padding-y: .75rem;--ax-comp-select-box-chips-font-size: 1.125rem;--ax-comp-editor-placeholder-space-x: .75rem}ax-select-box{display:block;width:100%;border-radius:var(--ax-sys-border-radius)}ax-select-box.ax-float-label .ax-editor{padding-top:1.75rem!important}ax-select-box .ax-state-disabled{opacity:.5;cursor:not-allowed}ax-select-box .ax-state-disabled .ax-content,ax-select-box .ax-state-disabled .ax-editor-button{cursor:not-allowed}ax-select-box .ax-state-disabled .ax-chips-container{cursor:not-allowed!important}ax-select-box ax-dropdown-box{border-radius:inherit!important}ax-select-box ax-dropdown-box.ax-state-multiple{height:auto;min-height:var(--ax-comp-editor-height);--ax-comp-editor-space-start-size: 0}ax-select-box ax-dropdown-box.ax-state-multiple .ax-placeholder{padding:0 var(--ax-comp-editor-placeholder-space-x)}ax-select-box .ax-chips-container{display:flex;flex:1 1 0%;min-width:0;cursor:pointer!important;-webkit-user-select:none;user-select:none;flex-wrap:wrap;align-items:center;justify-content:flex-start;gap:var(--ax-comp-select-box-chips-gap, .25rem);min-height:var(--ax-sys-size-base)}ax-select-box .ax-chips-container .ax-chips{display:block;overflow:hidden;text-wrap:nowrap;line-height:normal;text-overflow:ellipsis;padding:0 var(--ax-comp-editor-padding-x, .25rem);color:rgb(var(--ax-comp-select-box-chips-text-color));font-size:var(--ax-comp-select-box-chips-font-size)}ax-select-box .ax-chips-container.ax-state-multiple .ax-chips{background-color:rgb(var(--ax-comp-select-box-chips-bg-color));border-radius:var(--ax-comp-select-box-chips-border-radius, 999rem);border-width:var(--ax-comp-select-box-chips-border-width, 0px);padding:var(--ax-comp-select-box-chips-padding-y, .25rem) var(--ax-comp-select-box-chips-padding-x, .5rem)}ax-select-box .ax-chips-container.ax-state-multiple .ax-chips .ax-icon-close{cursor:pointer;margin-inline-start:var(--ax-comp-select-box-chips-padding-x)}ax-select-box .ax-chips-container .ax-selectbox-input{width:0px;opacity:0}ax-select-box .ax-chips-container.ax-state-multiple:has(.ax-chips){padding:var(--ax-comp-select-box-chips-container-padding, .25rem)}.ax-select-box-panel{height:fit-content}.ax-select-box-panel .ax-select-box-loading-container{display:flex;align-items:center;justify-content:center;padding:1rem}.ax-select-box-panel>ax-header .ax-icon-check{color:rgba(var(--ax-sys-color-primary-500))}.ax-select-box-panel>ax-header.ax-solid{border-bottom-width:1px;border-color:rgba(var(--ax-sys-color-border-lightest-surface))}.ax-select-box-panel>ax-header.ax-solid ax-title{font-size:1rem;line-height:1.5rem;font-weight:500}\n"] }]
        }], propDecorators: { dataSource: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], minRecordsForSearch: [{
                type: Input
            }], caption: [{
                type: Input
            }], itemTemplate: [{
                type: Input
            }], selectedTemplate: [{
                type: Input
            }], emptyTemplate: [{
                type: Input
            }], loadingTemplate: [{
                type: Input
            }], panel: [{
                type: ViewChild,
                args: ['panel']
            }], list: [{
                type: ViewChild,
                args: [AXListComponent]
            }], searchBox: [{
                type: ContentChild,
                args: [AXSearchBoxComponent]
            }], dropdown: [{
                type: ViewChild,
                args: [AXDropdownBoxComponent, { static: true }]
            }], _handleKeydown: [{
                type: HostListener,
                args: ['keydown', ['$event']]
            }], hostClickListener: [{
                type: HostListener,
                args: ['click']
            }] } });

class AXSelectBoxModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxModule, imports: [CommonModule,
            AXCommonModule,
            FormsModule,
            AXCheckBoxModule,
            AXBadgeModule,
            AXDecoratorModule,
            AXTranslationModule,
            AXPopoverModule,
            AXLoadingModule,
            A11yModule,
            AXTextBoxModule,
            AXDropdownModule,
            AXListModule,
            AXSelectBoxComponent], exports: [AXSelectBoxComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxModule, imports: [CommonModule,
            AXCommonModule,
            FormsModule,
            AXCheckBoxModule,
            AXBadgeModule,
            AXDecoratorModule,
            AXTranslationModule,
            AXPopoverModule,
            AXLoadingModule,
            A11yModule,
            AXTextBoxModule,
            AXDropdownModule,
            AXListModule,
            AXSelectBoxComponent] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXSelectBoxModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        CommonModule,
                        AXCommonModule,
                        FormsModule,
                        AXCheckBoxModule,
                        AXBadgeModule,
                        AXDecoratorModule,
                        AXTranslationModule,
                        AXPopoverModule,
                        AXLoadingModule,
                        A11yModule,
                        AXTextBoxModule,
                        AXDropdownModule,
                        AXListModule,
                        AXSelectBoxComponent,
                    ],
                    exports: [AXSelectBoxComponent],
                    providers: [],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { AXSelectBoxComponent, AXSelectBoxModule };
//# sourceMappingURL=acorex-components-select-box.mjs.map
