// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Themeable } from '../../../../Controls/Behaviors/Themeable';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Emit } from '../../../../Events/Decorators/EmitDecorator';
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Busyable } from '../../../Behaviors/Busyable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Key } from '../../../Types/Key';
import { KeyName } from '../../../Types/Key';
import { SearchTriggerMode } from '../../../Types/SearchTriggerMode';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { searchBoxElementTemplate } from './SearchBoxElementTemplate';
import { searchBoxElementJoyStyle } from './Themes/SearchBoxElement.Joy';
import { searchBoxElementMemphisStyle } from './Themes/SearchBoxElement.Memphis';
import { searchBoxElementCosmopolitanStyle } from './Themes/SearchBoxElement.Cosmopolitan';
import { TextAlignment } from '../../../Types/TextAlignment';
// #endregion
/**
 * Search Box - A specialized input control for search queries with integrated search functionality.
 *
 * @description
 * The Search Box component provides a dedicated interface for entering and executing search queries with
 * built-in search functionality and visual indicators. It features a search icon, clear functionality,
 * configurable search trigger modes (on enter, on input, manual), debounced search execution to prevent
 * excessive queries, progress indication for ongoing searches, and comprehensive keyboard support.
 * The component handles search execution timing, provides search and clear events, supports both
 * immediate and delayed search triggers, and integrates with loading states and validation systems.
 * Perfect for search forms, filter interfaces, content discovery, and any application requiring
 * search input with optimized query handling.
 *
 * @name Search Box
 * @element mosaik-searchbox
 * @category Inputs
 *
 * @slot prefix - Content placed before the search input.
 * @slot suffix - Content placed after the search input.
 *
 * @csspart prefix - The prefix content container.
 * @csspart search - The search icon element.
 * @csspart inner - The inner container wrapper.
 * @csspart input - The search input field.
 * @csspart suffix - The suffix content container.
 * @csspart clear - The clear button element.
 * @csspart focusRing - The focus ring indicator.
 * @csspart progressRing - The progress ring for loading state.
 *
 * @cssprop {String} --search-box-background-color - The background color.
 * @cssprop {String} --search-box-border-color - The border color.
 * @cssprop {String} --search-box-border-radius - The border radius.
 * @cssprop {String} --search-box-border-style - The border style.
 * @cssprop {String} --search-box-border-width - The border width.
 * @cssprop {String} --search-box-font-family - The font family.
 * @cssprop {String} --search-box-font-size - The font size.
 * @cssprop {String} --search-box-font-weight - The font weight.
 * @cssprop {String} --search-box-foreground-color - The foreground color.
 * @cssprop {String} --search-box-gap - The gap between elements.
 * @cssprop {String} --search-box-height - The height.
 * @cssprop {String} --search-box-padding-bottom - The padding bottom.
 * @cssprop {String} --search-box-padding-left - The padding left.
 * @cssprop {String} --search-box-padding-right - The padding right.
 * @cssprop {String} --search-box-padding-top - The padding top.
 * @cssprop {String} --search-box-shadow - The shadow.
 * @cssprop {String} --search-box-transition-duration - The transition duration.
 *
 * @dependency mosaik-focus-ring - Used for focus indication.
 * @dependency mosaik-icon - Used for search and clear icons.
 * @dependency mosaik-button - Used for action buttons.
 * @dependency mosaik-progress-ring - Used for loading indication.
 *
 * @fires cleared - Fired when the value is cleared.
 * @fires searched - Fired when the element is searched.
 *
 * @keyhandle Backspace - Clears the value.
 * @keyhandle Escape - Clears the value.
 * @keyhandle Enter - Searches the value.
 *
 * @example
 * ```html
 * <mosaik-searchbox
 *   placeholder="Search products..."
 *   trigger-mode="debounced"
 *   debounce-delay="300">
 * </mosaik-searchbox>
 * ```
 *
 * @example
 * ```html
 * <mosaik-searchbox
 *   placeholder="Search..."
 *   trigger-mode="enter"
 *   clearable>
 * </mosaik-searchbox>
 * ```
 *
 * @public
 */
