import { buildBreadcrumbManager, buildFacetManager, buildQuerySummary, buildSearchStatus, buildSort, buildTabManager } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { findSection } from "../../common/atomic-layout-section/atomic-layout-section-utils.js";
import { popoverClass } from "../../common/facets/popover/popover-type.js";
import { isRefineModalFacet } from "../../common/interface/store.js";
import { renderRefineModalBody } from "../../common/refine-modal/body.js";
import { renderRefineModalFiltersClearButton, renderRefineModalFiltersSection } from "../../common/refine-modal/filters.js";
import { renderRefineModal } from "../../common/refine-modal/modal.js";
import { renderRefineModalSortSection } from "../../common/refine-modal/sort.js";
import { booleanConverter } from "../../../converters/boolean-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 { watch } from "../../../decorators/watch.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { shouldDisplayOnCurrentTab } from "../../../utils/tab-utils.js";
import { sortByDocumentPosition } from "../../../utils/utils.js";
import { collapseFacetsAfter, sortFacetVisibility, triageFacetsByParents } from "../../common/facets/facet-common.js";
import "../atomic-automatic-facet-generator/atomic-automatic-facet-generator.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 AtomicRefineModal extends LitElement {
    initialize() {
        this.breadcrumbManager = buildBreadcrumbManager(this.bindings.engine);
        this.sort = buildSort(this.bindings.engine);
        this.querySummary = buildQuerySummary(this.bindings.engine);
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.facetManager = buildFacetManager(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        this.watchEnabled();
    }
    watchEnabled() {
        if (this.isOpen) {
            if (this.querySelector('div[slot="facets"]')) return;
            this.appendChild(this.createFacetSlot());
        }
    }
    createFacetSlot() {
        const divSlot = document.createElement('div');
        divSlot.setAttribute('slot', 'facets');
        this.addFacetColumnStyling(divSlot);
        const facets = this.bindings.store.getFacetElements();
        const boundInterfaces = this.getBoundInterfaces().sort(sortByDocumentPosition);
        const facetsSection = [];
        const horizontalFacetsSection = [];
        for (const boundInterface of boundInterfaces){
            const facetSection = findSection(boundInterface, 'facets');
            if (facetSection) facetsSection.push(facetSection);
            const horizontalFacetSection = findSection(boundInterface, 'horizontal-facets');
            if (horizontalFacetSection) horizontalFacetsSection.push(horizontalFacetSection);
        }
        const triagedFacets = triageFacetsByParents(facets, ...horizontalFacetsSection, ...facetsSection);
        for (const triagedFacet of triagedFacets.values())triagedFacet.sort(sortByDocumentPosition);
        const sortedFacets = [];
        for(let i = 0; i < boundInterfaces.length; i++){
            sortedFacets.push(...triagedFacets.get(facetsSection[i]) || []);
            sortedFacets.push(...triagedFacets.get(horizontalFacetsSection[i]) || []);
        }
        sortedFacets.push(...triagedFacets.get(null) || []);
        const { visibleFacets, invisibleFacets } = sortFacetVisibility(sortedFacets, this.bindings.store.getAllFacets());
        const visibleFacetsClone = this.cloneFacets(visibleFacets);
        const invisibleFacetsClone = this.cloneFacets(invisibleFacets);
        collapseFacetsAfter(visibleFacetsClone, this.collapseFacetsAfter);
        divSlot.append(...visibleFacetsClone);
        divSlot.append(...invisibleFacetsClone);
        const generator = this.makeAutomaticFacetGenerator();
        if (generator) {
            generator.updateCollapseFacetsDependingOnFacetsVisibility(this.collapseFacetsAfter, visibleFacets.length);
            divSlot.append(generator);
        }
        return divSlot;
    }
    getBoundInterfaces() {
        const mainInterface = this.closest('atomic-search-interface') ?? this.closest('atomic-external')?.boundInterface ?? null;
        if (!mainInterface) throw new Error('Cannot find bound interface');
        const boundExternalInterfaces = Array.from(document.querySelectorAll('atomic-external')).filter((atomicExternal)=>atomicExternal.boundInterface === mainInterface);
        return [
            ...boundExternalInterfaces,
            mainInterface
        ];
    }
    cloneFacets(facets) {
        return facets.map((facet, i)=>{
            facet.classList.remove(popoverClass);
            facet.setAttribute(isRefineModalFacet, '');
            const clone = facet.cloneNode(true);
            clone.isCollapsed = -1 === this.collapseFacetsAfter ? false : i + 1 > this.collapseFacetsAfter;
            return clone;
        });
    }
    makeAutomaticFacetGenerator() {
        if (!this.bindings.engine.state.automaticFacetSet?.desiredCount) return;
        const generator = document.createElement('atomic-automatic-facet-generator');
        generator.setAttribute('desired-count', `${this.bindings.engine.state.automaticFacetSet?.desiredCount}`);
        this.addFacetColumnStyling(generator);
        return generator;
    }
    addFacetColumnStyling(el) {
        el.style.display = 'flex';
        el.style.flexDirection = 'column';
        el.style.gap = 'var(--atomic-refine-modal-facet-margin, 20px)';
    }
    get options() {
        return this.bindings.store.state.sortOptions;
    }
    renderSortOption({ expression, criteria, label, tabs }) {
        if (!shouldDisplayOnCurrentTab([
            ...tabs.included
        ], [
            ...tabs.excluded
        ], this.tabManagerState?.activeTab)) return nothing;
        return html`
      <option value=${expression} ?selected=${this.sort.isSortedBy(criteria)}>
        ${this.bindings.i18n.t(label)}
      </option>
    `;
    }
    renderSort() {
        if (!this.options.length) return nothing;
        return renderRefineModalSortSection({
            props: {
                i18n: this.bindings.i18n,
                onSelect: this.onSelectSortOption
            }
        })(html`${this.options.map((option)=>this.renderSortOption(option))}`);
    }
    renderFilters() {
        const hasFacetElements = this.bindings.store.getFacetElements().length > 0;
        const hasAutomaticFacets = this.bindings.engine.state.automaticFacetSet?.set !== void 0;
        if (!hasFacetElements && !hasAutomaticFacets) return nothing;
        const { i18n } = this.bindings;
        return renderRefineModalFiltersSection({
            props: {
                i18n,
                withFacets: hasFacetElements,
                withAutomaticFacets: hasAutomaticFacets
            }
        })(this.breadcrumbManagerState.hasBreadcrumbs ? renderRefineModalFiltersClearButton({
            props: {
                i18n,
                onClick: ()=>this.breadcrumbManager.deselectAll()
            }
        }) : nothing);
    }
    render() {
        return html`${renderRefineModal({
            props: {
                i18n: this.bindings.i18n,
                i18nFooterButtonTextKey: 'view-results',
                host: this,
                isOpen: this.isOpen,
                onClose: ()=>{
                    this.isOpen = false;
                },
                title: this.bindings.i18n.t('sort-and-filter'),
                numberOfItems: this.querySummaryState.total,
                openButton: this.openButton
            }
        })(renderRefineModalBody(this.bindings.i18n)(html`
        ${this.renderSort()} ${this.renderFilters()}
      `))}`;
    }
    constructor(...args){
        super(...args), this.isOpen = false, this.collapseFacetsAfter = 0, this.onSelectSortOption = (e)=>{
            const select = e.composedPath()[0];
            const option = this.options.find((option)=>option.expression === select.value);
            option && this.sort.sortBy(option.criteria);
        };
    }
}
AtomicRefineModal.styles = [
    css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */select:focus-visible+div,select:hover+div{color:var(--atomic-primary-light)}`
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicRefineModal.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicRefineModal.prototype, "error", void 0);
_ts_decorate([
    property({
        attribute: 'open-button',
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicRefineModal.prototype, "openButton", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true,
        attribute: 'is-open'
    })
], AtomicRefineModal.prototype, "isOpen", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'collapse-facets-after'
    })
], AtomicRefineModal.prototype, "collapseFacetsAfter", void 0);
_ts_decorate([
    bindStateToController('sort'),
    state(),
    _ts_metadata("design:type", "u" < typeof SortState ? Object : SortState)
], AtomicRefineModal.prototype, "sortState", void 0);
_ts_decorate([
    bindStateToController('breadcrumbManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof BreadcrumbManagerState ? Object : BreadcrumbManagerState)
], AtomicRefineModal.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    bindStateToController('querySummary'),
    state(),
    _ts_metadata("design:type", "u" < typeof QuerySummaryState ? Object : QuerySummaryState)
], AtomicRefineModal.prototype, "querySummaryState", void 0);
_ts_decorate([
    bindStateToController('facetManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof FacetManagerState ? Object : FacetManagerState)
], AtomicRefineModal.prototype, "facetManagerState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicRefineModal.prototype, "tabManagerState", void 0);
_ts_decorate([
    watch('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRefineModal.prototype, "watchEnabled", null);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRefineModal.prototype, "render", null);
AtomicRefineModal = _ts_decorate([
    customElement('atomic-refine-modal'),
    bindings(),
    withTailwindStyles
], AtomicRefineModal);
export { AtomicRefineModal };
