import { ArrayValue, Schema, StringValue } from "@coveo/bueno";
import { buildInteractiveResult, buildResultList, buildResultsPerPage, buildTabManager } from "@coveo/headless";
import { LitElement, 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 { 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 { ResultTemplateProvider } from "../../common/item-list/result-template-provider.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 { renderTabWrapper } from "../../common/tabs/tab-wrapper.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { arrayConverter } from "../../../converters/array-converter.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-result-template/atomic-result-template.js";
import "../atomic-result/atomic-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 AtomicResultList extends ChildrenUpdateCompleteMixin(LitElement) {
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    initialize() {
        if (this.innerHTML.includes('<atomic-result-children')) console.warn('Folded results will not render any children for the "atomic-result-list". Please use "atomic-folded-result-list" instead.');
        this.resultList = buildResultList(this.bindings.engine);
        this.resultsPerPage = buildResultsPerPage(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        this.initResultTemplateProvider();
        this.initResultListCommon();
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    async willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('tabManagerState')) {
            const oldValue = changedProperties.get('tabManagerState');
            if (this.tabManagerState?.activeTab !== oldValue?.activeTab && void 0 !== oldValue) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
        }
        if (changedProperties.has('resultListState')) {
            const oldState = changedProperties.get('resultListState');
            if (this.resultListState.firstSearchExecuted) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
            if (!oldState?.isLoading && this.resultListState.isLoading) this.isEveryResultReady = false;
        }
        await this.updateResultReadyState();
    }
    async updateResultReadyState() {
        if (this.isAppLoaded && !this.isEveryResultReady && this.resultListState?.firstSearchExecuted && this.resultListState?.results?.length > 0) {
            await this.getUpdateComplete();
            this.isEveryResultReady = true;
        }
    }
    render() {
        return html`${renderTabWrapper({
            props: {
                tabsIncluded: this.tabsIncluded,
                tabsExcluded: this.tabsExcluded,
                activeTab: this.tabManagerState?.activeTab
            }
        })(renderItemList({
            props: {
                hasError: this.resultListState.hasError,
                hasItems: this.resultListState.hasResults,
                hasTemplate: this.resultTemplateRegistered,
                firstRequestExecuted: this.resultListState.firstSearchExecuted,
                templateHasError: this.templateHasError
            }
        })(html`${when(this.templateHasError, ()=>html`<slot></slot>`, ()=>{
            const listClasses = this.computeListDisplayClasses();
            const resultClasses = `${listClasses} ${!this.isEveryResultReady && 'hidden'}`;
            return html`
              ${when(this.isAppLoaded, ()=>renderDisplayWrapper({
                    props: {
                        listClasses: resultClasses,
                        display: this.display
                    }
                })(html`${when('grid' === this.display, ()=>this.renderGrid(), ()=>html`${when('table' === this.display, ()=>this.renderTable(), ()=>this.renderList())}`)}`))}
              ${when(!this.isEveryResultReady, ()=>renderDisplayWrapper({
                    props: {
                        listClasses,
                        display: this.display
                    }
                })(renderItemPlaceholders({
                    props: {
                        density: this.density,
                        display: this.display,
                        imageSize: this.imageSize,
                        numberOfPlaceholders: this.resultsPerPageState.numberOfResults || 10
                    }
                })))}
            `;
        })}`))}`;
    }
    initResultTemplateProvider() {
        this.resultTemplateProvider = new ResultTemplateProvider({
            includeDefaultTemplate: true,
            templateElements: Array.from(this.querySelectorAll('atomic-result-template')),
            getResultTemplateRegistered: ()=>this.resultTemplateRegistered,
            getTemplateHasError: ()=>this.templateHasError,
            setResultTemplateRegistered: (value)=>{
                this.resultTemplateRegistered = value;
            },
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            },
            bindings: this.bindings
        });
    }
    initResultListCommon() {
        this.resultListCommon = new ItemListCommon({
            engineSubscribe: this.bindings.engine.subscribe,
            getCurrentNumberOfItems: ()=>this.resultListState.results.length,
            getIsLoading: ()=>this.resultListState.isLoading,
            host: this,
            loadingFlag: this.loadingFlag,
            nextNewItemTarget: this.focusTarget,
            store: this.bindings.store
        });
    }
    computeListDisplayClasses() {
        const displayPlaceholders = !(this.isAppLoaded && this.isEveryResultReady);
        return getItemListDisplayClasses(this.display, this.density, this.imageSize, this.resultListState?.isLoading, displayPlaceholders);
    }
    renderGrid() {
        return html`${map(this.resultListState.results, (result, index)=>renderGridLayout({
                props: {
                    item: {
                        ...result,
                        title: result.title ?? ''
                    },
                    selectorForItem: 'atomic-result',
                    setRef: (element)=>{
                        element instanceof HTMLElement && this.resultListCommon.setNewResultRef(element, index);
                    }
                }
            })(html`${keyed(this.getResultId(result), html`<atomic-result
            .content=${this.getContent(result)}
            .density=${this.density}
            .display=${this.display}
            .imageSize=${this.imageSize}
            .interactiveResult=${this.getInteractiveResult(result)}
            .linkContent=${this.getLinkContent(result)}
            .loadingFlag=${this.loadingFlag}
            .result=${result}
            .renderingFunction=${this.itemRenderingFunction}
            .store=${this.bindings.store}
          ></atomic-result>`)}`))}`;
    }
    renderList() {
        return html`${map(this.resultListState.results, (result, index)=>html`${keyed(this.getResultId(result), html`<atomic-result
          part="outline"
          ${ref((element)=>element instanceof HTMLElement && this.resultListCommon.setNewResultRef(element, index))}
          .content=${this.getContent(result)}
          .density=${this.density}
          .display=${this.display}
          .imageSize=${this.imageSize}
          .interactiveResult=${this.getInteractiveResult(result)}
          .linkContent=${this.getLinkContent(result)}
          .loadingFlag=${this.loadingFlag}
          .result=${result}
          .renderingFunction=${this.itemRenderingFunction}
          .store=${this.bindings.store}
        ></atomic-result>`)}`)}`;
    }
    renderTable() {
        return html`${when(this.resultListState.hasResults, ()=>{
            const firstItem = this.resultListState.results[0];
            const listClasses = this.computeListDisplayClasses();
            const templateContentForFirstItem = this.resultTemplateProvider.getTemplateContent(firstItem);
            return renderTableLayout({
                props: {
                    firstItem,
                    host: this,
                    itemRenderingFunction: this.itemRenderingFunction,
                    label: this.bindings.i18n.t('view-results'),
                    listClasses,
                    logger: this.bindings.engine.logger,
                    templateContentForFirstItem
                }
            })(html`${map(this.resultListState.results, (result, index)=>renderTableRow({
                    props: {
                        key: this.getResultId(result),
                        rowIndex: index,
                        setRef: (element)=>{
                            element instanceof HTMLElement && this.resultListCommon.setNewResultRef(element, index);
                        }
                    }
                })(renderTableData({
                    props: {
                        firstItem,
                        templateContentForFirstItem,
                        itemRenderingFunction: this.itemRenderingFunction,
                        key: this.getResultId(result),
                        renderItem: (content)=>html`<atomic-result
                      .content=${content}
                      .density=${this.density}
                      .display=${this.display}
                      .imageSize=${this.imageSize}
                      .interactiveResult=${this.getInteractiveResult(result)}
                      .linkContent=${this.getLinkContent(result)}
                      .loadingFlag=${this.loadingFlag}
                      .result=${result}
                      .renderingFunction=${this.itemRenderingFunction}
                      .store=${this.bindings.store}
                    ></atomic-result>`
                    }
                })))}`);
        }, ()=>nothing)}`;
    }
    get focusTarget() {
        if (!this.nextNewResultTarget) this.nextNewResultTarget = new FocusTargetController(this, this.bindings);
        return this.nextNewResultTarget;
    }
    getLinkContent(result) {
        return 'grid' === this.display ? this.resultTemplateProvider.getLinkTemplateContent(result) : this.resultTemplateProvider.getEmptyLinkTemplateContent();
    }
    getContent(result) {
        return this.resultTemplateProvider.getTemplateContent(result);
    }
    getInteractiveResult(result) {
        return buildInteractiveResult(this.bindings.engine, {
            options: {
                result
            }
        });
    }
    getResultId(result) {
        return this.resultListCommon.getResultId(result.uniqueId, this.resultListState.searchResponseId, this.density, this.imageSize);
    }
    constructor(){
        super(), this.loadingFlag = randomID('firstResultLoaded-'), this.isAppLoaded = false, this.isEveryResultReady = false, this.resultTemplateRegistered = false, this.templateHasError = false, this.density = 'normal', this.display = 'list', this.imageSize = 'icon', this.tabsIncluded = [], this.tabsExcluded = [];
        new ValidatePropsController(this, ()=>({
                density: this.density,
                display: this.display,
                imageSize: this.imageSize,
                tabsIncluded: this.tabsIncluded,
                tabsExcluded: this.tabsExcluded
            }), AtomicResultList.propsSchema, false);
    }
}
AtomicResultList.styles = [
    placeholders_tw_css,
    table_display_tw_css,
    list_display_tw_css,
    grid_display_tw_css
];
AtomicResultList.propsSchema = new Schema({
    density: new StringValue({
        constrainTo: [
            'normal',
            'comfortable',
            'compact'
        ]
    }),
    display: new StringValue({
        constrainTo: [
            'grid',
            'list',
            'table'
        ]
    }),
    imageSize: new StringValue({
        constrainTo: [
            'small',
            'large',
            'icon',
            'none'
        ]
    }),
    tabsIncluded: new ArrayValue({
        each: new StringValue({}),
        required: false
    }),
    tabsExcluded: new ArrayValue({
        each: new StringValue({}),
        required: false
    })
});
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicResultList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicResultList.prototype, "isEveryResultReady", void 0);
_ts_decorate([
    state()
], AtomicResultList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicResultList.prototype, "templateHasError", void 0);
_ts_decorate([
    bindStateToController('resultList'),
    state(),
    _ts_metadata("design:type", "u" < typeof ResultListState ? Object : ResultListState)
], AtomicResultList.prototype, "resultListState", void 0);
_ts_decorate([
    bindStateToController('resultsPerPage'),
    state(),
    _ts_metadata("design:type", "u" < typeof ResultsPerPageState ? Object : ResultsPerPageState)
], AtomicResultList.prototype, "resultsPerPageState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicResultList.prototype, "tabManagerState", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicResultList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayLayout ? Object : ItemDisplayLayout)
], AtomicResultList.prototype, "display", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicResultList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        attribute: 'tabs-included',
        converter: arrayConverter,
        type: Array
    }),
    _ts_metadata("design:type", Array)
], AtomicResultList.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        attribute: 'tabs-excluded',
        converter: arrayConverter,
        type: Array
    }),
    _ts_metadata("design:type", Array)
], AtomicResultList.prototype, "tabsExcluded", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultList.prototype, "render", null);
AtomicResultList = _ts_decorate([
    customElement('atomic-result-list'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultList);
export { AtomicResultList };
