"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__, {
    AtomicIpxRecsList: ()=>AtomicIpxRecsList
});
const bueno_namespaceObject = require("@coveo/bueno");
const headless_namespaceObject = require("@coveo/headless");
const recommendation_namespaceObject = require("@coveo/headless/recommendation");
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 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 result_template_provider_cjs_namespaceObject = require("../../common/item-list/result-template-provider.cjs");
const item_layout_utils_cjs_namespaceObject = require("../../common/layout/item-layout-utils.cjs");
const validate_props_controller_cjs_namespaceObject = require("../../common/validate-props-controller/validate-props-controller.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 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("../../recommendations/atomic-recs-result-template/atomic-recs-result-template.cjs");
require("../../recommendations/atomic-recs-result/atomic-recs-result.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 AtomicIpxRecsList extends (0, children_update_complete_mixin_cjs_namespaceObject.ChildrenUpdateCompleteMixin)(external_lit_namespaceObject.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 = (0, recommendation_namespaceObject.buildRecommendationList)(this.bindings.engine, {
            options: {
                id: this.recommendation,
                numberOfRecommendations: this.numberOfRecommendations
            }
        });
        this.itemTemplateProvider = new result_template_provider_cjs_namespaceObject.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 item_list_common_cjs_namespaceObject.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 = (0, headless_namespaceObject.loadIPXActionsHistoryActions)(this.bindings.engine);
        (0, store_cjs_namespaceObject.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 accessibility_utils_cjs_namespaceObject.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 bueno_namespaceObject.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 = (0, recommendation_namespaceObject.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 = (0, recommendation_namespaceObject.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 (0, item_layout_utils_cjs_namespaceObject.getItemListDisplayClasses)('grid', this.density, this.imageSize, this.recommendationListState.isLoading, displayPlaceholders);
    }
    renderHeading() {
        if (!this.label) return external_lit_namespaceObject.nothing;
        if (this.recommendationListStateWithAugment.hasError) return external_lit_namespaceObject.nothing;
        if (!this.isEveryResultReady && 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>
      `;
        if (this.recommendationListStateWithAugment.firstRequestExecuted && !this.recommendationListStateWithAugment.hasItems) return external_lit_namespaceObject.nothing;
        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.label)}`)}`;
    }
    renderAsGrid() {
        return (0, external_lit_namespaceObject.html)`${(0, map_js_namespaceObject.map)(this.subsetRecommendations, (recommendation, index)=>{
            const props = this.getPropsForAtomicRecsResult(recommendation);
            return (0, grid_layout_cjs_namespaceObject.renderGridLayout)({
                props: {
                    selectorForItem: 'atomic-recs-result',
                    item: {
                        ...recommendation,
                        clickUri: recommendation.clickUri,
                        title: recommendation.title ?? ''
                    },
                    ...props.interactiveResult,
                    setRef: (element)=>{
                        element && this.itemListCommon.setNewResultRef(element, index);
                    }
                }
            })((0, external_lit_namespaceObject.html)`${(0, keyed_js_namespaceObject.keyed)(props.key, (0, external_lit_namespaceObject.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 external_lit_namespaceObject.nothing;
        const resultClasses = [
            listClasses,
            !this.isEveryResultReady && 'hidden'
        ].filter(Boolean).join(' ');
        return (0, external_lit_namespaceObject.html)`
      ${(0, when_js_namespaceObject.when)(this.isAppLoaded, ()=>(0, display_wrapper_cjs_namespaceObject.renderDisplayWrapper)({
                props: {
                    listClasses: resultClasses,
                    display: 'grid'
                }
            })((0, external_lit_namespaceObject.html)`${this.renderAsGrid()}`))}
      ${(0, when_js_namespaceObject.when)(!this.isEveryResultReady, ()=>(0, display_wrapper_cjs_namespaceObject.renderDisplayWrapper)({
                props: {
                    listClasses,
                    display: 'grid'
                }
            })((0, item_placeholders_cjs_namespaceObject.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 external_lit_namespaceObject.nothing;
        }
        return (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.renderHeading()}
        ${(0, when_js_namespaceObject.when)(this.shouldRenderPagination, ()=>(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.label ?? 'recommendations')
                    }
                })((0, external_lit_namespaceObject.html)`<div class="px-3">${this.renderRecommendationList()}</div>`), ()=>this.renderRecommendationList())}`)}`;
    }
    constructor(){
        super(), this.loadingFlag = (0, utils_cjs_namespaceObject.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 validate_props_controller_cjs_namespaceObject.ValidatePropsController(this, ()=>({
                density: this.density,
                display: this.display,
                imageSize: this.imageSize
            }), AtomicIpxRecsList.propsSchema, false);
    }
}
AtomicIpxRecsList.styles = [
    placeholders_tw_css_cjs_default(),
    (0, external_lit_namespaceObject.css)`
      @reference '../../../utils/tailwind.global.tw.css';
      @import '../../common/item-list/styles/mixins.css';

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

        /**
 * @prop --atomic-recs-number-of-columns: Number of columns 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)
          );
        }

        [part='label'] {
          @apply font-sans text-2xl font-bold;
        }

        atomic-result:not(.hydrated) {
          visibility: hidden;
        }
      }
    `
];
AtomicIpxRecsList.propsSchema = new bueno_namespaceObject.Schema({
    density: new bueno_namespaceObject.StringValue({
        constrainTo: [
            'normal',
            'comfortable',
            'compact'
        ]
    }),
    display: new bueno_namespaceObject.StringValue({
        constrainTo: [
            'grid',
            'list'
        ]
    }),
    imageSize: new bueno_namespaceObject.StringValue({
        constrainTo: [
            'small',
            'large',
            'icon',
            'none'
        ]
    })
});
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof RecsBindings ? Object : RecsBindings)
], AtomicIpxRecsList.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicIpxRecsList.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicIpxRecsList.prototype, "currentPage", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicIpxRecsList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicIpxRecsList.prototype, "isEveryResultReady", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicIpxRecsList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)()
], AtomicIpxRecsList.prototype, "templateHasError", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('recommendationList'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof RecommendationListState ? Object : RecommendationListState)
], AtomicIpxRecsList.prototype, "recommendationListState", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    })
], AtomicIpxRecsList.prototype, "recommendation", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayBasicLayout ? Object : ItemDisplayBasicLayout)
], AtomicIpxRecsList.prototype, "display", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicIpxRecsList.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)
], AtomicIpxRecsList.prototype, "imageSize", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'number-of-recommendations',
        type: Number
    })
], AtomicIpxRecsList.prototype, "numberOfRecommendations", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'number-of-recommendations-per-page',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicIpxRecsList.prototype, "numberOfRecommendationsPerPage", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicIpxRecsList.prototype, "label", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        reflect: true,
        attribute: 'heading-level',
        type: Number
    })
], AtomicIpxRecsList.prototype, "headingLevel", void 0);
_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)
], AtomicIpxRecsList.prototype, "render", null);
AtomicIpxRecsList = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-ipx-recs-list'),
    (0, bindings_cjs_namespaceObject.bindings)(),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicIpxRecsList);
exports.AtomicIpxRecsList = __webpack_exports__.AtomicIpxRecsList;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicIpxRecsList"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
