import { buildInstantProducts } from "@coveo/headless/commerce";
import { LitElement, html, nothing, render } from "lit";
import { customElement, property, state as decorators_js_state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";
import { getPartialInstantItemElement, getPartialInstantItemShowAllElement, renderInstantItemShowAllButton } from "../../common/suggestions/instant-item.js";
import { dispatchSearchBoxSuggestionsEvent } from "../../common/suggestions/suggestions-events.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { encodeForDomAttribute } from "../../../utils/string-utils.js";
import { ProductTemplateProvider } from "../product-list/product-template-provider.js";
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 LitElement {
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    connectedCallback() {
        super.connectedCallback();
        try {
            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 = getPartialInstantItemElement(this.bindings.i18n, 'instant-products-suggestion-label', this.ariaLabelGenerator?.(this.bindings, product) || product.ec_name, product.permanentid);
            const key = `instant-product-${encodeForDomAttribute(product.permanentid)}`;
            const template = html`${keyed(key, 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');
            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 = getPartialInstantItemShowAllElement(this.bindings.i18n, 'show-all-products');
            elements.push({
                ...partialItem,
                content: 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 = 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 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 nothing;
    }
    constructor(...args){
        super(...args), this.products = [], this.display = 'list', this.templateHasError = false, this.density = 'normal', this.imageSize = 'icon';
    }
}
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceSearchBoxInstantProducts.prototype, "error", void 0);
_ts_decorate([
    decorators_js_state()
], AtomicCommerceSearchBoxInstantProducts.prototype, "templateHasError", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicCommerceSearchBoxInstantProducts.prototype, "density", void 0);
_ts_decorate([
    property({
        attribute: 'image-size',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicCommerceSearchBoxInstantProducts.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        attribute: 'aria-label-generator'
    }),
    _ts_metadata("design:type", "u" < typeof AriaLabelGenerator ? Object : AriaLabelGenerator)
], AtomicCommerceSearchBoxInstantProducts.prototype, "ariaLabelGenerator", void 0);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceSearchBoxInstantProducts.prototype, "render", null);
AtomicCommerceSearchBoxInstantProducts = _ts_decorate([
    customElement('atomic-commerce-search-box-instant-products'),
    withTailwindStyles
], AtomicCommerceSearchBoxInstantProducts);
export { AtomicCommerceSearchBoxInstantProducts };
