"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __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__, {
    AtomicCommerceRecommendationList: ()=>AtomicCommerceRecommendationList
});
const bueno_namespaceObject = require("@coveo/bueno");
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 map_js_namespaceObject = require("lit/directives/map.js");
const when_js_namespaceObject = require("lit/directives/when.js");
const product_template_provider_cjs_namespaceObject = require("../product-list/product-template-provider.cjs");
const item_placeholders_cjs_namespaceObject = require("../../common/atomic-result-placeholder/item-placeholders.cjs");
const carousel_cjs_namespaceObject = require("../../common/carousel.cjs");
const heading_cjs_namespaceObject = require("../../common/heading.cjs");
const store_cjs_namespaceObject = require("../../common/interface/store.cjs");
const display_wrapper_cjs_namespaceObject = require("../../common/item-list/display-wrapper.cjs");
const grid_layout_cjs_namespaceObject = require("../../common/item-list/grid-layout.cjs");
const item_list_common_cjs_namespaceObject = require("../../common/item-list/item-list-common.cjs");
const item_layout_utils_cjs_namespaceObject = require("../../common/layout/item-layout-utils.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 children_update_complete_mixin_cjs_namespaceObject = require("../../../mixins/children-update-complete-mixin.cjs");
const accessibility_utils_cjs_namespaceObject = require("../../../utils/accessibility-utils.cjs");
const utils_cjs_namespaceObject = require("../../../utils/utils.cjs");
const placeholders_tw_css_cjs_namespaceObject = require("../../common/item-list/styles/placeholders.tw.css.cjs");
var placeholders_tw_css_cjs_default = /*#__PURE__*/ __webpack_require__.n(placeholders_tw_css_cjs_namespaceObject);
require("../atomic-product/atomic-product.cjs");
require("../atomic-product-template/atomic-product-template.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 AtomicCommerceRecommendationList extends (0, children_update_complete_mixin_cjs_namespaceObject.ChildrenUpdateCompleteMixin)(external_lit_namespaceObject.LitElement) {
    async watchNumberOfRecommendationsPerPage() {
        this.currentPage = 0;
    }
    async setRenderFunction(productRenderingFunction) {
        this.itemRenderingFunction = productRenderingFunction;
    }
    async previousPage() {
        this.currentPage = this.currentPage - 1 < 0 ? this.numberOfPages - 1 : this.currentPage - 1;
    }
    async nextPage() {
        this.currentPage = (this.currentPage + 1) % this.numberOfPages;
    }
    initialize() {
        this.validateProps();
        this.validateSlotID();
        this.initRecommendations();
        this.initSummary();
        this.initProductTemplateProvider();
        this.initProductListCommon();
        this.createSelectChildProductListener();
        (0, store_cjs_namespaceObject.createAppLoadedListener)(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.unsubscribeSummary?.();
        this.removeEventListener('atomic/selectChildProduct', this.selectChildProductCallback);
    }
    async updated(changedProperties) {
        super.updated(changedProperties);
        if (changedProperties.has('recommendationsState') && this.isEveryProductReady) this.isEveryProductReady = false;
        await this.updateProductsReadyState();
    }
    async updateProductsReadyState() {
        if (this.isAppLoaded && !this.isEveryProductReady && this.summaryState?.firstRequestExecuted && this.recommendationsState?.products?.length > 0) {
            await this.getUpdateComplete();
            this.isEveryProductReady = true;
        }
    }
    get focusTarget() {
        if (!this.nextNewProductTarget) this.nextNewProductTarget = new accessibility_utils_cjs_namespaceObject.FocusTargetController(this, this.bindings);
        return this.nextNewProductTarget;
    }
    get augmentedRecommendationListState() {
        return {
            ...this.recommendationsState,
            firstRequestExecuted: '' !== this.recommendationsState.responseId,
            hasError: null !== this.recommendationsState.error,
            hasItems: this.recommendationsState.products.length > 0,
            products: this.subsetRecommendations
        };
    }
    validateProps() {
        new bueno_namespaceObject.Schema({
            density: new bueno_namespaceObject.StringValue({
                constrainTo: [
                    'normal',
                    'comfortable',
                    'compact'
                ]
            }),
            display: new bueno_namespaceObject.StringValue({
                constrainTo: [
                    'grid',
                    'list',
                    'table'
                ]
            }),
            imageSize: new bueno_namespaceObject.StringValue({
                constrainTo: [
                    'small',
                    'large',
                    'icon',
                    'none'
                ]
            }),
            productsPerPage: new bueno_namespaceObject.NumberValue({
                min: 0
            }),
            slotId: new bueno_namespaceObject.StringValue({
                emptyAllowed: false
            })
        }).validate({
            density: this.density,
            display: this.display,
            imageSize: this.imageSize,
            productsPerPage: this.productsPerPage,
            slotId: this.slotId
        });
    }
    validateSlotID() {
        const recListWithRecommendation = document.querySelectorAll(`atomic-commerce-recommendation-list[slot-id="${this.slotId}"]`);
        if (recListWithRecommendation.length > 1) this.bindings.engine.logger.warn(`There are multiple atomic-commerce-recommendation-list in this page with the same slot-id property "${this.slotId}". Make sure to set a different recommendation property for each.`);
    }
    renderListHeading() {
        if (!this.augmentedRecommendationListState.headline) return;
        if (this.augmentedRecommendationListState.hasError) return;
        if (!this.isEveryProductReady && this.isAppLoaded) return (0, external_lit_namespaceObject.html)`
        <div
          aria-hidden="true"
          class="bg-neutral my-2 h-8 w-60 animate-pulse rounded"
        ></div>
      `;
        return (0, external_lit_namespaceObject.html)`${(0, heading_cjs_namespaceObject.renderHeading)({
            props: {
                level: this.headingLevel,
                part: 'label',
                class: 'm-0 mb-2'
            }
        })((0, external_lit_namespaceObject.html)`${this.bindings.i18n.t(this.recommendationsState.headline)}`)}`;
    }
    get subsetRecommendations() {
        if (!this.productsPerPage) return this.recommendationsState.products;
        return this.recommendationsState.products.slice(this.currentIndex, this.currentIndex + this.productsPerPage);
    }
    get numberOfPages() {
        return Math.ceil(this.recommendationsState.products.length / this.productsPerPage);
    }
    get currentIndex() {
        return Math.abs(this.currentPage * this.productsPerPage % this.recommendationsState.products.length);
    }
    get hasNoProducts() {
        return !this.recommendationsState.isLoading && 0 === this.augmentedRecommendationListState.products.length;
    }
    initRecommendations() {
        this.recommendations = (0, commerce_namespaceObject.buildRecommendations)(this.bindings.engine, {
            options: {
                slotId: this.slotId,
                productId: this.productId
            }
        });
        this.recommendations.refresh();
    }
    initSummary() {
        this.summary = this.recommendations.summary();
        this.unsubscribeSummary = this.summary.subscribe(()=>{
            this.summaryState = this.summary.state;
            if (this.summaryState.firstRequestExecuted) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
        });
    }
    getAtomicProductProps(product) {
        const linkContent = this.productTemplateProvider.getLinkTemplateContent(product);
        return {
            interactiveProduct: this.recommendations.interactiveProduct({
                options: {
                    product
                }
            }),
            product: product,
            renderingFunction: this.itemRenderingFunction,
            loadingFlag: this.loadingFlag,
            key: this.productListCommon.getResultId(product.permanentid, this.recommendationsState.responseId, this.density, this.imageSize),
            content: this.productTemplateProvider.getTemplateContent(product),
            linkContent,
            stopPropagation: !!linkContent,
            store: this.bindings.store,
            density: this.density,
            display: this.display,
            imageSize: this.imageSize
        };
    }
    initProductTemplateProvider() {
        this.productTemplateProvider = new product_template_provider_cjs_namespaceObject.ProductTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-product-template')),
            getResultTemplateRegistered: ()=>this.productTemplateRegistered,
            getTemplateHasError: ()=>this.templateHasError,
            setResultTemplateRegistered: (value)=>{
                this.productTemplateRegistered = value;
            },
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            }
        });
    }
    initProductListCommon() {
        this.productListCommon = new item_list_common_cjs_namespaceObject.ItemListCommon({
            engineSubscribe: this.bindings.engine.subscribe,
            getCurrentNumberOfItems: ()=>this.recommendationsState.products.length,
            getIsLoading: ()=>this.recommendationsState.isLoading,
            host: this,
            loadingFlag: this.loadingFlag,
            nextNewItemTarget: this.focusTarget,
            store: this.bindings.store
        });
    }
    createSelectChildProductListener() {
        this.addEventListener('atomic/selectChildProduct', this.selectChildProductCallback);
    }
    selectChildProductCallback(event) {
        event.stopPropagation();
        const child = event.detail.child;
        this.recommendations.promoteChildToParent(child);
    }
    computeListDisplayClasses() {
        const displayPlaceholders = !(this.isAppLoaded && this.isEveryProductReady);
        return (0, item_layout_utils_cjs_namespaceObject.getItemListDisplayClasses)('grid', this.density, this.imageSize, this.recommendationsState.isLoading, displayPlaceholders);
    }
    render() {
        return (0, external_lit_namespaceObject.html)`${(0, when_js_namespaceObject.when)(this.shouldRender, ()=>(0, external_lit_namespaceObject.html)`${(0, when_js_namespaceObject.when)(this.templateHasError, ()=>(0, external_lit_namespaceObject.html)`<slot></slot>`, ()=>(0, external_lit_namespaceObject.html)`${this.renderListHeading()}
            ${(0, carousel_cjs_namespaceObject.renderCarousel)({
                    props: {
                        bindings: this.bindings,
                        previousPage: ()=>this.previousPage(),
                        nextPage: ()=>this.nextPage(),
                        numberOfPages: this.numberOfPages,
                        currentPage: this.currentPage,
                        ariaLabel: this.bindings.i18n.t(this.recommendationsState.headline)
                    }
                })((0, external_lit_namespaceObject.html)`<div class="px-3">${this.renderRecommendationList()}</div>`)}`)}`, ()=>external_lit_namespaceObject.nothing)}`;
    }
    renderAsGrid() {
        return (0, external_lit_namespaceObject.html)`${(0, map_js_namespaceObject.map)(this.subsetRecommendations, (product, index)=>{
            const props = this.getAtomicProductProps(product);
            return (0, grid_layout_cjs_namespaceObject.renderGridLayout)({
                props: {
                    selectorForItem: 'atomic-product',
                    item: {
                        ...product,
                        clickUri: product.clickUri,
                        title: product.ec_name ?? ''
                    },
                    ...props.interactiveProduct,
                    setRef: (element)=>{
                        element && this.productListCommon.setNewResultRef(element, index);
                    }
                }
            })((0, external_lit_namespaceObject.html)`${(0, keyed_js_namespaceObject.keyed)(props.key, (0, external_lit_namespaceObject.html)`<atomic-product
            .content=${this.productTemplateProvider.getTemplateContent(product)}
            .density=${props.density}
            .display=${props.display}
            .imageSize=${props.imageSize}
            .linkContent=${'grid' === props.display ? this.productTemplateProvider.getLinkTemplateContent(product) : this.productTemplateProvider.getEmptyLinkTemplateContent()}
            .loadingFlag=${props.loadingFlag}
            .interactiveProduct=${props.interactiveProduct}
            .product=${props.product}
            .renderingFunction=${props.renderingFunction}
            .store=${props.store}
          ></atomic-product>`)}`);
        })}`;
    }
    renderRecommendationList() {
        this.productListCommon.updateBreakpoints();
        const listClasses = this.computeListDisplayClasses();
        if (!this.productTemplateRegistered || this.error) return;
        const productClasses = `${listClasses} ${!this.isEveryProductReady && 'hidden'}`;
        return (0, external_lit_namespaceObject.html)`
      ${(0, when_js_namespaceObject.when)(this.isAppLoaded, ()=>(0, display_wrapper_cjs_namespaceObject.renderDisplayWrapper)({
                props: {
                    listClasses: productClasses,
                    display: 'list'
                }
            })((0, external_lit_namespaceObject.html)`${this.renderAsGrid()}`))}
      ${(0, when_js_namespaceObject.when)(!this.isEveryProductReady, ()=>(0, display_wrapper_cjs_namespaceObject.renderDisplayWrapper)({
                props: {
                    listClasses,
                    display: 'list'
                }
            })((0, item_placeholders_cjs_namespaceObject.renderItemPlaceholders)({
                props: {
                    density: this.density,
                    display: this.display,
                    imageSize: this.imageSize,
                    numberOfPlaceholders: this.productsPerPage ?? this.recommendationsState.products.length
                }
            })))}
    `;
    }
    get shouldRender() {
        if (!this.productTemplateRegistered || this.error) return false;
        if (this.hasNoProducts) {
            this.bindings.store.unsetLoadingFlag(this.loadingFlag);
            return false;
        }
        return true;
    }
    constructor(...args){
        super(...args), this.loadingFlag = (0, utils_cjs_namespaceObject.randomID)('firstRecommendationLoaded-'), this.isAppLoaded = false, this.productTemplateRegistered = false, this.templateHasError = false, this.isEveryProductReady = false, this.currentPage = 0, this.display = 'list', this.density = 'normal', this.imageSize = 'small', this.headingLevel = 0;
    }
}
AtomicCommerceRecommendationList.styles = [
    placeholders_tw_css_cjs_default(),
    (0, external_lit_namespaceObject.css)`
      @reference "../../common/item-list/styles/mixins.css";

      :host {
        @apply atomic-grid-clickable-elements;
        @apply atomic-grid-display-common;

        /**
     * @prop --atomic-recs-number-of-columns: Number of columns for the recommendation list.
     * @prop --atomic-recs-number-of-rows: Number of rows for the recommendation list.
     */
        .list-root {
          @apply atomic-grid-with-cards;
          grid-template-columns: repeat(
            var(--atomic-recs-number-of-columns, 1),
            minmax(0, 1fr)
          );
          grid-template-rows: repeat(
            var(--atomic-recs-number-of-rows, 1),
            minmax(0, 1fr)
          );
        }

        [part='label'] {
          @apply font-sans text-2xl font-bold;
        }
      }
    `
];
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceRecommendationList.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceRecommendationList.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceRecommendationList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceRecommendationList.prototype, "productTemplateRegistered", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceRecommendationList.prototype, "templateHasError", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceRecommendationList.prototype, "isEveryProductReady", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('recommendations'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof RecommendationsState ? Object : RecommendationsState)
], AtomicCommerceRecommendationList.prototype, "recommendationsState", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof RecommendationsSummaryState ? Object : RecommendationsSummaryState)
], AtomicCommerceRecommendationList.prototype, "summaryState", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicCommerceRecommendationList.prototype, "currentPage", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'slot-id',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationList.prototype, "slotId", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'product-id',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationList.prototype, "productId", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayBasicLayout ? Object : ItemDisplayBasicLayout)
], AtomicCommerceRecommendationList.prototype, "display", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicCommerceRecommendationList.prototype, "density", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicCommerceRecommendationList.prototype, "imageSize", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'products-per-page',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicCommerceRecommendationList.prototype, "productsPerPage", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'heading-level',
        type: Number
    })
], AtomicCommerceRecommendationList.prototype, "headingLevel", void 0);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('productsPerPage'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", Promise)
], AtomicCommerceRecommendationList.prototype, "watchNumberOfRecommendationsPerPage", 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)
], AtomicCommerceRecommendationList.prototype, "render", null);
AtomicCommerceRecommendationList = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-commerce-recommendation-list'),
    (0, bindings_cjs_namespaceObject.bindings)(),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles
], AtomicCommerceRecommendationList);
exports.AtomicCommerceRecommendationList = __webpack_exports__.AtomicCommerceRecommendationList;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicCommerceRecommendationList"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
