"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__, {
    AtomicSearchBoxInstantResults: ()=>AtomicSearchBoxInstantResults
});
const headless_namespaceObject = require("@coveo/headless");
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const keyed_js_namespaceObject = require("lit/directives/keyed.js");
const result_template_provider_cjs_namespaceObject = require("../../common/item-list/result-template-provider.cjs");
const instant_item_cjs_namespaceObject = require("../../common/suggestions/instant-item.cjs");
const suggestions_events_cjs_namespaceObject = require("../../common/suggestions/suggestions-events.cjs");
const error_guard_cjs_namespaceObject = require("../../../decorators/error-guard.cjs");
const string_utils_cjs_namespaceObject = require("../../../utils/string-utils.cjs");
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 AtomicSearchBoxInstantResults extends external_lit_namespaceObject.LitElement {
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    connectedCallback() {
        super.connectedCallback();
        try {
            (0, suggestions_events_cjs_namespaceObject.dispatchSearchBoxSuggestionsEvent)((bindings)=>{
                this.bindings = bindings;
                return this.initialize();
            }, this, [
                'atomic-search-box'
            ]);
        } catch (error) {
            this.error = error;
        }
    }
    getLink(el) {
        const atomicResult = 'ATOMIC-RESULT' === el.tagName ? el : el?.querySelector('atomic-result');
        return atomicResult?.shadowRoot?.querySelector('atomic-result-link a:not([slot])') || null;
    }
    handleLinkClick(el, hasModifier) {
        const setTarget = (value)=>el.setAttribute('target', value);
        const initialTarget = el.getAttribute('target');
        hasModifier && setTarget('_blank');
        el.click();
        hasModifier && setTarget(initialTarget || '');
    }
    renderItems() {
        if (!this.bindings.suggestedQuery() || this.bindings.store.isMobile()) return [];
        const results = this.instantResults.state.results.length ? this.instantResults.state.results : this.results;
        const elements = results.map((result)=>{
            const partialItem = (0, instant_item_cjs_namespaceObject.getPartialInstantItemElement)(this.bindings.i18n, 'instant-results-suggestion-label', this.ariaLabelGenerator?.(this.bindings, result) || result.title, result.uniqueId);
            const key = `instant-result-${(0, string_utils_cjs_namespaceObject.encodeForDomAttribute)(result.uniqueId)}`;
            const template = (0, external_lit_namespaceObject.html)`${(0, keyed_js_namespaceObject.keyed)(key, (0, external_lit_namespaceObject.html)`<atomic-result
            part="outline"
            .result=${result}
            .interactiveResult=${(0, headless_namespaceObject.buildInteractiveInstantResult)(this.bindings.engine, {
                options: {
                    result
                }
            })}
            .display=${this.display}
            .density=${this.density}
            .imageSize=${this.imageSize}
            .content=${this.itemTemplateProvider.getTemplateContent(result)}
            .renderingFunction=${this.itemRenderingFunction}
          ></atomic-result>`)}`;
            const container = document.createElement('div');
            (0, external_lit_namespaceObject.render)(template, container);
            const resultElement = container.firstElementChild;
            return {
                ...partialItem,
                content: resultElement,
                onSelect: (e)=>{
                    const link = this.getLink(e.target);
                    if (!link) return;
                    this.handleLinkClick(link, e.ctrlKey || e.metaKey);
                }
            };
        });
        if (elements.length) {
            const partialItem = (0, instant_item_cjs_namespaceObject.getPartialInstantItemShowAllElement)(this.bindings.i18n, 'show-all-results');
            elements.push({
                ...partialItem,
                content: (0, instant_item_cjs_namespaceObject.renderInstantItemShowAllButton)({
                    i18n: this.bindings.i18n,
                    i18nKey: 'show-all-results'
                }),
                onSelect: ()=>{
                    this.bindings.clearSuggestions();
                    this.bindings.searchBoxController.updateText(this.instantResults.state.q);
                    this.bindings.searchBoxController.submit();
                }
            });
        }
        return elements;
    }
    initialize() {
        this.instantResults = (0, headless_namespaceObject.buildInstantResults)(this.bindings.engine, {
            options: {
                maxResultsPerQuery: this.maxResultsPerQuery
            }
        });
        this.itemTemplateProvider = new result_template_provider_cjs_namespaceObject.ResultTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-result-template')),
            getResultTemplateRegistered: ()=>true,
            setResultTemplateRegistered: ()=>{},
            getTemplateHasError: ()=>this.templateHasError,
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            },
            bindings: this.bindings
        });
        return {
            position: Array.from(this.parentNode.children).indexOf(this),
            panel: 'right',
            onSuggestedQueryChange: (q)=>{
                this.instantResults.updateQuery(q);
                return this.onSuggestedQueryChange();
            },
            renderItems: ()=>this.renderItems()
        };
    }
    onSuggestedQueryChange() {
        if (!this.bindings.getSuggestionElements().length && !this.bindings.searchBoxController.state.value) console.warn("There doesn't seem to be any query suggestions configured. Make sure to include either an atomic-search-box-query-suggestions or atomic-search-box-recent-queries in your search box in order to see some instant results.");
        return new Promise((resolve)=>{
            const unsubscribe = this.instantResults.subscribe(()=>{
                const state = this.instantResults.state;
                if (!state.isLoading) {
                    if (state.results.length) this.results = state.results;
                    unsubscribe();
                    resolve();
                }
            });
        });
    }
    render() {
        return external_lit_namespaceObject.nothing;
    }
    constructor(...args){
        super(...args), this.results = [], this.display = 'list', this.templateHasError = false, this.maxResultsPerQuery = 4, this.density = 'normal', this.imageSize = 'icon';
    }
}
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSearchBoxInstantResults.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicSearchBoxInstantResults.prototype, "templateHasError", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        attribute: 'max-results-per-query',
        reflect: true,
        type: Number
    })
], AtomicSearchBoxInstantResults.prototype, "maxResultsPerQuery", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicSearchBoxInstantResults.prototype, "density", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        attribute: 'image-size',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicSearchBoxInstantResults.prototype, "imageSize", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        attribute: 'aria-label-generator'
    }),
    _ts_metadata("design:type", "u" < typeof AriaLabelGenerator ? Object : AriaLabelGenerator)
], AtomicSearchBoxInstantResults.prototype, "ariaLabelGenerator", void 0);
_ts_decorate([
    (0, error_guard_cjs_namespaceObject.errorGuard)(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSearchBoxInstantResults.prototype, "render", null);
AtomicSearchBoxInstantResults = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-search-box-instant-results')
], AtomicSearchBoxInstantResults);
exports.AtomicSearchBoxInstantResults = __webpack_exports__.AtomicSearchBoxInstantResults;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicSearchBoxInstantResults"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
