import { buildInteractiveResult } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { map } from "lit/directives/map.js";
import { when } from "lit/directives/when.js";
import { ChildTemplatesContextController } from "../../common/item-list/context/child-templates-context-controller.js";
import { FoldedItemListContextController } from "../../common/item-list/context/folded-item-list-context-controller.js";
import { ItemDisplayConfigContextController } from "../../common/item-list/context/item-display-config-context-controller.js";
import { ResultTemplateProvider } from "../../common/item-list/result-template-provider.js";
import { extractUnfoldedItem } from "../../common/item-list/unfolded-item.js";
import { renderChildrenWrapper } from "../../common/result-children/children-wrapper.js";
import { renderCollectionGuard } from "../../common/result-children/collection-guard.js";
import { renderResultChildrenGuard } from "../../common/result-children/guard.js";
import { renderShowHideButton } from "../../common/result-children/show-hide-button.js";
import { createResultContextController } from "../result-template-component-utils/context/result-context-controller.js";
import { bindings } from "../../../decorators/bindings.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { buildCustomEvent } from "../../../utils/event-utils.js";
import { elementHasAncestorTag } from "../../../utils/utils.js";
import "../atomic-result/atomic-result.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { errorGuard } from "../../../decorators/error-guard.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);
}
const childTemplateComponent = 'atomic-result-children-template';
const componentTag = 'atomic-result-children';
class AtomicResultChildren extends LitElement {
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('atomic/resolveChildTemplates', this.resolveChildTemplates);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/resolveChildTemplates', this.resolveChildTemplates);
        this.foldedResultListUnsubscriber?.();
    }
    initialize() {
        if (this.inheritTemplates) return;
        const childrenTemplates = Array.from(this.querySelectorAll(childTemplateComponent)).filter((template)=>!elementHasAncestorTag(template, childTemplateComponent));
        if (!childrenTemplates.length) {
            this.error = new Error(`The "${componentTag}" component requires at least one "${childTemplateComponent}" component.`);
            return;
        }
        this.itemTemplateProvider = new ResultTemplateProvider({
            includeDefaultTemplate: false,
            templateElements: childrenTemplates,
            getResultTemplateRegistered: ()=>this.resultTemplateRegistered,
            getTemplateHasError: ()=>this.templateHasError,
            setResultTemplateRegistered: (value)=>{
                this.resultTemplateRegistered = value;
            },
            setTemplateHasError: (value)=>{
                this.templateHasError = value;
            },
            bindings: this.bindings
        });
    }
    get foldedResultList() {
        return this.foldedItemListContextController.foldedItemList;
    }
    get result() {
        return this.resultContextController.item;
    }
    get displayConfig() {
        return this.displayConfigContextController.config;
    }
    get effectiveItemTemplateProvider() {
        return this.itemTemplateProvider || this.childTemplatesContextController.itemTemplateProvider;
    }
    get collection() {
        if (!this.foldedResultListState || !this.result) return;
        return this.foldedResultListState.results.find((r)=>r.result.uniqueId === this.result?.result.uniqueId);
    }
    willUpdate() {
        if (this.foldedResultList && !this.foldedResultListUnsubscriber) {
            this.foldedResultListUnsubscriber = this.foldedResultList.subscribe(()=>{
                this.foldedResultListState = this.foldedResultList.state;
                if (!this.initialChildren && this.collection) this.initialChildren = this.collection.children;
            });
            this.foldedResultListState = this.foldedResultList.state;
        }
        if (!this.initialChildren && this.collection) this.initialChildren = this.collection.children;
    }
    loadFullCollection() {
        this.loadedFullCollection = true;
        this.dispatchEvent(buildCustomEvent('atomic/loadCollection', this.collection));
    }
    renderChild(child, isLast) {
        const content = this.effectiveItemTemplateProvider?.getTemplateContent(child.result);
        if (!content) return nothing;
        const key = child.result.uniqueId + child.children.map((c)=>c.result.uniqueId).join(',');
        return html`<atomic-result
      .key=${key}
      .content=${content}
      .result=${child}
      .interactiveResult=${buildInteractiveResult(this.bindings.engine, {
            options: {
                result: extractUnfoldedItem(child)
            }
        })}
      .store=${this.bindings.store}
      density=${this.displayConfig?.density ?? 'normal'}
      image-size=${this.imageSize || this.displayConfig?.imageSize || 'icon'}
      classes=${`child-result ${isLast ? 'last-child' : ''}`.trim()}
    ></atomic-result>`;
    }
    renderChildren(children) {
        if (0 === children.length) return nothing;
        return renderChildrenWrapper()(html`${map(children, (child, i)=>this.renderChild(child, i === children.length - 1))}`);
    }
    renderCollection() {
        const collection = this.collection;
        const children = this.showInitialChildren ? this.initialChildren : collection.children;
        const showShouldButtons = this.loadedFullCollection || collection.moreResultsAvailable;
        const showHideButton = showShouldButtons ? renderShowHideButton({
            props: {
                moreResultsAvailable: collection.moreResultsAvailable,
                loadFullCollection: ()=>this.loadFullCollection(),
                showInitialChildren: this.showInitialChildren,
                toggleShowInitialChildren: this.toggleShowInitialChildren,
                loadAllResults: this.bindings.i18n.t('load-all-results'),
                collapseResults: this.bindings.i18n.t('collapse-results')
            }
        }) : nothing;
        const guard = renderCollectionGuard({
            props: {
                isLoadingMoreResults: collection.isLoadingMoreResults,
                moreResultsAvailable: collection.moreResultsAvailable,
                numberOfChildren: collection.children.length,
                density: this.displayConfig?.density ?? 'normal',
                imageSize: this.imageSize || this.displayConfig?.imageSize || 'icon',
                noResultText: this.bindings.i18n.t(this.noResultText)
            }
        });
        return html`${showHideButton}${guard(this.renderChildren(children))}`;
    }
    renderFoldedResult() {
        if (!this.result || 0 === this.result.children.length) return nothing;
        return this.renderChildren(this.result.children);
    }
    render() {
        return html`${when(this.bindings && (this.displayConfig || this.inheritTemplates), ()=>renderResultChildrenGuard({
                props: {
                    inheritTemplates: this.inheritTemplates,
                    resultTemplateRegistered: this.resultTemplateRegistered,
                    templateHasError: this.templateHasError
                }
            })(this.collection ? this.renderCollection() : this.renderFoldedResult()))}`;
    }
    constructor(){
        super(), this.inheritTemplates = false, this.noResultText = 'no-documents-related', this.resultTemplateRegistered = false, this.templateHasError = false, this.showInitialChildren = true, this.loadedFullCollection = false, this.resolveChildTemplates = (event)=>{
            event.preventDefault();
            const provider = this.itemTemplateProvider || this.childTemplatesContextController.itemTemplateProvider;
            event.detail(provider ?? void 0);
        }, this.toggleShowInitialChildren = ()=>{
            if (!this.foldedResultList || !this.result) return;
            if (this.showInitialChildren) this.foldedResultList.logShowMoreFoldedResults(this.result.result);
            else this.foldedResultList.logShowLessFoldedResults();
            this.showInitialChildren = !this.showInitialChildren;
        };
        this.foldedItemListContextController = new FoldedItemListContextController(this);
        this.childTemplatesContextController = new ChildTemplatesContextController(this);
        this.displayConfigContextController = new ItemDisplayConfigContextController(this);
        this.resultContextController = createResultContextController(this, {
            folded: true
        });
    }
}
AtomicResultChildren.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */.show-hide-button{--font-size:var(--atomic-text-sm);font-size:var(--font-size);--line-height:calc(var(--font-size)*var(--atomic-line-height-ratio));line-height:var(--line-height)}.no-result-root{color:var(--atomic-neutral-dark)}`;
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'inherit-templates'
    })
], AtomicResultChildren.prototype, "inheritTemplates", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'image-size'
    }),
    _ts_metadata("design:type", "u" < typeof ItemDisplayImageSize ? Object : ItemDisplayImageSize)
], AtomicResultChildren.prototype, "imageSize", void 0);
_ts_decorate([
    property({
        attribute: 'no-result-text'
    })
], AtomicResultChildren.prototype, "noResultText", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultChildren.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultChildren.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicResultChildren.prototype, "resultTemplateRegistered", void 0);
_ts_decorate([
    state()
], AtomicResultChildren.prototype, "templateHasError", void 0);
_ts_decorate([
    state()
], AtomicResultChildren.prototype, "showInitialChildren", void 0);
_ts_decorate([
    state()
], AtomicResultChildren.prototype, "loadedFullCollection", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof FoldedResultListState ? Object : FoldedResultListState)
], AtomicResultChildren.prototype, "foldedResultListState", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultChildren.prototype, "render", null);
AtomicResultChildren = _ts_decorate([
    customElement('atomic-result-children'),
    withTailwindStyles,
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultChildren);
export { AtomicResultChildren };
