import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildProductListing, buildSearch } 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 { ref } from "lit/directives/ref.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 { 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 { renderItemList } from "../../common/item-list/item-list.js";
import { ItemListCommon } from "../../common/item-list/item-list-common.js";
import grid_display_tw_css from "../../common/item-list/styles/grid-display.tw.css.js";
import list_display_tw_css from "../../common/item-list/styles/list-display.tw.css.js";
import placeholders_tw_css from "../../common/item-list/styles/placeholders.tw.css.js";
import table_display_tw_css from "../../common/item-list/styles/table-display.tw.css.js";
import { renderTableData, renderTableLayout, renderTableRow } from "../../common/item-list/table-layout.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 { 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 "../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 AtomicCommerceProductList extends ChildrenUpdateCompleteMixin(LitElement) {
    async setRenderFunction(productRenderingFunction) {
        this.itemRenderingFunction = productRenderingFunction;
    }
    initialize() {
        this.validateProps();
        this.initSearchOrListing();
        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('searchOrListingState')) {
            const oldState = changedProperties.get('searchOrListingState');
            if (!oldState?.isLoading && this.searchOrListingState.isLoading) this.isEveryProductReady = false;
        }
        await this.updateProductsReadyState();
    }
    async updateProductsReadyState() {
        if (this.isAppLoaded && !this.isEveryProductReady && this.summaryState?.firstRequestExecuted && this.searchOrListingState?.products?.length > 0) {
            await this.getUpdateComplete();
            this.isEveryProductReady = true;
        }
    }
    render() {
        return html`${renderItemList({
            props: {
                hasError: this.summaryState.hasError,
                hasItems: this.summaryState.hasProducts,
                hasTemplate: this.resultTemplateRegistered,
                firstRequestExecuted: this.summaryState.firstRequestExecuted,
                templateHasError: this.templateHasError
            }
        })(html`${when(this.templateHasError, ()=>html`<slot></slot>`, ()=>{
            const listClasses = this.computeListDisplayClasses();
            const productClasses = `${listClasses} ${!this.isEveryProductReady && 'hidden'}`;
            return html`
            ${when(this.isAppLoaded, ()=>renderDisplayWrapper({
                    props: {
                        listClasses: productClasses,
                        display: this.display
                    }
                })(html`${when('grid' === this.display, ()=>this.renderGrid(), ()=>html`${when('list' === this.display, ()=>this.renderList(), ()=>this.renderTable())}`)}`))}
            ${when(!this.isEveryProductReady, ()=>renderDisplayWrapper({
                    props: {
                        listClasses,
                        display: this.display
                    }
                })(renderItemPlaceholders({
                    props: {
                        density: this.density,
                        display: this.display,
                        imageSize: this.imageSize,
                        numberOfPlaceholders: this.numberOfPlaceholders
                    }
                })))}
          `;
        })}`)}`;
    }
    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'
                ]
            }),
            numberOfPlaceholders: new NumberValue({
                min: 0
            })
        }).validate({
            density: this.density,
            display: this.display,
            imageSize: this.imageSize,
            numberOfPlaceholders: this.numberOfPlaceholders
        });
    }
    initSearchOrListing() {
        if ('product-listing' === this.bindings.interfaceElement.type) this.searchOrListing = buildProductListing(this.bindings.engine);
        else this.searchOrListing = buildSearch(this.bindings.engine);
    }
    initSummary() {
        this.summary = this.searchOrListing.summary();
        this.unsubscribeSummary = this.summary.subscribe(()=>{
            this.summaryState = this.summary.state;
            if (this.summaryState.firstRequestExecuted) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
        });
    }
    initProductTemplateProvider() {
        this.productTemplateProvider = new ProductTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-product-template')),
            getResultTemplateRegistered: ()=>this.resultTemplateRegistered,
            getTemplateHasError: ()=>this.templateHasError,
            setResultTemplateRegistered: (value)=>{
                this.resultTemplateRegistered = value;
            },
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            }
        });
    }
    initProductListCommon() {
        this.productListCommon = new ItemListCommon({
            engineSubscribe: this.bindings.engine.subscribe,
            getCurrentNumberOfItems: ()=>this.searchOrListingState.products.length,
            getIsLoading: ()=>this.searchOrListingState.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.searchOrListing.promoteChildToParent(child);
    }
    computeListDisplayClasses() {
        const displayPlaceholders = !(this.isAppLoaded && this.isEveryProductReady);
        return getItemListDisplayClasses(this.display, this.density, this.imageSize, this.searchOrListingState?.isLoading, displayPlaceholders);
    }
    renderGrid() {
        return html`${map(this.searchOrListingState.products, (product, index)=>renderGridLayout({
                props: {
                    item: {
                        ...product,
                        title: product.ec_name ?? ''
                    },
                    selectorForItem: 'atomic-product',
                    setRef: (element)=>{
                        element instanceof HTMLElement && this.productListCommon.setNewResultRef(element, index);
                    }
                }
            })(html`${keyed(this.productListCommon.getResultId(product.permanentid, this.searchOrListingState.responseId, this.density, this.imageSize), html`<atomic-product
            .content=${this.productTemplateProvider.getTemplateContent(product)}
            .density=${this.density}
            .display=${this.display}
            .imageSize=${this.imageSize}
            .interactiveProduct=${this.searchOrListing.interactiveProduct({
                options: {
                    product
                }
            })}
            .linkContent=${this.productTemplateProvider.getLinkTemplateContent(product)}
            .loadingFlag=${this.loadingFlag}
            .product=${product}
            .renderingFunction=${this.itemRenderingFunction}
            .store=${this.bindings.store}
          ></atomic-product>`)}`))}`;
    }
    renderList() {
        return html`${map(this.searchOrListingState.products, (product, index)=>html`${keyed(this.productListCommon.getResultId(product.permanentid, this.searchOrListingState.responseId, this.density, this.imageSize), html`<atomic-product
          part="outline"
          ${ref((element)=>element instanceof HTMLElement && this.productListCommon.setNewResultRef(element, index))}
          .content=${this.productTemplateProvider.getTemplateContent(product)}
          .density=${this.density}
          .display=${this.display}
          .imageSize=${this.imageSize}
          .interactiveProduct=${this.searchOrListing.interactiveProduct({
                options: {
                    product
                }
            })}
          .linkContent=${this.productTemplateProvider.getLinkTemplateContent(product)}
          .loadingFlag=${this.loadingFlag}
          .product=${product}
          .renderingFunction=${this.itemRenderingFunction}
          .store=${this.bindings.store}
        ></atomic-product>`)}`)}`;
    }
    renderTable() {
        return html`${when(this.summaryState.hasProducts, ()=>{
            const firstItem = this.searchOrListingState.products[0];
            const listClasses = this.computeListDisplayClasses();
            const templateContentForFirstItem = this.productTemplateProvider.getTemplateContent(firstItem);
            return renderTableLayout({
                props: {
                    firstItem,
                    host: this,
                    itemRenderingFunction: this.itemRenderingFunction,
                    label: this.bindings.i18n.t('view-products'),
                    listClasses,
                    logger: this.bindings.engine.logger,
                    templateContentForFirstItem
                }
            })(html`${map(this.searchOrListingState.products, (product, index)=>{
                const key = this.productListCommon.getResultId(product.permanentid, this.searchOrListingState.responseId, this.density, this.imageSize);
                return renderTableRow({
                    props: {
                        key,
                        rowIndex: index,
                        setRef: (element)=>element instanceof HTMLElement && this.productListCommon.setNewResultRef(element, index)
                    }
                })(html`${renderTableData({
                    props: {
                        firstItem,
                        key,
                        itemRenderingFunction: this.itemRenderingFunction,
                        templateContentForFirstItem,
                        renderItem: (content)=>html`${keyed(key, html`<atomic-product
                        .content=${content}
                        .density=${this.density}
                        .display=${this.display}
                        .imageSize=${this.imageSize}
                        .interactiveProduct=${this.searchOrListing.interactiveProduct({
                                options: {
                                    product
                                }
                            })}
                        .linkContent=${this.productTemplateProvider.getLinkTemplateContent(product)}
                        .loadingFlag=${this.loadingFlag}
                        .product=${product}
                        .store=${this.bindings.store}
                      ></atomic-product>`)}`
                    }
                })}`);
            })}`);
        }, ()=>nothing)}`;
    }
    get focusTarget() {
        if (!this.nextNewResultTarget) this.nextNewResultTarget = new FocusTargetController(this, this.bindings);
        return this.nextNewResultTarget;
    }
    constructor(...args){
        super(...args), this.loadingFlag = randomID('firstProductLoaded-'), this.isAppLoaded = false, this.isEveryProductReady = false, this.resultTemplateRegistered = false, this.templateHasError = false, this.density = 'normal', this.display = 'grid', this.imageSize = 'small', this.numberOfPlaceholders = 24;
    }
}
AtomicCommerceProductList.styles = [
    placeholders_tw_css,
    table_display_tw_css,
    list_display_tw_css,
    grid_display_tw_css,
    css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */:host .result-link{color:var(--atomic-on-background)}:host .result-link:focus-visible,:host .result-link:hover{color:var(--atomic-primary);text-decoration:underline}:host .result-link:focus{outline:none}:host .result-link:visited{color:var(--atomic-visited)}:host .result-grid{grid-template-columns:repeat(5,minmax(0,1fr));justify-items:center}:host .result-grid a{justify-content:center}:host .result-list{display:flex;flex-direction:column}:host .result-list .result-item{display:flex;flex-wrap:wrap;max-width:600px;width:100%}:host .result-list .result-item .result-details{align-content:center}@media (min-width:1024px){:host .result-grid{display:grid}}@media not all and (min-width:1024px){:host .result-grid{display:flex;flex-direction:column}}`
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceProductList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceProductList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicCommerceProductList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicCommerceProductList.prototype, "isEveryProductReady", void 0);
_ts_decorate([
    state()
], AtomicCommerceProductList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicCommerceProductList.prototype, "templateHasError", void 0);
_ts_decorate([
    bindStateToController('searchOrListing'),
    state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceProductList.prototype, "searchOrListingState", void 0);
_ts_decorate([
    bindStateToController('summary'),
    state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceProductList.prototype, "summaryState", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicCommerceProductList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayLayout ? Object : ItemDisplayLayout)
], AtomicCommerceProductList.prototype, "display", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicCommerceProductList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-placeholders',
        type: Number
    })
], AtomicCommerceProductList.prototype, "numberOfPlaceholders", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceProductList.prototype, "render", null);
AtomicCommerceProductList = _ts_decorate([
    customElement('atomic-commerce-product-list'),
    bindings(),
    withTailwindStyles
], AtomicCommerceProductList);
export { AtomicCommerceProductList };
