import { ArrayValue, NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildFoldedResultList, buildInteractiveResult, buildResultsPerPage, buildTabManager } from "@coveo/headless";
import { LitElement, html } 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 { 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 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 { extractUnfoldedItem } from "../../common/item-list/unfolded-item.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/atomic-result.js";
import "../atomic-result-template/atomic-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 AtomicFoldedResultList extends ChildrenUpdateCompleteMixin(LitElement) {
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/resolveFoldedResultList', this.handleResolveFoldedResultList);
        this.removeEventListener('atomic/loadCollection', this.handleLoadCollection);
    }
    initialize() {
        this.foldedResultList = this.initFolding();
        this.resultsPerPage = buildResultsPerPage(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        this.initResultTemplateProvider();
        this.initResultListCommon();
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
        this.addEventListener('atomic/resolveFoldedResultList', this.handleResolveFoldedResultList);
        this.addEventListener('atomic/loadCollection', this.handleLoadCollection);
    }
    async setRenderFunction(resultRenderingFunction) {
        this.itemRenderingFunction = resultRenderingFunction;
    }
    willUpdate(changedProperties) {
        if (changedProperties.has('tabManagerState')) {
            const oldState = changedProperties.get('tabManagerState');
            if (this.tabManagerState?.activeTab !== oldState?.activeTab) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
        }
        if (changedProperties.has('foldedResultListState')) {
            const oldState = changedProperties.get('foldedResultListState');
            if (this.foldedResultListState.firstSearchExecuted) this.bindings.store.unsetLoadingFlag(this.loadingFlag);
            if (!oldState?.isLoading && this.foldedResultListState.isLoading) this.isEveryResultReady = false;
        }
        this.updateResultReadyState();
    }
    async updateResultReadyState() {
        if (this.isAppLoaded && !this.isEveryResultReady && this.foldedResultListState?.firstSearchExecuted && this.foldedResultListState?.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.foldedResultListState.hasError,
                hasItems: this.foldedResultListState.hasResults,
                hasTemplate: this.resultTemplateRegistered,
                firstRequestExecuted: this.foldedResultListState.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`${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
                    }
                })))}
            `;
        })}`))}`;
    }
    initFolding(props = {
        options: {}
    }) {
        return buildFoldedResultList(this.bindings.engine, {
            options: {
                ...props.options,
                folding: {
                    collectionField: this.collectionField,
                    parentField: this.parentField,
                    childField: this.childField,
                    numberOfFoldedResults: this.numberOfFoldedResults
                }
            }
        });
    }
    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.foldedResultListState.results.length,
            getIsLoading: ()=>this.foldedResultListState.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.foldedResultListState?.isLoading, displayPlaceholders);
    }
    renderList() {
        return html`${map(this.foldedResultListState.results, (collection, index)=>html`${keyed(this.getResultId(collection), html`<atomic-result
            part="outline"
            ${ref((element)=>element instanceof HTMLElement && this.resultListCommon.setNewResultRef(element, index))}
            .content=${this.getContent(collection)}
            .density=${this.density}
            .display=${this.display}
            .imageSize=${this.imageSize}
            .interactiveResult=${this.getInteractiveResult(collection)}
            .loadingFlag=${this.loadingFlag}
            .result=${collection}
            .renderingFunction=${this.itemRenderingFunction}
            .store=${this.bindings.store}
          ></atomic-result>`)}`)}`;
    }
    get focusTarget() {
        if (!this.nextNewResultTarget) this.nextNewResultTarget = new FocusTargetController(this, this.bindings);
        return this.nextNewResultTarget;
    }
    getContent(collection) {
        const result = extractUnfoldedItem(collection);
        return this.resultTemplateProvider.getTemplateContent(result);
    }
    getInteractiveResult(collection) {
        const result = extractUnfoldedItem(collection);
        return buildInteractiveResult(this.bindings.engine, {
            options: {
                result
            }
        });
    }
    getResultId(collection) {
        const result = extractUnfoldedItem(collection);
        return this.resultListCommon.getResultId(result.uniqueId, this.foldedResultListState.searchResponseId, this.density, this.imageSize);
    }
    constructor(){
        super(), this.loadingFlag = randomID('firstResultLoaded-'), this.display = 'list', this.density = 'normal', this.imageSize = 'icon', this.tabsIncluded = [], this.tabsExcluded = [], this.numberOfFoldedResults = 2, this.isAppLoaded = false, this.isEveryResultReady = false, this.resultTemplateRegistered = false, this.templateHasError = false, this.handleResolveFoldedResultList = (event)=>{
            event.preventDefault();
            event.stopPropagation();
            event.detail(this.foldedResultList);
        }, this.handleLoadCollection = (event)=>{
            event.preventDefault();
            event.stopPropagation();
            this.foldedResultList.loadCollection(event.detail);
        };
        new ValidatePropsController(this, ()=>({
                density: this.density,
                imageSize: this.imageSize,
                tabsIncluded: this.tabsIncluded,
                tabsExcluded: this.tabsExcluded,
                numberOfFoldedResults: this.numberOfFoldedResults
            }), AtomicFoldedResultList.propsSchema);
    }
}
AtomicFoldedResultList.styles = [
    placeholders_tw_css,
    list_display_tw_css
];
AtomicFoldedResultList.propsSchema = new Schema({
    density: new StringValue({
        constrainTo: [
            'normal',
            'comfortable',
            'compact'
        ]
    }),
    imageSize: new StringValue({
        constrainTo: [
            'small',
            'large',
            'icon',
            'none'
        ]
    }),
    tabsIncluded: new ArrayValue({
        each: new StringValue({})
    }),
    tabsExcluded: new ArrayValue({
        each: new StringValue({})
    }),
    numberOfFoldedResults: new NumberValue({
        min: 0
    })
});
_ts_decorate([
    property({
        reflect: true,
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayDensity ? Object : ItemDisplayDensity)
], AtomicFoldedResultList.prototype, "density", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size',
        type: String
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicFoldedResultList.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        attribute: 'tabs-included',
        converter: arrayConverter,
        type: Array
    }),
    _ts_metadata("design:type", Array)
], AtomicFoldedResultList.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        attribute: 'tabs-excluded',
        converter: arrayConverter,
        type: Array
    }),
    _ts_metadata("design:type", Array)
], AtomicFoldedResultList.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'collection-field',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicFoldedResultList.prototype, "collectionField", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'parent-field',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicFoldedResultList.prototype, "parentField", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'child-field',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicFoldedResultList.prototype, "childField", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-folded-results',
        type: Number
    })
], AtomicFoldedResultList.prototype, "numberOfFoldedResults", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicFoldedResultList.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicFoldedResultList.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicFoldedResultList.prototype, "isAppLoaded", void 0);
_ts_decorate([
    state()
], AtomicFoldedResultList.prototype, "isEveryResultReady", void 0);
_ts_decorate([
    state()
], AtomicFoldedResultList.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicFoldedResultList.prototype, "templateHasError", void 0);
_ts_decorate([
    bindStateToController('foldedResultList'),
    state(),
    _ts_metadata("design:type", "u" < typeof FoldedResultListState ? Object : FoldedResultListState)
], AtomicFoldedResultList.prototype, "foldedResultListState", void 0);
_ts_decorate([
    bindStateToController('resultsPerPage'),
    state(),
    _ts_metadata("design:type", "u" < typeof ResultsPerPageState ? Object : ResultsPerPageState)
], AtomicFoldedResultList.prototype, "resultsPerPageState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicFoldedResultList.prototype, "tabManagerState", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicFoldedResultList.prototype, "render", null);
AtomicFoldedResultList = _ts_decorate([
    customElement('atomic-folded-result-list'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicFoldedResultList);
export { AtomicFoldedResultList };