let SearchBoxElement = class SearchBoxElement extends Themeable(Slottable(Clearable(Disableable(Invalidable(Valueable(Variantable(Busyable(Appearanceable(InputBaseElement))))))))) {
    // #region Fields
    _keyboardController;
    _searched;
    _inputElement;
    _value;
    _readonly;
    _required;
    _autofocus;
    _name;
    _pattern;
    _placeholder;
    _autocomplete;
    _mode;
    _delay;
    _delayTimeoutId;
    _textAlign;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._value = '';
        this._readonly = false;
        this._required = false;
        this._autofocus = false;
        this._name = '';
        this._pattern = '';
        this._placeholder = '';
        this._autocomplete = false;
        this._mode = SearchTriggerMode.Input;
        this._delay = 0;
        this._delayTimeoutId = null;
        this._textAlign = TextAlignment.Left;
        this._searched = new HTMLElementEventEmitter(this, 'searched');
        this._keyboardController = new KeyboardController(this);
    }
    // #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-searchbox';
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `readonly` property.
     *
     * @public
     * @attr
     */
    get readonly() {
        return this._readonly;
    }
    set readonly(value) {
        if (this._readonly !== value) {
            this._readonly = value;
            this.requestUpdate('readonly');
        }
    }
    /**
     * Gets or sets the `required` property.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Gets or sets the `autofocus` property.
     *
     * @public
     * @override
     */
    get autofocus() {
        return this._autofocus;
    }
    set autofocus(value) {
        if (this._autofocus !== value) {
            this._autofocus = value;
            this.requestUpdate('autofocus');
        }
    }
    /**
     * Gets or sets the `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Gets or sets the `pattern` property.
     *
     * @public
     * @attr
     */
    get pattern() {
        return this._pattern;
    }
    set pattern(value) {
        if (this._pattern !== value) {
            this._pattern = value;
            this.requestUpdate('pattern');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     * @attr
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `autocomplete` property.
     *
     * @public
     * @attr
     */
    get autocomplete() {
        return this._autocomplete;
    }
    set autocomplete(value) {
        if (this._autocomplete !== value) {
            this._autocomplete = value;
            this.requestUpdate('autocomplete');
        }
    }
    /**
     * Gets or sets the `mode` property.
     *
     * @public
     * @attr
     */
    get mode() {
        return this._mode;
    }
    set mode(value) {
        if (this._mode !== value) {
            this._mode = value;
            this.requestUpdate('mode');
        }
    }
    /**
     * Gets or sets the `delay` property.
     *
     * @public
     * @attr
     */
    get delay() {
        return this._delay;
    }
    set delay(value) {
        if (this._delay !== value) {
            this._delay = value;
            this.requestUpdate('delay');
        }
    }
    /**
     * 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');
        }
    }
    /**
     * Determines whether the element has a prefix or not.
     * The Prefix is a slot that is displayed before the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasPrefix() {
        return this.hasSlotContent('prefix');
    }
    /**
     * Determines whether the element has a suffix or not.
     * The Suffix is a slot that is displayed after the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasSuffix() {
        return this.hasSlotContent('suffix');
    }
    /**
     * Called when the search is triggered.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get searched() {
        return this._searched;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        // Prevent duplicate paste (browser default + manual assignment previously caused double text).
        // We now intercept paste, insert plain text ourselves (no formatting) and let the resulting
        // native input event drive value + search trigger logic (handled in onInput/onChange).
        this.on('paste', (e) => {
            const target = e.target;
            if (!target || target.tagName !== 'INPUT') {
                return;
            }
            if (this.disabled || this.readonly) {
                return;
            }
            e.preventDefault();
            const data = e.clipboardData?.getData('text/plain') ?? '';
            const start = target.selectionStart ?? target.value.length;
            const end = target.selectionEnd ?? start;
            // setRangeText will dispatch a single 'input' event (selectionMode != 'preserve').
            target.setRangeText(data, start, end, 'end');
        });
        this._keyboardController
            .add([Key.Backspace], () => {
            // if (this._mode === 'instant') {
            //     this.value = '';
            // } else {
            //     this.value = this.value.slice(0, -1);
            // }
        })
            .add([Key.Escape], () => {
            this.clear();
        });
    }
    /**
    * @public
    * @override
    */
    focus() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.focus();
        }
    }
    /**
     * @public
     * @override
     */
    blur() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.blur();
        }
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     * @override
     */
    reset() {
        super.reset();
        this.clear();
        this.invalid = false;
    }
    /**
     * @public
     */
    search() {
        if (this._mode === SearchTriggerMode.Input) {
            this.onSearched(this.value);
        }
        else {
            if (this._delayTimeoutId !== null) {
                clearTimeout(this._delayTimeoutId);
            }
            this._delayTimeoutId = window.setTimeout(() => {
                this._delayTimeoutId = null;
                this.onSearched(this.value);
            }, this._delay);
        }
    }
    /**
     * 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;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : false;
    }
    /**
     * @template
     * @protected
     */
    onChange(event) {
        this.value = event.target.value;
        this.emit('change', { detail: this.value });
        if (this._mode === SearchTriggerMode.Input) {
            this.onSearched(this.value);
        }
        else if (this._mode === SearchTriggerMode.Delay) {
            if (this._delayTimeoutId !== null) {
                clearTimeout(this._delayTimeoutId);
            }
            this._delayTimeoutId = window.setTimeout(() => {
                this._delayTimeoutId = null;
                this.onSearched(this.value);
            }, this._delay);
        }
    }
    /**
     * @template
     * @protected
     * @override
     */
    onInput(event) {
        super.onInput(event);
        this.value = event.target.value;
        this.emit('input', { detail: this.value });
        if (this._mode === SearchTriggerMode.Input) {
            this.onSearched(this.value);
        }
        else if (this._mode === SearchTriggerMode.Delay) {
            if (this._delayTimeoutId !== null) {
                clearTimeout(this._delayTimeoutId);
            }
            this._delayTimeoutId = window.setTimeout(() => {
                this._delayTimeoutId = null;
                this.onSearched(this.value);
            }, this._delay);
        }
    }
    /**
     * @template
     * @protected
     * @override
     */
    onFocus(event) {
        super.onFocus(event);
        this.emit('focus', { detail: event });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        this.emit('blur', { detail: event });
    }
    /**
     * @template
     * @protected
     */
    onKeyUp(event) {
        if (this._mode === SearchTriggerMode.Enter && event.key === KeyName.Enter) {
            this.onSearched(this.value);
        }
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
    }
    /**
     * Emits the {@link searched} event.
     *
     * @protected
     */
    onSearched(args) {
        this._searched.emit(args);
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SearchBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SearchBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SearchBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "pattern", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SearchBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({ type: SearchTriggerMode }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "mode", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], SearchBoxElement.prototype, "delay", null);
__decorate([
    Attribute({ type: TextAlignment }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SearchBoxElement.prototype, "textAlign", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], SearchBoxElement.prototype, "hasPrefix", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], SearchBoxElement.prototype, "hasSuffix", null);
__decorate([
    Emit({ eventName: 'searched' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], SearchBoxElement.prototype, "searched", null);
SearchBoxElement = __decorate([
    Component({
        selector: 'mosaik-searchbox',
        template: searchBoxElementTemplate,
        themes: {
            joy: searchBoxElementJoyStyle,
            memphis: searchBoxElementMemphisStyle,
            cosmopolitan: searchBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            FocusRingElement,
            ButtonElement
        ]
    }),
    __metadata("design:paramtypes", [])
], SearchBoxElement);
export { SearchBoxElement };
//# sourceMappingURL=SearchBoxElement.js.map