import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildRecommendations } from "@coveo/headless/commerce";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";
import { map } from "lit/directives/map.js";
import { when } from "lit/directives/when.js";
import { ProductTemplateProvider } from "../product-list/product-template-provider.js";
import { renderItemPlaceholders } from "../../common/atomic-result-placeholder/item-placeholders.js";
import { renderCarousel } from "../../common/carousel.js";
import { renderHeading } from "../../common/heading.js";
import { createAppLoadedListener } from "../../common/interface/store.js";
import { renderDisplayWrapper } from "../../common/item-list/display-wrapper.js";
import { renderGridLayout } from "../../common/item-list/grid-layout.js";
import { ItemListCommon } from "../../common/item-list/item-list-common.js";
import { getItemListDisplayClasses } from "../../common/layout/item-layout-utils.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { watch } from "../../../decorators/watch.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { ChildrenUpdateCompleteMixin } from "../../../mixins/children-update-complete-mixin.js";
import { FocusTargetController } from "../../../utils/accessibility-utils.js";
import { randomID } from "../../../utils/utils.js";
import placeholders_tw_css from "../../common/item-list/styles/placeholders.tw.css.js";
import "../atomic-product/atomic-product.js";
import "../atomic-product-template/atomic-product-template.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 AtomicCommerceRecommendationList extends ChildrenUpdateCompleteMixin(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();
        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 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 Schema({
            density: new StringValue({
                constrainTo: [
                    'normal',
                    'comfortable',
                    'compact'
                ]
            }),
            display: new StringValue({
                constrainTo: [
                    'grid',
                    'list',
                    'table'
                ]
            }),
            imageSize: new StringValue({
                constrainTo: [
                    'small',
                    'large',
                    'icon',
                    'none'
                ]
            }),
            productsPerPage: new NumberValue({
                min: 0
            }),
            slotId: new 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 html`
        <div
          aria-hidden="true"
          class="bg-neutral my-2 h-8 w-60 animate-pulse rounded"
        ></div>
      `;
        return html`${renderHeading({
            props: {
                level: this.headingLevel,
                part: 'label',
                class: 'm-0 mb-2'
            }
        })(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 = 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 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 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 getItemListDisplayClasses('grid', this.density, this.imageSize, this.recommendationsState.isLoading, displayPlaceholders);
    }
    render() {
        return html`${when(this.shouldRender, ()=>html`${when(this.templateHasError, ()=>html`<slot></slot>`, ()=>html`${this.renderListHeading()}
            ${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)
                    }
                })(html`<div class="px-3">${this.renderRecommendationList()}</div>`)}`)}`, ()=>nothing)}`;
    }
    renderAsGrid() {
        return html`${map(this.subsetRecommendations, (product, index)=>{
            const props = this.getAtomicProductProps(product);
            return renderGridLayout({
                props: {
                    selectorForItem: 'atomic-product',
                    item: {
                        ...product,
                        clickUri: product.clickUri,
                        title: product.ec_name ?? ''
                    },
                    ...props.interactiveProduct,
                    setRef: (element)=>{
                        element && this.productListCommon.setNewResultRef(element, index);
                    }
                }
            })(html`${keyed(props.key, 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 html`
      ${when(this.isAppLoaded, ()=>renderDisplayWrapper({
                props: {
                    listClasses: productClasses,
                    display: 'list'
                }
            })(html`${this.renderAsGrid()}`))}
      ${when(!this.isEveryProductReady, ()=>renderDisplayWrapper({
                props: {
                    listClasses,
                    display: 'list'
                }
            })(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 = 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,
    css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,::backdrop,:after,:before{--tw-border-style:solid;--tw-font-weight:initial}}}:host [part~=outline][part~=result-list-grid-clickable-container]{border:1px solid #0000;border-radius:1rem;padding:1rem;position:relative;transition:all .12s ease-out}:host [part~=outline][part~=result-list-grid-clickable-container]:hover{border-color:var(--atomic-neutral);border-style:var(--tw-border-style);border-width:1px;box-shadow:0 10px 25px var(--atomic-neutral);cursor:pointer}:host [part=result-list-grid-clickable]:focus-visible{border-color:var(--atomic-primary);border-radius:2px;border-style:var(--tw-border-style);border-width:2px;color:var(--atomic-primary);cursor:pointer;display:inline-block;position:absolute;text-align:center;text-decoration:underline}:host [part=result-list-grid-clickable]:not(:focus){clip:rect(1px,1px,1px,1px);overflow:hidden;padding:0;position:absolute}:host .list-wrapper{word-break:break-word}:host .list-root.display-grid{display:grid;justify-content:space-evenly}:host .list-root.display-grid .result-component{box-sizing:border-box;height:100%}:host .list-root [part~=outline]{border-color:var(--atomic-neutral);border-radius:1rem;border-style:var(--tw-border-style);border-width:1px;padding:1rem}:host .list-root atomic-result-placeholder{border-color:#0000}:host .list-root{grid-column-gap:.5rem;grid-row-gap:.5rem;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))}:host [part=label]{font-family:var(--atomic-font-family);font-size:var(--atomic-text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height,1.33333));--tw-font-weight:var(--atomic-font-bold);font-weight:var(--atomic-font-bold)}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}`
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceRecommendationList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceRecommendationList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicCommerceRecommendationList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicCommerceRecommendationList.prototype, "productTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicCommerceRecommendationList.prototype, "templateHasError", void 0);
_ts_decorate([
    state()
], AtomicCommerceRecommendationList.prototype, "isEveryProductReady", void 0);
_ts_decorate([
    bindStateToController('recommendations'),
    state(),
    _ts_metadata("design:type", "u" < typeof RecommendationsState ? Object : RecommendationsState)
], AtomicCommerceRecommendationList.prototype, "recommendationsState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof RecommendationsSummaryState ? Object : RecommendationsSummaryState)
], AtomicCommerceRecommendationList.prototype, "summaryState", void 0);
_ts_decorate([
    state()
], AtomicCommerceRecommendationList.prototype, "currentPage", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'slot-id',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationList.prototype, "slotId", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'product-id',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceRecommendationList.prototype, "productId", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayBasicLayout ? Object : ItemDisplayBasicLayout)
], AtomicCommerceRecommendationList.prototype, "display", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicCommerceRecommendationList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicCommerceRecommendationList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'products-per-page',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicCommerceRecommendationList.prototype, "productsPerPage", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'heading-level',
        type: Number
    })
], AtomicCommerceRecommendationList.prototype, "headingLevel", void 0);
_ts_decorate([
    watch('productsPerPage'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", Promise)
], AtomicCommerceRecommendationList.prototype, "watchNumberOfRecommendationsPerPage", null);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRecommendationList.prototype, "render", null);
AtomicCommerceRecommendationList = _ts_decorate([
    customElement('atomic-commerce-recommendation-list'),
    bindings(),
    withTailwindStyles
], AtomicCommerceRecommendationList);
export { AtomicCommerceRecommendationList };
