"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__, {
    AtomicCommerceSearchBoxInstantProducts: ()=>AtomicCommerceSearchBoxInstantProducts
});
const commerce_namespaceObject = require("@coveo/headless/commerce");
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const keyed_js_namespaceObject = require("lit/directives/keyed.js");
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 with_tailwind_styles_cjs_namespaceObject = require("../../../decorators/with-tailwind-styles.cjs");
const string_utils_cjs_namespaceObject = require("../../../utils/string-utils.cjs");
const product_template_provider_cjs_namespaceObject = require("../product-list/product-template-provider.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 AtomicCommerceSearchBoxInstantProducts 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-commerce-search-box'
            ]);
        } catch (error) {
            this.error = error;
        }
    }
    getLink(el) {
        const atomicProduct = 'ATOMIC-PRODUCT' === el.tagName ? el : el?.querySelector('atomic-product');
        return atomicProduct?.shadowRoot?.querySelector('atomic-product-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 products = this.instantProducts.state.products.length ? this.instantProducts.state.products : this.products;
        const elements = products.map((product)=>{
            const interactiveProduct = this.instantProducts.interactiveProduct({
                options: {
                    product
                }
            });
            const partialItem = (0, instant_item_cjs_namespaceObject.getPartialInstantItemElement)(this.bindings.i18n, 'instant-products-suggestion-label', this.ariaLabelGenerator?.(this.bindings, product) || product.ec_name, product.permanentid);
            const key = `instant-product-${(0, string_utils_cjs_namespaceObject.encodeForDomAttribute)(product.permanentid)}`;
            const template = (0, external_lit_namespaceObject.html)`${(0, keyed_js_namespaceObject.keyed)(key, (0, external_lit_namespaceObject.html)`<atomic-product
            part="outline"
            .product=${product}
            .interactiveProduct=${interactiveProduct}
            .display=${this.display}
            .density=${this.density}
            .imageSize=${this.imageSize}
            .content=${this.itemTemplateProvider.getTemplateContent(product)}
            .stopPropagation=${false}
            .renderingFunction=${this.itemRenderingFunction}
          ></atomic-product>`)}`;
            const container = document.createElement('div');
            (0, external_lit_namespaceObject.render)(template, container);
            const productElement = container.firstElementChild;
            return {
                ...partialItem,
                content: productElement,
                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-products');
            elements.push({
                ...partialItem,
                content: (0, instant_item_cjs_namespaceObject.renderInstantItemShowAllButton)({
                    i18n: this.bindings.i18n,
                    i18nKey: 'show-all-products'
                }),
                onSelect: ()=>{
                    this.bindings.clearSuggestions();
                    this.bindings.searchBoxController.updateText(this.instantProducts.state.query);
                    this.bindings.searchBoxController.submit();
                }
            });
        }
        return elements;
    }
    initialize() {
        this.instantProducts = (0, commerce_namespaceObject.buildInstantProducts)(this.bindings.engine, {
            options: {}
        });
        this.bindings.store.onChange('activeProductChild', ()=>{
            if (this.bindings.store.state.activeProductChild) this.instantProducts.promoteChildToParent(this.bindings.store.state.activeProductChild);
        });
        this.itemTemplateProvider = new product_template_provider_cjs_namespaceObject.ProductTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-product-template')),
            getResultTemplateRegistered: ()=>true,
            setResultTemplateRegistered: ()=>{},
            getTemplateHasError: ()=>this.templateHasError,
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            }
        });
        return {
            position: Array.from(this.parentNode.children).indexOf(this),
            panel: 'right',
            onSuggestedQueryChange: (q)=>{
                this.instantProducts.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-commerce-search-box-query-suggestions or atomic-commerce-search-box-recent-queries in your search box in order to see some instant products.");
        return new Promise((resolve)=>{
            const unsubscribe = this.instantProducts.subscribe(()=>{
                const state = this.instantProducts.state;
                if (!state.isLoading) {
                    if (state.products.length) this.products = state.products;
                    unsubscribe();
                    resolve();
                }
            });
        });
    }
    render() {
        return external_lit_namespaceObject.nothing;
    }
    constructor(...args){
        super(...args), this.products = [], this.display = 'list', this.templateHasError = false, this.density = 'normal', this.imageSize = 'icon';
    }
}
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceSearchBoxInstantProducts.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceSearchBoxInstantProducts.prototype, "templateHasError", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicCommerceSearchBoxInstantProducts.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)
], AtomicCommerceSearchBoxInstantProducts.prototype, "imageSize", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        attribute: 'aria-label-generator'
    }),
    _ts_metadata("design:type", "u" < typeof AriaLabelGenerator ? Object : AriaLabelGenerator)
], AtomicCommerceSearchBoxInstantProducts.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)
], AtomicCommerceSearchBoxInstantProducts.prototype, "render", null);
AtomicCommerceSearchBoxInstantProducts = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-commerce-search-box-instant-products'),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles
], AtomicCommerceSearchBoxInstantProducts);
exports.AtomicCommerceSearchBoxInstantProducts = __webpack_exports__.AtomicCommerceSearchBoxInstantProducts;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicCommerceSearchBoxInstantProducts"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
