"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    AtomicCommerceSearchBox: ()=>AtomicCommerceSearchBox
});
const commerce_namespaceObject = require("@coveo/headless/commerce");
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const class_map_js_namespaceObject = require("lit/directives/class-map.js");
const ref_js_namespaceObject = require("lit/directives/ref.js");
const boolean_converter_cjs_namespaceObject = require("../../../converters/boolean-converter.cjs");
const bind_state_cjs_namespaceObject = require("../../../decorators/bind-state.cjs");
const binding_guard_cjs_namespaceObject = require("../../../decorators/binding-guard.cjs");
const bindings_cjs_namespaceObject = require("../../../decorators/bindings.cjs");
const error_guard_cjs_namespaceObject = require("../../../decorators/error-guard.cjs");
const watch_cjs_namespaceObject = require("../../../decorators/watch.cjs");
const with_tailwind_styles_cjs_namespaceObject = require("../../../decorators/with-tailwind-styles.cjs");
const accessibility_utils_cjs_namespaceObject = require("../../../utils/accessibility-utils.cjs");
const device_utils_cjs_namespaceObject = require("../../../utils/device-utils.cjs");
const event_utils_cjs_namespaceObject = require("../../../utils/event-utils.cjs");
const local_storage_utils_cjs_namespaceObject = require("../../../utils/local-storage-utils.cjs");
const replace_breakpoint_utils_cjs_namespaceObject = require("../../../utils/replace-breakpoint-utils.cjs");
const slot_utils_cjs_namespaceObject = require("../../../utils/slot-utils.cjs");
const utils_cjs_namespaceObject = require("../../../utils/utils.cjs");
const search_box_wrapper_cjs_namespaceObject = require("../../common/search-box/search-box-wrapper.cjs");
const search_text_area_cjs_namespaceObject = require("../../common/search-box/search-text-area.cjs");
const submit_button_cjs_namespaceObject = require("../../common/search-box/submit-button.cjs");
const suggestion_manager_cjs_namespaceObject = require("../../common/suggestions/suggestion-manager.cjs");
const suggestions_utils_cjs_namespaceObject = require("../../common/suggestions/suggestions-utils.cjs");
require("../atomic-commerce-search-box-instant-products/atomic-commerce-search-box-instant-products.cjs");
require("../atomic-commerce-search-box-query-suggestions/atomic-commerce-search-box-query-suggestions.cjs");
require("../atomic-commerce-search-box-recent-queries/atomic-commerce-search-box-recent-queries.cjs");
require("@coveo/atomic-legacy/atomic-suggestion-renderer");
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) 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;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicCommerceSearchBox extends external_lit_namespaceObject.LitElement {
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('atomic/searchBoxSuggestion/register', (event)=>{
            const customEvent = event;
            this.searchBoxSuggestionEventsQueue.push(customEvent);
        });
        this.addEventListener('atomic/selectChildProduct', (event)=>{
            const customEvent = event;
            customEvent.stopPropagation();
            this.bindings.store.state.activeProductChild = customEvent.detail.child;
            this.suggestionManager.forceUpdate();
        });
    }
    willUpdate() {
        if (!this.searchBoxState || !this.searchBox) return;
        if (!('redirectTo' in this.searchBoxState) || !('afterRedirection' in this.searchBox)) return;
        const { redirectTo, value } = this.searchBoxState;
        if ('' === redirectTo) return;
        const data = {
            value,
            enableQuerySyntax: false
        };
        const storage = new local_storage_utils_cjs_namespaceObject.SafeStorage();
        storage.setJSON(local_storage_utils_cjs_namespaceObject.StorageItems.STANDALONE_SEARCH_BOX_DATA, data);
        this.searchBox.afterRedirection();
        const event = (0, event_utils_cjs_namespaceObject.buildCustomEvent)('redirect', {
            redirectTo,
            value
        });
        this.dispatchEvent(event);
        if (!event.defaultPrevented) window.location.href = redirectTo;
    }
    initialize() {
        this.id = (0, utils_cjs_namespaceObject.randomID)('atomic-commerce-search-box-');
        this.initializeSearchboxController();
        this.initializeSuggestionManager();
    }
    initializeSearchboxController() {
        this.searchBox = this.redirectionUrl ? (0, commerce_namespaceObject.buildStandaloneSearchBox)(this.bindings.engine, {
            options: {
                ...this.searchBoxOptions,
                redirectionUrl: this.redirectionUrl,
                overwrite: true
            }
        }) : (0, commerce_namespaceObject.buildSearchBox)(this.bindings.engine, {
            options: this.searchBoxOptions
        });
    }
    initializeSuggestionManager() {
        if (this.suggestionManager) return;
        this.suggestionManager = new suggestion_manager_cjs_namespaceObject.SuggestionManager({
            getNumberOfSuggestionsToDisplay: ()=>this.numberOfQueries,
            updateQuery: (query)=>this.searchBox.updateText(query),
            getSearchBoxValue: ()=>this.searchBoxState.value,
            getSuggestionTimeout: ()=>this.suggestionTimeout,
            getSuggestionDelay: ()=>this.suggestionDelay,
            getHost: ()=>this,
            getLogger: ()=>this.bindings.engine.logger
        });
        this.suggestionManager.initializeSuggestions(this.suggestionBindings);
    }
    watchRedirectionUrl() {
        if (!this.searchBox) return;
        if (this.isStandaloneSearchBox(this.searchBox) && this.redirectionUrl) this.searchBox.updateRedirectUrl(this.redirectionUrl);
        else this.registerNewSearchBoxController();
    }
    isStandaloneSearchBox(searchBox) {
        return 'updateRedirectUrl' in searchBox;
    }
    get isSearchDisabledForEndUser() {
        if (this.searchBoxState.value.trim().length < this.minimumQueryLength) return true;
        return this.disableSearch;
    }
    get textAreaLabel() {
        if (this.isSearchDisabledForEndUser) return this.bindings.i18n.t('search-disabled', {
            length: this.minimumQueryLength
        });
        if ((0, device_utils_cjs_namespaceObject.isMacOS)()) return this.bindings.i18n.t('search-box-with-suggestions-macos');
        if (!(0, device_utils_cjs_namespaceObject.hasKeyboard)()) return this.bindings.i18n.t('search-box-with-suggestions-keyboardless');
        return this.bindings.i18n.t('search-box-with-suggestions');
    }
    get suggestionBindings() {
        return (0, utils_cjs_namespaceObject.spreadProperties)(this.bindings, this.suggestionManager.partialSuggestionBindings, this.partialSuggestionBindings);
    }
    get partialSuggestionBindings() {
        return Object.defineProperties({
            ...this.bindings
        }, {
            id: {
                get: ()=>this.id,
                enumerable: true
            },
            searchBoxController: {
                get: ()=>this.searchBox,
                enumerable: true
            },
            isStandalone: {
                get: ()=>!!this.redirectionUrl,
                enumerable: true
            },
            numberOfQueries: {
                get: ()=>this.numberOfQueries,
                enumerable: true
            },
            clearFilters: {
                get: ()=>this.clearFilters,
                enumerable: true
            }
        });
    }
    get searchBoxOptions() {
        return {
            id: this.id,
            highlightOptions: {
                notMatchDelimiters: {
                    open: '<span class="font-bold">',
                    close: '</span>'
                },
                correctionDelimiters: {
                    open: '<span class="font-normal">',
                    close: '</span>'
                }
            },
            clearFilters: this.clearFilters
        };
    }
    registerNewSearchBoxController() {
        this.disconnectedCallback();
        this.initialize();
    }
    registerSearchboxSuggestionEvents() {
        this.searchBoxSuggestionEventsQueue.forEach((evt)=>{
            this.suggestionManager.registerSuggestionsFromEvent(evt, this.suggestionBindings);
        });
        this.searchBoxSuggestionEventsQueue = [];
    }
    async onInput(value) {
        this.updateQueryWithoutQuerySuggestionTrigger(value);
        if (this.isSearchDisabledForEndUser) return void this.suggestionManager.clearSuggestions();
        this.isExpanded = true;
        await this.suggestionManager.triggerSuggestions();
        this.announceNewSuggestionsToScreenReader();
    }
    async onFocus() {
        if (this.isExpanded) return;
        if (this.isSearchDisabledForEndUser) return;
        this.isExpanded = true;
        await this.suggestionManager.triggerSuggestions();
        this.announceNewSuggestionsToScreenReader();
    }
    onSubmit() {
        this.isExpanded = false;
        if (this.suggestionManager.keyboardActiveDescendant) return void this.suggestionManager.onSubmit();
        this.searchBox.submit();
    }
    async onKeyDown(e) {
        if (this.isSearchDisabledForEndUser) return;
        switch(e.key){
            case 'Enter':
                if (!e.shiftKey) this.onSubmit();
                break;
            case 'Escape':
                this.suggestionManager.clearSuggestions();
                break;
            case 'ArrowDown':
                e.preventDefault();
                await this.suggestionManager.focusNextValue();
                this.announceNewActiveSuggestionToScreenReader();
                break;
            case 'ArrowUp':
                e.preventDefault();
                await this.suggestionManager.focusPreviousValue();
                this.announceNewActiveSuggestionToScreenReader();
                break;
            case 'ArrowRight':
                if (this.suggestionManager.hasActiveDescendant || !this.searchBoxState.value) {
                    e.preventDefault();
                    this.suggestionManager.focusPanel('right');
                    this.announceNewActiveSuggestionToScreenReader();
                }
                break;
            case 'ArrowLeft':
                if (this.suggestionManager.hasActiveDescendant || !this.searchBoxState.value) {
                    e.preventDefault();
                    this.suggestionManager.focusPanel('left');
                    this.announceNewActiveSuggestionToScreenReader();
                }
                break;
            case 'Tab':
                this.suggestionManager.clearSuggestions();
                break;
            default:
                if (this.suggestionManager.keyboardActiveDescendant) this.suggestionManager.updateKeyboardActiveDescendant();
                break;
        }
    }
    triggerTextAreaChange(value) {
        this.textAreaRef.value.value = value;
        this.textAreaRef.value.dispatchEvent(new window.Event('change'));
    }
    announceNewActiveSuggestionToScreenReader() {
        const ariaLabel = this.suggestionManager.activeDescendantElement?.ariaLabel;
        if ((0, device_utils_cjs_namespaceObject.isMacOS)() && ariaLabel) this.suggestionsAriaMessage.message = ariaLabel;
    }
    announceNewSuggestionsToScreenReader() {
        const elsLength = this.suggestionManager.allSuggestionElements.filter(suggestions_utils_cjs_namespaceObject.elementHasQuery).length;
        this.searchBoxAriaMessage.message = elsLength ? this.bindings.i18n.t(this.searchBoxState.value ? 'query-suggestions-available' : 'query-suggestions-available-no-query', {
            count: elsLength,
            query: this.searchBoxState.value
        }) : this.bindings.i18n.t('query-suggestions-unavailable');
    }
    updateQueryWithoutQuerySuggestionTrigger(query) {
        const { engine } = this.bindings;
        engine.dispatch((0, commerce_namespaceObject.loadQuerySetActions)(engine).updateQuerySetQuery({
            id: this.id,
            query
        }));
    }
    renderAbsolutePositionSpacer() {
        return (0, external_lit_namespaceObject.html)`<textarea
      disabled
      aria-hidden="true"
      part="textarea-spacer"
      class="invisible w-full p-3.5 px-4 text-lg"
      rows="1"
    ></textarea>`;
    }
    renderTextBox() {
        return (0, external_lit_namespaceObject.html)`${(0, search_text_area_cjs_namespaceObject.renderSearchBoxTextArea)({
            props: {
                textAreaRef: this.textAreaRef,
                loading: this.searchBoxState.isLoading,
                i18n: this.bindings.i18n,
                value: this.searchBoxState.value,
                title: this.textAreaLabel,
                ariaLabel: this.textAreaLabel,
                onFocus: ()=>this.onFocus(),
                onInput: (e)=>this.onInput(e.target.value),
                onKeyDown: (e)=>this.onKeyDown(e),
                onClear: ()=>{
                    this.searchBox.clear();
                    this.suggestionManager.clearSuggestions();
                    this.triggerTextAreaChange('');
                    this.announceClearSearchBoxToScreenReader();
                },
                popup: {
                    id: `${this.id}-popup`,
                    activeDescendant: this.suggestionManager.activeDescendant,
                    expanded: this.isExpanded,
                    hasSuggestions: this.suggestionManager.hasSuggestions
                }
            }
        })}`;
    }
    renderSuggestions() {
        const part = `suggestions-wrapper ${this.suggestionManager.isDoubleList ? 'suggestions-double-list' : 'suggestions-single-list'}`;
        const isVisible = this.suggestionManager.hasSuggestions && this.isExpanded && !this.isSearchDisabledForEndUser;
        const classes = {
            'bg-background border-neutral absolute top-full left-0 z-10 flex w-full rounded-md border': true,
            hidden: !isVisible
        };
        return (0, external_lit_namespaceObject.html)`<div
      id="${this.id}-popup"
      part=${part}
      class=${(0, class_map_js_namespaceObject.classMap)(classes)}
      role="application"
      aria-label=${this.bindings.i18n.t(this.suggestionManager.isDoubleList ? 'search-suggestions-double-list' : 'search-suggestions-single-list')}
      aria-activedescendant=${this.suggestionManager.activeDescendant}
    >
      ${this.renderPanel('left', this.suggestionManager.leftSuggestionElements, (el)=>{
            this.suggestionManager.leftPanel = el;
        }, ()=>this.suggestionManager.leftPanel)}
      ${this.renderPanel('right', this.suggestionManager.rightSuggestionElements, (el)=>{
            this.suggestionManager.rightPanel = el;
        }, ()=>this.suggestionManager.rightPanel)}
    </div>`;
    }
    renderPanel(side, elements, setRef, getRef) {
        if (!elements.length) return null;
        return (0, external_lit_namespaceObject.html)`<div
      part="suggestions suggestions-${side}"
      ${(0, ref_js_namespaceObject.ref)(setRef)}
      class="flex grow basis-1/2 flex-col"
      @mousedown=${(e)=>{
            if (e.target === getRef()) e.preventDefault();
        }}
    >
      ${elements.map((suggestion, index)=>this.renderSuggestion(suggestion, index, elements.length - 1, side))}
    </div>`;
    }
    renderSuggestion(item, index, lastIndex, side) {
        const id = `${this.id}-${side}-suggestion-${item.key}`;
        const isSelected = id === this.suggestionManager.activeDescendant;
        if (index === lastIndex && item.hideIfLast) return null;
        return (0, external_lit_namespaceObject.html)`
      <atomic-suggestion-renderer
        .i18n=${this.bindings.i18n}
        .id=${id}
        .suggestion=${item}
        .isSelected=${isSelected}
        .side=${side}
        .index=${index}
        .lastIndex=${lastIndex}
        .isDoubleList=${this.suggestionManager.isDoubleList}
        .onClick=${async (e)=>{
            await this.suggestionManager.onSuggestionClick(item, e);
            if ('recent-query-clear' === item.key) return;
            this.isExpanded = false;
        }}
        .onMouseEnter=${async ()=>{
            await this.suggestionManager.onSuggestionMouseOver(item, side, id);
        }}
      ></atomic-suggestion-renderer>
    `;
    }
    renderSlotContent() {
        const hasDefaultSlot = (0, slot_utils_cjs_namespaceObject.getDefaultSlotContent)(this).length > 0;
        if (hasDefaultSlot) return (0, external_lit_namespaceObject.html)`<slot></slot>`;
        return (0, external_lit_namespaceObject.html)`<atomic-commerce-search-box-recent-queries></atomic-commerce-search-box-recent-queries>
      <atomic-commerce-search-box-query-suggestions></atomic-commerce-search-box-query-suggestions>`;
    }
    render() {
        this.updateBreakpoints();
        if (!this.suggestionManager.suggestions.length) this.registerSearchboxSuggestionEvents();
        return (0, external_lit_namespaceObject.html)`
      ${this.renderAbsolutePositionSpacer()}
      ${(0, search_box_wrapper_cjs_namespaceObject.renderSearchBoxWrapper)({
            props: {
                disabled: this.isSearchDisabledForEndUser,
                onFocusout: (event)=>{
                    if (!(0, utils_cjs_namespaceObject.isFocusingOut)(event)) return;
                    this.suggestionManager.clearSuggestions();
                    this.isExpanded = false;
                }
            }
        })((0, external_lit_namespaceObject.html)`${this.renderTextBox()}
        ${(0, submit_button_cjs_namespaceObject.renderSubmitButton)({
            props: {
                i18n: this.bindings.i18n,
                disabled: this.isSearchDisabledForEndUser,
                onClick: ()=>{
                    this.searchBox.submit();
                    this.suggestionManager.clearSuggestions();
                }
            }
        })}
        ${this.renderSuggestions()}`)}
      ${this.renderSlotContent()}
    `;
    }
    announceClearSearchBoxToScreenReader() {
        this.searchBoxAriaMessage.message = this.bindings.i18n.t('search-box-cleared');
    }
    constructor(...args){
        super(...args), this.isExpanded = false, this.textAreaRef = (0, ref_js_namespaceObject.createRef)(), this.searchBoxSuggestionEventsQueue = [], this.searchBoxAriaMessage = new accessibility_utils_cjs_namespaceObject.AriaLiveRegionController(this, 'search-box'), this.suggestionsAriaMessage = new accessibility_utils_cjs_namespaceObject.AriaLiveRegionController(this, 'search-suggestions', true), this.numberOfQueries = 8, this.suggestionTimeout = 400, this.suggestionDelay = 0, this.disableSearch = false, this.minimumQueryLength = 0, this.clearFilters = true, this.updateBreakpoints = (0, utils_cjs_namespaceObject.once)(()=>(0, replace_breakpoint_utils_cjs_namespaceObject.updateBreakpoints)(this));
    }
}
AtomicCommerceSearchBox.shadowRootOptions = {
    ...external_lit_namespaceObject.LitElement.shadowRootOptions,
    delegatesFocus: true
};
AtomicCommerceSearchBox.styles = (0, external_lit_namespaceObject.css)`
    @import '../../search/atomic-search-box/atomic-search-box.css';
  `;
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceSearchBox.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceSearchBox.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceSearchBox.prototype, "isExpanded", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('searchBox'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", Object)
], AtomicCommerceSearchBox.prototype, "searchBoxState", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        attribute: 'number-of-queries',
        reflect: true
    })
], AtomicCommerceSearchBox.prototype, "numberOfQueries", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: String,
        attribute: 'redirection-url',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceSearchBox.prototype, "redirectionUrl", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        attribute: 'suggestion-timeout'
    })
], AtomicCommerceSearchBox.prototype, "suggestionTimeout", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        attribute: 'suggestion-delay'
    })
], AtomicCommerceSearchBox.prototype, "suggestionDelay", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'disable-search',
        reflect: true,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicCommerceSearchBox.prototype, "disableSearch", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        attribute: 'minimum-query-length',
        reflect: true
    })
], AtomicCommerceSearchBox.prototype, "minimumQueryLength", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        attribute: 'clear-filters',
        reflect: true,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter
    })
], AtomicCommerceSearchBox.prototype, "clearFilters", void 0);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('redirectionUrl'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceSearchBox.prototype, "watchRedirectionUrl", null);
_ts_decorate([
    (0, binding_guard_cjs_namespaceObject.bindingGuard)(),
    (0, error_guard_cjs_namespaceObject.errorGuard)(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceSearchBox.prototype, "render", null);
AtomicCommerceSearchBox = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-commerce-search-box'),
    (0, bindings_cjs_namespaceObject.bindings)(),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles
], AtomicCommerceSearchBox);
exports.AtomicCommerceSearchBox = __webpack_exports__.AtomicCommerceSearchBox;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicCommerceSearchBox"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
