import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { loadIPXActionsHistoryActions } from "@coveo/headless";
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 { 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 placeholders_tw_css from "../../common/item-list/styles/placeholders.tw.css.js";
import "../../recommendations/atomic-recs-result-template/atomic-recs-result-template.js";
import "../../recommendations/atomic-recs-result/atomic-recs-result.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 AtomicIpxRecsList 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.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
        });
        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
        });
        this.actionsHistoryActions = loadIPXActionsHistoryActions(this.bindings.engine);
        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.updateResultsReadyState();
    }
    async updateResultsReadyState() {
        if (this.isAppLoaded && !this.isEveryResultReady && this.recommendationListState?.searchResponseId !== '' && this.recommendationListState?.recommendations?.length > 0) {
            await this.getUpdateComplete();
            this.isEveryResultReady = true;
        }
    }
    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
        };
    }
    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-ipx-recs-list[recommendation="${this.recommendation}"]`);
        if (recListWithRecommendation.length > 1) this.bindings.engine.logger.warn(`There are multiple atomic-ipx-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);
        }
    }
    get currentIndex() {
        if (!this.recommendationListState.recommendations.length) return 0;
        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() {
        if (!this.numberOfRecommendationsPerPage) return 1;
        return Math.ceil(this.recommendationListState.recommendations.length / this.numberOfRecommendationsPerPage);
    }
    get hasPagination() {
        return !!this.numberOfRecommendationsPerPage && this.numberOfPages > 1;
    }
    get shouldRenderPagination() {
        return this.hasPagination && this.recommendationListStateWithAugment.hasItems;
    }
    get hasNoResults() {
        return !this.recommendationListState.isLoading && 0 === this.recommendationListStateWithAugment.results.length;
    }
    onSelect(recommendation, originalSelect) {
        if (recommendation.raw.permanentid && this.actionsHistoryActions) {
            const action = this.actionsHistoryActions.addPageViewEntryInActionsHistory(recommendation.raw.permanentid);
            this.bindings.engine.dispatch(action);
        }
        originalSelect();
    }
    getPropsForAtomicRecsResult(recommendation) {
        const interactiveResult = buildInteractiveResult(this.bindings.engine, {
            options: {
                result: recommendation
            }
        });
        const originalSelect = interactiveResult.select;
        interactiveResult.select = ()=>{
            this.onSelect(recommendation, originalSelect);
        };
        const linkContent = this.itemTemplateProvider.getLinkTemplateContent(recommendation);
        return {
            interactiveResult,
            result: recommendation,
            renderingFunction: this.itemRenderingFunction,
            loadingFlag: this.loadingFlag,
            key: this.itemListCommon.getResultId(recommendation.uniqueId, this.recommendationListState.searchResponseId, this.density, this.imageSize),
            content: this.itemTemplateProvider.getTemplateContent(recommendation),
            linkContent,
            stopPropagation: !!linkContent,
            store: this.bindings.store,
            density: this.density,
            display: this.display,
            imageSize: this.imageSize
        };
    }
    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.isEveryResultReady && this.isAppLoaded) return html`
        <div
          aria-hidden="true"
          class="bg-neutral my-2 h-8 w-60 animate-pulse rounded"
        ></div>
      `;
        if (this.recommendationListStateWithAugment.firstRequestExecuted && !this.recommendationListStateWithAugment.hasItems) return nothing;
        return html`${renderHeading({
            props: {
                level: this.headingLevel,
                part: 'label',
                class: 'm-0 mb-2'
            }
        })(html`${this.bindings.i18n.t(this.label)}`)}`;
    }
    renderAsGrid() {
        return html`${map(this.subsetRecommendations, (recommendation, index)=>{
            const props = this.getPropsForAtomicRecsResult(recommendation);
            return renderGridLayout({
                props: {
                    selectorForItem: 'atomic-recs-result',
                    item: {
                        ...recommendation,
                        clickUri: recommendation.clickUri,
                        title: recommendation.title ?? ''
                    },
                    ...props.interactiveResult,
                    setRef: (element)=>{
                        element && this.itemListCommon.setNewResultRef(element, index);
                    }
                }
            })(html`${keyed(props.key, html`<atomic-recs-result
            .content=${props.content}
            .density=${props.density}
            .display=${props.display}
            .imageSize=${props.imageSize}
            .linkContent=${props.linkContent}
            .loadingFlag=${props.loadingFlag}
            .interactiveResult=${props.interactiveResult}
            .result=${props.result}
            .renderingFunction=${props.renderingFunction}
            .store=${props.store}
          ></atomic-recs-result>`)}`);
        })}`;
    }
    renderRecommendationList() {
        this.itemListCommon.updateBreakpoints();
        const listClasses = this.computeListDisplayClasses();
        if (!this.resultTemplateRegistered || this.error) return nothing;
        const resultClasses = [
            listClasses,
            !this.isEveryResultReady && 'hidden'
        ].filter(Boolean).join(' ');
        return html`
      ${when(this.isAppLoaded, ()=>renderDisplayWrapper({
                props: {
                    listClasses: resultClasses,
                    display: 'grid'
                }
            })(html`${this.renderAsGrid()}`))}
      ${when(!this.isEveryResultReady, ()=>renderDisplayWrapper({
                props: {
                    listClasses,
                    display: 'grid'
                }
            })(renderItemPlaceholders({
                props: {
                    density: this.density,
                    display: this.display,
                    imageSize: this.imageSize,
                    numberOfPlaceholders: this.numberOfRecommendationsPerPage ?? this.numberOfRecommendations
                }
            })))}
    `;
    }
    get shouldRender() {
        if (!this.resultTemplateRegistered || this.error) return false;
        if (this.hasNoResults) return false;
        return true;
    }
    render() {
        if (!this.shouldRender) {
            if (this.hasNoResults) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
            return nothing;
        }
        return html`${when(this.templateHasError, ()=>html`<slot></slot>`, ()=>html`${this.renderHeading()}
        ${when(this.shouldRenderPagination, ()=>renderCarousel({
                    props: {
                        bindings: this.bindings,
                        previousPage: ()=>this.previousPage(),
                        nextPage: ()=>this.nextPage(),
                        numberOfPages: this.numberOfPages,
                        currentPage: this.currentPage,
                        ariaLabel: this.bindings.i18n.t(this.label ?? 'recommendations')
                    }
                })(html`<div class="px-3">${this.renderRecommendationList()}</div>`), ()=>this.renderRecommendationList())}`)}`;
    }
    constructor(){
        super(), this.loadingFlag = randomID('firstRecommendationLoaded-'), this.currentPage = 0, this.isAppLoaded = false, this.isEveryResultReady = false, this.resultTemplateRegistered = false, this.templateHasError = false, 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
            }), AtomicIpxRecsList.propsSchema, false);
    }
}
AtomicIpxRecsList.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}`
];
AtomicIpxRecsList.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)
], AtomicIpxRecsList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicIpxRecsList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicIpxRecsList.prototype, "currentPage", void 0);
_ts_decorate([
    state()
], AtomicIpxRecsList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicIpxRecsList.prototype, "isEveryResultReady", void 0);
_ts_decorate([
    state()
], AtomicIpxRecsList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicIpxRecsList.prototype, "templateHasError", void 0);
_ts_decorate([
    bindStateToController('recommendationList'),
    state(),
    _ts_metadata("design:type", "u" < typeof RecommendationListState ? Object : RecommendationListState)
], AtomicIpxRecsList.prototype, "recommendationListState", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    })
], AtomicIpxRecsList.prototype, "recommendation", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayBasicLayout ? Object : ItemDisplayBasicLayout)
], AtomicIpxRecsList.prototype, "display", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicIpxRecsList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicIpxRecsList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-recommendations',
        type: Number
    })
], AtomicIpxRecsList.prototype, "numberOfRecommendations", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-recommendations-per-page',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicIpxRecsList.prototype, "numberOfRecommendationsPerPage", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicIpxRecsList.prototype, "label", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'heading-level',
        type: Number
    })
], AtomicIpxRecsList.prototype, "headingLevel", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicIpxRecsList.prototype, "render", null);
AtomicIpxRecsList = _ts_decorate([
    customElement('atomic-ipx-recs-list'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicIpxRecsList);
export { AtomicIpxRecsList };
