import { FocusMonitor } from '@angular/cdk/a11y';
import { AsyncPipe } from '@angular/common';
import * as i0 from '@angular/core';
import { InjectionToken, inject, DestroyRef, ChangeDetectorRef, ElementRef, EventEmitter, booleanAttribute, numberAttribute, Component, ChangeDetectionStrategy, ViewEncapsulation, ViewChildren, ViewChild, Input, Output, NgModule } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import * as i5 from '@angular/forms';
import { NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms';
import * as i1 from '@koobiq/components/button';
import { KbqButton, KbqButtonModule } from '@koobiq/components/button';
import { ruRULocaleData, KBQ_LOCALE_SERVICE } from '@koobiq/components/core';
import * as i4 from '@koobiq/components/form-field';
import { KbqFormFieldModule } from '@koobiq/components/form-field';
import * as i2 from '@koobiq/components/icon';
import { KbqIconModule } from '@koobiq/components/icon';
import * as i3 from '@koobiq/components/input';
import { KbqInput, KbqInputModule } from '@koobiq/components/input';
import * as i6 from '@koobiq/components/tooltip';
import { KbqTooltipTrigger, KbqToolTipModule } from '@koobiq/components/tooltip';
import { BehaviorSubject, distinctUntilChanged, filter, debounceTime } from 'rxjs';
import { map } from 'rxjs/operators';

/** default configuration of search-expandable */
const KBQ_SEARCH_EXPANDABLE_DEFAULT_CONFIGURATION = ruRULocaleData.searchExpandable;
/** Injection Token for providing configuration of search-expandable */
const KBQ_SEARCH_EXPANDABLE_CONFIGURATION = new InjectionToken('KbqSearchExpandableConfiguration');
const defaultValue = '';
const defaultEmitValueTimeout = 200;
class KbqSearchExpandable {
    /** Placeholder for input when expanded */
    get placeholder() {
        return this._placeholder ?? this.localeData?.placeholder;
    }
    set placeholder(value) {
        this._placeholder = value;
    }
    /** localized data
     * @docs-private */
    get localeData() {
        return this.configuration;
    }
    constructor() {
        /** @docs-private */
        this.focusMonitor = inject(FocusMonitor);
        /** @docs-private */
        this.localeService = inject(KBQ_LOCALE_SERVICE, { optional: true });
        /** @docs-private */
        this.destroyRef = inject(DestroyRef);
        /** @docs-private */
        this.changeDetectorRef = inject(ChangeDetectorRef);
        /** @docs-private */
        this.nativeElement = inject(ElementRef).nativeElement;
        this.externalConfiguration = inject(KBQ_SEARCH_EXPANDABLE_CONFIGURATION, { optional: true });
        /** Current value in input. */
        this.value = new BehaviorSubject(defaultValue);
        /** state of component. */
        this.isOpened = false;
        /** Emit event by enter or not. Default is false */
        this.isEmitValueByEnterEnabled = false;
        /** Timeout in milliseconds for emit event. The default value is taken from defaultEmitValueTimeout */
        this.emitValueTimeout = defaultEmitValueTimeout;
        this._placeholder = this.localeData?.placeholder;
        /** Event emitted when the search has been toggled. */
        this.isOpenedChange = new EventEmitter();
        this.lastEmittedValue = defaultValue;
        /** @docs-private */
        this.onTouch = () => { };
        this.updateLocaleParams = () => {
            this.configuration = this.externalConfiguration || this.localeService?.getParams('searchExpandable');
            this.changeDetectorRef.markForCheck();
        };
        this.emitValue = (value, forced = false) => {
            if (value !== this.lastEmittedValue || forced) {
                this.onChange(value);
                this.lastEmittedValue = value;
            }
        };
        this.focusMonitor
            .monitor(this.nativeElement, true)
            .pipe(takeUntilDestroyed())
            .subscribe((origin) => (this.lastFocusOrigin = origin));
        this.localeService?.changes.pipe(takeUntilDestroyed()).subscribe(this.updateLocaleParams);
        if (!this.localeService) {
            this.initDefaultParams();
        }
        this.value
            .pipe(distinctUntilChanged(), filter(() => !this.isEmitValueByEnterEnabled), debounceTime(this.emitValueTimeout), takeUntilDestroyed(this.destroyRef))
            .subscribe(this.emitValue);
    }
    ngAfterViewInit() {
        this.button.changes
            .pipe(filter((queryList) => queryList.length), map((queryList) => queryList.first), takeUntilDestroyed(this.destroyRef))
            .subscribe((button) => {
            this.tooltip.disabled = true;
            this.focusMonitor.focusVia(button.elementRef.nativeElement, this.lastFocusOrigin);
            this.tooltip.disabled = false;
        });
        this.input.changes
            .pipe(filter((queryList) => queryList.length), map((queryList) => queryList.first), takeUntilDestroyed(this.destroyRef))
            .subscribe((input) => input.focus());
    }
    /** Implemented as part of ControlValueAccessor. */
    registerOnChange(fn) {
        this.onChange = fn;
    }
    /** Implemented as part of ControlValueAccessor. */
    registerOnTouched(fn) {
        this.onTouch = fn;
    }
    /** Implemented as part of ControlValueAccessor. */
    writeValue(value) {
        this.value.next(value || defaultValue);
    }
    toggle() {
        this.isOpened = !this.isOpened;
        if (!this.isOpened) {
            this.value.next(defaultValue);
            if (this.isEmitValueByEnterEnabled) {
                this.emitValue(defaultValue, true);
            }
        }
        this.tooltip?.hide();
        this.isOpenedChange.emit(this.isOpened);
    }
    initDefaultParams() {
        this.configuration = KBQ_SEARCH_EXPANDABLE_DEFAULT_CONFIGURATION;
    }
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandable, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    /** @nocollapse */ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: KbqSearchExpandable, isStandalone: true, selector: "kbq-search-expandable", inputs: { isOpened: ["isOpened", "isOpened", booleanAttribute], isEmitValueByEnterEnabled: "isEmitValueByEnterEnabled", emitValueTimeout: ["emitValueTimeout", "emitValueTimeout", numberAttribute], placeholder: "placeholder" }, outputs: { isOpenedChange: "isOpenedChange" }, host: { properties: { "class.kbq-search-expandable_opened": "isOpened" }, classAttribute: "kbq-search-expandable" }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: KbqSearchExpandable,
                multi: true
            }
        ], viewQueries: [{ propertyName: "tooltip", first: true, predicate: KbqTooltipTrigger, descendants: true }, { propertyName: "input", predicate: KbqInput, descendants: true }, { propertyName: "button", predicate: KbqButton, descendants: true }], ngImport: i0, template: "@if (!isOpened) {\n    <button\n        type=\"button\"\n        kbq-button\n        class=\"kbq-search-expandable__button\"\n        [color]=\"'contrast'\"\n        [kbqStyle]=\"'transparent'\"\n        kbqTooltip=\"{{ localeData.tooltip }}\"\n        (click)=\"toggle()\"\n    >\n        <i kbq-icon=\"kbq-magnifying-glass_16\"></i>\n    </button>\n} @else {\n    <kbq-form-field class=\"kbq-search-expandable__search\">\n        <i kbqPrefix kbq-icon=\"kbq-magnifying-glass_16\"></i>\n\n        <input\n            kbqInput\n            name=\"value\"\n            type=\"text\"\n            autocomplete=\"off\"\n            [placeholder]=\"placeholder\"\n            [ngModel]=\"value | async\"\n            (ngModelChange)=\"value.next($event)\"\n            (blur)=\"onTouch()\"\n            (keyup.escape)=\"toggle()\"\n        />\n\n        <i kbqSuffix kbq-icon-button=\"kbq-xmark-circle_16\" (click)=\"toggle()\" (keyup.enter)=\"toggle()\"></i>\n    </kbq-form-field>\n}\n", styles: [".kbq-search-expandable{display:flex;flex-flow:row nowrap;align-items:center;justify-content:flex-start;min-width:0;min-height:0}.kbq-search-expandable__search .kbq-icon-button.kbq-suffix{display:flex;align-items:center;justify-content:center;border-radius:var(--kbq-size-xxs);height:var(--kbq-size-xxl)}\n"], dependencies: [{ kind: "ngmodule", type: KbqButtonModule }, { kind: "component", type: i1.KbqButton, selector: "[kbq-button]", inputs: ["kbqStyle", "disabled", "tabIndex"] }, { kind: "directive", type: i1.KbqButtonCssStyler, selector: "[kbq-button]" }, { kind: "ngmodule", type: KbqIconModule }, { kind: "component", type: i2.KbqIcon, selector: "[kbq-icon]", inputs: ["small", "autoColor", "kbq-icon"] }, { kind: "component", type: i2.KbqIconButton, selector: "[kbq-icon-button]", inputs: ["small", "kbq-icon-button", "tabindex", "disabled"] }, { kind: "ngmodule", type: KbqInputModule }, { kind: "directive", type: i3.KbqInput, selector: "input[kbqInput],input[kbqNumberInput]", inputs: ["errorStateMatcher", "placeholder", "disabled", "id", "required", "type", "value"], exportAs: ["kbqInput"] }, { kind: "component", type: i4.KbqFormField, selector: "kbq-form-field", inputs: ["noBorders"], exportAs: ["kbqFormField"] }, { kind: "directive", type: i4.KbqPrefix, selector: "[kbqPrefix]", exportAs: ["kbqPrefix"] }, { kind: "directive", type: i4.KbqSuffix, selector: "[kbqSuffix]" }, { kind: "directive", type: i4.KbqValidateDirective, selector: "        input[kbqInput],        input[kbqNumberInput],        input[kbqInputPassword],        input[kbqTimepicker],        input[kbqDatepicker],        textarea[kbqTextarea],        kbq-select,        kbq-tree-select,        kbq-tag-list    ", exportAs: ["KbqValidate"] }, { kind: "directive", type: i4.KbqTrim, selector: "[kbqInput], [kbqTextarea]", exportAs: ["KbqTrim"] }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i5.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i5.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i5.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "pipe", type: AsyncPipe, name: "async" }, { kind: "ngmodule", type: KbqToolTipModule }, { kind: "directive", type: i6.KbqTooltipTrigger, selector: "[kbqTooltip]", inputs: ["hideWithTimeout", "kbqVisible", "kbqPlacement", "kbqRelativeToPointer", "kbqPlacementPriority", "kbqTooltip", "kbqTooltipDisabled", "kbqEnterDelay", "kbqLeaveDelay", "kbqTrigger", "kbqTooltipClass", "kbqTooltipContext", "kbqTooltipColor", "kbqTooltipArrow", "kbqTooltipOffset"], outputs: ["kbqPlacementChange", "kbqVisibleChange"], exportAs: ["kbqTooltip"] }, { kind: "ngmodule", type: KbqFormFieldModule }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandable, decorators: [{
            type: Component,
            args: [{ standalone: true, selector: 'kbq-search-expandable', host: {
                        class: 'kbq-search-expandable',
                        '[class.kbq-search-expandable_opened]': 'isOpened'
                    }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [
                        KbqButtonModule,
                        KbqIconModule,
                        KbqInputModule,
                        FormsModule,
                        AsyncPipe,
                        KbqToolTipModule,
                        KbqFormFieldModule
                    ], providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: KbqSearchExpandable,
                            multi: true
                        }
                    ], template: "@if (!isOpened) {\n    <button\n        type=\"button\"\n        kbq-button\n        class=\"kbq-search-expandable__button\"\n        [color]=\"'contrast'\"\n        [kbqStyle]=\"'transparent'\"\n        kbqTooltip=\"{{ localeData.tooltip }}\"\n        (click)=\"toggle()\"\n    >\n        <i kbq-icon=\"kbq-magnifying-glass_16\"></i>\n    </button>\n} @else {\n    <kbq-form-field class=\"kbq-search-expandable__search\">\n        <i kbqPrefix kbq-icon=\"kbq-magnifying-glass_16\"></i>\n\n        <input\n            kbqInput\n            name=\"value\"\n            type=\"text\"\n            autocomplete=\"off\"\n            [placeholder]=\"placeholder\"\n            [ngModel]=\"value | async\"\n            (ngModelChange)=\"value.next($event)\"\n            (blur)=\"onTouch()\"\n            (keyup.escape)=\"toggle()\"\n        />\n\n        <i kbqSuffix kbq-icon-button=\"kbq-xmark-circle_16\" (click)=\"toggle()\" (keyup.enter)=\"toggle()\"></i>\n    </kbq-form-field>\n}\n", styles: [".kbq-search-expandable{display:flex;flex-flow:row nowrap;align-items:center;justify-content:flex-start;min-width:0;min-height:0}.kbq-search-expandable__search .kbq-icon-button.kbq-suffix{display:flex;align-items:center;justify-content:center;border-radius:var(--kbq-size-xxs);height:var(--kbq-size-xxl)}\n"] }]
        }], ctorParameters: () => [], propDecorators: { input: [{
                type: ViewChildren,
                args: [KbqInput]
            }], button: [{
                type: ViewChildren,
                args: [KbqButton]
            }], tooltip: [{
                type: ViewChild,
                args: [KbqTooltipTrigger]
            }], isOpened: [{
                type: Input,
                args: [{ transform: booleanAttribute }]
            }], isEmitValueByEnterEnabled: [{
                type: Input
            }], emitValueTimeout: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], placeholder: [{
                type: Input
            }], isOpenedChange: [{
                type: Output
            }] } });

class KbqSearchExpandableModule {
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandableModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    /** @nocollapse */ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandableModule, imports: [KbqSearchExpandable], exports: [KbqSearchExpandable] }); }
    /** @nocollapse */ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandableModule, imports: [KbqSearchExpandable] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqSearchExpandableModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        KbqSearchExpandable
                    ],
                    exports: [KbqSearchExpandable]
                }]
        }] });

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

export { KBQ_SEARCH_EXPANDABLE_CONFIGURATION, KBQ_SEARCH_EXPANDABLE_DEFAULT_CONFIGURATION, KbqSearchExpandable, KbqSearchExpandableModule, defaultEmitValueTimeout, defaultValue };
//# sourceMappingURL=koobiq-components-search-expandable.mjs.map
