import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildInteractiveResult, buildRecommendationList, loadConfigurationActions } from "@coveo/headless/recommendation";
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 { 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 { ResultTemplateProvider } from "../../common/item-list/result-template-provider.js";
import placeholders_tw_css from "../../common/item-list/styles/placeholders.tw.css.js";
import { getItemListDisplayClasses } from "../../common/layout/item-layout-utils.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.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-recs-result/atomic-recs-result.js";
import "../atomic-recs-result-template/atomic-recs-result-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 AtomicRecsList extends ChildrenUpdateCompleteMixin(LitElement) {
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    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.validateNumberOfRecommendationsPerPage();
        this.validateRecommendationIdentifier();
        this.updateOriginLevel2();
        this.recommendationList = buildRecommendationList(this.bindings.engine, {
            options: {
                id: this.recommendation,
                numberOfRecommendations: this.numberOfRecommendations
            }
        });
        this.initResultTemplateProvider();
        this.initItemListCommon();
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    async willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('numberOfRecommendationsPerPage')) this.currentPage = 0;
        if (changedProperties.has('recommendationListState')) {
            const oldState = changedProperties.get('recommendationListState');
            if ('' !== this.recommendationListState.searchResponseId) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
            if (!oldState?.isLoading && this.recommendationListState.isLoading) this.isEveryResultReady = false;
        }
        await this.updateResultReadyState();
    }
    async updateResultReadyState() {
        if (this.isAppLoaded && !this.isEveryResultReady && this.recommendationListState?.searchResponseId !== '' && this.recommendationListState?.recommendations?.length > 0) {
            await this.getUpdateComplete();
            this.isEveryResultReady = true;
        }
    }
    render() {
        if (!this.resultTemplateRegistered || this.templateHasError || this.error || this.recommendationListStateWithAugment.hasError) return nothing;
        const listContent = this.renderListOfRecommendations();
        return html`
      ${this.renderHeading()}
      ${when(this.shouldRenderPagination, ()=>renderCarousel({
                props: {
                    bindings: this.bindings,
                    currentPage: this.currentPage,
                    nextPage: ()=>this.nextPage(),
                    previousPage: ()=>this.previousPage(),
                    numberOfPages: this.numberOfPages,
                    ariaLabel: this.label ? this.bindings.i18n.t(this.label) : this.bindings.i18n.t('recommendations')
                }
            })(listContent), ()=>listContent)}
    `;
    }
    get focusTarget() {
        if (!this.nextNewResultTarget) this.nextNewResultTarget = new FocusTargetController(this, this.bindings);
        return this.nextNewResultTarget;
    }
    get recommendationListStateWithAugment() {
        return {
            ...this.recommendationListState,
            firstRequestExecuted: '' !== this.recommendationListState.searchResponseId,
            hasError: null !== this.recommendationListState.error,
            hasItems: 0 !== this.recommendationListState.recommendations.length,
            results: this.subsetRecommendations
        };
    }
    get currentIndex() {
        return Math.abs(this.currentPage * this.numberOfRecommendationsPerPage % this.recommendationListState.recommendations.length);
    }
    get subsetRecommendations() {
        if (!this.numberOfRecommendationsPerPage) return this.recommendationListState.recommendations;
        return this.recommendationListState.recommendations.slice(this.currentIndex, this.currentIndex + this.numberOfRecommendationsPerPage);
    }
    get numberOfPages() {
        return Math.ceil(this.recommendationListState.recommendations.length / this.numberOfRecommendationsPerPage);
    }
    get hasPagination() {
        return this.numberOfPages > 1;
    }
    get shouldRenderPagination() {
        return this.hasPagination && this.recommendationListStateWithAugment.hasItems;
    }
    validateNumberOfRecommendationsPerPage() {
        if (void 0 === this.numberOfRecommendationsPerPage) return;
        const msg = new NumberValue({
            min: 1,
            max: this.numberOfRecommendations - 1
        }).validate(this.numberOfRecommendationsPerPage);
        if (msg) this.error = new Error(`The "numberOfRecommendationsPerPage" is invalid: ${msg}`);
    }
    validateRecommendationIdentifier() {
        const recListWithRecommendation = document.querySelectorAll(`atomic-recs-list[recommendation="${this.recommendation}"]`);
        if (recListWithRecommendation.length > 1) this.bindings.engine.logger.warn(`There are multiple atomic-recs-list in this page with the same recommendation property "${this.recommendation}". Make sure to set a different recommendation property for each.`);
    }
    updateOriginLevel2() {
        if (this.label) {
            const action = loadConfigurationActions(this.bindings.engine).setOriginLevel2({
                originLevel2: this.label
            });
            this.bindings.engine.dispatch(action);
        }
    }
    initResultTemplateProvider() {
        this.itemTemplateProvider = new ResultTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-recs-result-template')),
            getResultTemplateRegistered: ()=>this.resultTemplateRegistered,
            getTemplateHasError: ()=>this.templateHasError,
            setResultTemplateRegistered: (value)=>{
                this.resultTemplateRegistered = value;
            },
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            },
            bindings: this.bindings
        });
    }
    initItemListCommon() {
        this.itemListCommon = new ItemListCommon({
            engineSubscribe: this.bindings.engine.subscribe,
            getCurrentNumberOfItems: ()=>this.recommendationListState.recommendations.length,
            getIsLoading: ()=>this.recommendationListState.isLoading,
            host: this,
            loadingFlag: this.loadingFlag,
            nextNewItemTarget: this.focusTarget,
            store: this.bindings.store
        });
    }
    computeListDisplayClasses() {
        const displayPlaceholders = !(this.isAppLoaded && this.isEveryResultReady);
        return getItemListDisplayClasses('grid', this.density, this.imageSize, this.recommendationListState?.isLoading, displayPlaceholders);
    }
    renderHeading() {
        if (!this.label) return nothing;
        if (this.recommendationListStateWithAugment.hasError) return nothing;
        if (this.recommendationListStateWithAugment.firstRequestExecuted && !this.recommendationListStateWithAugment.hasItems) return nothing;
        return renderHeading({
            props: {
                level: this.headingLevel,
                part: 'label',
                class: 'm-0 mb-2'
            }
        })(html`${this.bindings.i18n.t(this.label)}`);
    }
    renderListOfRecommendations() {
        const listClasses = this.computeListDisplayClasses();
        const resultClasses = `${listClasses} ${!this.isEveryResultReady && 'hidden'}`;
        return html`
      ${when(this.isAppLoaded, ()=>renderDisplayWrapper({
                props: {
                    listClasses: resultClasses,
                    display: 'grid'
                }
            })(html`${this.renderGrid()}`))}
      ${when(!this.isEveryResultReady, ()=>renderDisplayWrapper({
                props: {
                    listClasses,
                    display: 'grid'
                }
            })(renderItemPlaceholders({
                props: {
                    density: this.density,
                    display: this.display,
                    imageSize: this.imageSize,
                    numberOfPlaceholders: this.numberOfRecommendationsPerPage ?? this.numberOfRecommendations
                }
            })))}
    `;
    }
    renderGrid() {
        return html`${map(this.subsetRecommendations, (recommendation, index)=>renderGridLayout({
                props: {
                    item: {
                        ...recommendation,
                        title: recommendation.title ?? ''
                    },
                    selectorForItem: 'atomic-recs-result',
                    setRef: (element)=>{
                        element instanceof HTMLElement && this.itemListCommon.setNewResultRef(element, index);
                    }
                }
            })(html`${keyed(this.getResultId(recommendation), html`<atomic-recs-result
            .content=${this.getContent(recommendation)}
            .density=${this.density}
            .display=${this.display}
            .imageSize=${this.imageSize}
            .interactiveResult=${this.getInteractiveResult(recommendation)}
            .linkContent=${this.getLinkContent(recommendation)}
            .loadingFlag=${this.loadingFlag}
            .result=${recommendation}
            .renderingFunction=${this.itemRenderingFunction}
            .store=${this.bindings.store}
          ></atomic-recs-result>`)}`))}`;
    }
    getLinkContent(result) {
        return this.itemTemplateProvider.getLinkTemplateContent(result);
    }
    getContent(result) {
        return this.itemTemplateProvider.getTemplateContent(result);
    }
    getInteractiveResult(result) {
        return buildInteractiveResult(this.bindings.engine, {
            options: {
                result
            }
        });
    }
    getResultId(result) {
        return this.itemListCommon.getResultId(result.uniqueId, this.recommendationListState.searchResponseId, this.density, this.imageSize);
    }
    constructor(){
        super(), this.loadingFlag = randomID('firstRecommendationLoaded-'), this.isAppLoaded = false, this.isEveryResultReady = false, this.resultTemplateRegistered = false, this.templateHasError = false, this.currentPage = 0, this.recommendation = 'Recommendation', this.display = 'list', this.density = 'normal', this.imageSize = 'small', this.numberOfRecommendations = 10, this.headingLevel = 0;
        new ValidatePropsController(this, ()=>({
                density: this.density,
                display: this.display,
                imageSize: this.imageSize
            }), AtomicRecsList.propsSchema, false);
    }
}
AtomicRecsList.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{display:block}: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))}: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)}:host atomic-result:not(.hydrated){visibility:hidden}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}`
];
AtomicRecsList.propsSchema = new Schema({
    density: new StringValue({
        constrainTo: [
            'normal',
            'comfortable',
            'compact'
        ]
    }),
    display: new StringValue({
        constrainTo: [
            'grid',
            'list'
        ]
    }),
    imageSize: new StringValue({
        constrainTo: [
            'small',
            'large',
            'icon',
            'none'
        ]
    })
});
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof RecsBindings ? Object : RecsBindings)
], AtomicRecsList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicRecsList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicRecsList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicRecsList.prototype, "isEveryResultReady", void 0);
_ts_decorate([
    state()
], AtomicRecsList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicRecsList.prototype, "templateHasError", void 0);
_ts_decorate([
    state()
], AtomicRecsList.prototype, "currentPage", void 0);
_ts_decorate([
    bindStateToController('recommendationList'),
    state(),
    _ts_metadata("design:type", "u" < typeof RecommendationListState ? Object : RecommendationListState)
], AtomicRecsList.prototype, "recommendationListState", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    })
], AtomicRecsList.prototype, "recommendation", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayBasicLayout ? Object : ItemDisplayBasicLayout)
], AtomicRecsList.prototype, "display", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicRecsList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicRecsList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-recommendations',
        type: Number
    })
], AtomicRecsList.prototype, "numberOfRecommendations", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-recommendations-per-page',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicRecsList.prototype, "numberOfRecommendationsPerPage", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicRecsList.prototype, "label", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'heading-level',
        type: Number
    })
], AtomicRecsList.prototype, "headingLevel", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRecsList.prototype, "render", null);
AtomicRecsList = _ts_decorate([
    customElement('atomic-recs-list'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicRecsList);
export { AtomicRecsList };
