"use strict";
var __webpack_require__ = {};
(()=>{
    __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__, {
    AtomicRefineModal: ()=>AtomicRefineModal
});
const headless_namespaceObject = require("@coveo/headless");
const external_lit_namespaceObject = require("lit");
const decorators_js_namespaceObject = require("lit/decorators.js");
const atomic_layout_section_utils_cjs_namespaceObject = require("../../common/atomic-layout-section/atomic-layout-section-utils.cjs");
const popover_type_cjs_namespaceObject = require("../../common/facets/popover/popover-type.cjs");
const store_cjs_namespaceObject = require("../../common/interface/store.cjs");
const body_cjs_namespaceObject = require("../../common/refine-modal/body.cjs");
const filters_cjs_namespaceObject = require("../../common/refine-modal/filters.cjs");
const modal_cjs_namespaceObject = require("../../common/refine-modal/modal.cjs");
const sort_cjs_namespaceObject = require("../../common/refine-modal/sort.cjs");
const boolean_converter_cjs_namespaceObject = require("../../../converters/boolean-converter.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 watch_cjs_namespaceObject = require("../../../decorators/watch.cjs");
const with_tailwind_styles_cjs_namespaceObject = require("../../../decorators/with-tailwind-styles.cjs");
const tab_utils_cjs_namespaceObject = require("../../../utils/tab-utils.cjs");
const utils_cjs_namespaceObject = require("../../../utils/utils.cjs");
const facet_common_cjs_namespaceObject = require("../../common/facets/facet-common.cjs");
require("../atomic-automatic-facet-generator/atomic-automatic-facet-generator.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 AtomicRefineModal extends external_lit_namespaceObject.LitElement {
    initialize() {
        this.breadcrumbManager = (0, headless_namespaceObject.buildBreadcrumbManager)(this.bindings.engine);
        this.sort = (0, headless_namespaceObject.buildSort)(this.bindings.engine);
        this.querySummary = (0, headless_namespaceObject.buildQuerySummary)(this.bindings.engine);
        this.searchStatus = (0, headless_namespaceObject.buildSearchStatus)(this.bindings.engine);
        this.facetManager = (0, headless_namespaceObject.buildFacetManager)(this.bindings.engine);
        this.tabManager = (0, headless_namespaceObject.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(utils_cjs_namespaceObject.sortByDocumentPosition);
        const facetsSection = [];
        const horizontalFacetsSection = [];
        for (const boundInterface of boundInterfaces){
            const facetSection = (0, atomic_layout_section_utils_cjs_namespaceObject.findSection)(boundInterface, 'facets');
            if (facetSection) facetsSection.push(facetSection);
            const horizontalFacetSection = (0, atomic_layout_section_utils_cjs_namespaceObject.findSection)(boundInterface, 'horizontal-facets');
            if (horizontalFacetSection) horizontalFacetsSection.push(horizontalFacetSection);
        }
        const triagedFacets = (0, facet_common_cjs_namespaceObject.triageFacetsByParents)(facets, ...horizontalFacetsSection, ...facetsSection);
        for (const triagedFacet of triagedFacets.values())triagedFacet.sort(utils_cjs_namespaceObject.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 } = (0, facet_common_cjs_namespaceObject.sortFacetVisibility)(sortedFacets, this.bindings.store.getAllFacets());
        const visibleFacetsClone = this.cloneFacets(visibleFacets);
        const invisibleFacetsClone = this.cloneFacets(invisibleFacets);
        (0, facet_common_cjs_namespaceObject.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(popover_type_cjs_namespaceObject.popoverClass);
            facet.setAttribute(store_cjs_namespaceObject.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 (!(0, tab_utils_cjs_namespaceObject.shouldDisplayOnCurrentTab)([
            ...tabs.included
        ], [
            ...tabs.excluded
        ], this.tabManagerState?.activeTab)) return external_lit_namespaceObject.nothing;
        return (0, external_lit_namespaceObject.html)`
      <option value=${expression} ?selected=${this.sort.isSortedBy(criteria)}>
        ${this.bindings.i18n.t(label)}
      </option>
    `;
    }
    renderSort() {
        if (!this.options.length) return external_lit_namespaceObject.nothing;
        return (0, sort_cjs_namespaceObject.renderRefineModalSortSection)({
            props: {
                i18n: this.bindings.i18n,
                onSelect: this.onSelectSortOption
            }
        })((0, external_lit_namespaceObject.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 external_lit_namespaceObject.nothing;
        const { i18n } = this.bindings;
        return (0, filters_cjs_namespaceObject.renderRefineModalFiltersSection)({
            props: {
                i18n,
                withFacets: hasFacetElements,
                withAutomaticFacets: hasAutomaticFacets
            }
        })(this.breadcrumbManagerState.hasBreadcrumbs ? (0, filters_cjs_namespaceObject.renderRefineModalFiltersClearButton)({
            props: {
                i18n,
                onClick: ()=>this.breadcrumbManager.deselectAll()
            }
        }) : external_lit_namespaceObject.nothing);
    }
    render() {
        return (0, external_lit_namespaceObject.html)`${(0, modal_cjs_namespaceObject.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
            }
        })((0, body_cjs_namespaceObject.renderRefineModalBody)(this.bindings.i18n)((0, external_lit_namespaceObject.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 = [
    (0, external_lit_namespaceObject.css)`
      @reference '../../../utils/tailwind.global.tw.css';

      select:hover + div,
      select:focus-visible + div {
        @apply text-primary-light;
      }
    `
];
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicRefineModal.prototype, "bindings", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicRefineModal.prototype, "error", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        attribute: 'open-button',
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicRefineModal.prototype, "openButton", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Boolean,
        converter: boolean_converter_cjs_namespaceObject.booleanConverter,
        reflect: true,
        attribute: 'is-open'
    })
], AtomicRefineModal.prototype, "isOpen", void 0);
_ts_decorate([
    (0, decorators_js_namespaceObject.property)({
        type: Number,
        reflect: true,
        attribute: 'collapse-facets-after'
    })
], AtomicRefineModal.prototype, "collapseFacetsAfter", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('sort'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof SortState ? Object : SortState)
], AtomicRefineModal.prototype, "sortState", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('breadcrumbManager'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof BreadcrumbManagerState ? Object : BreadcrumbManagerState)
], AtomicRefineModal.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('querySummary'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof QuerySummaryState ? Object : QuerySummaryState)
], AtomicRefineModal.prototype, "querySummaryState", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('facetManager'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof FacetManagerState ? Object : FacetManagerState)
], AtomicRefineModal.prototype, "facetManagerState", void 0);
_ts_decorate([
    (0, bind_state_cjs_namespaceObject.bindStateToController)('tabManager'),
    (0, decorators_js_namespaceObject.state)(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicRefineModal.prototype, "tabManagerState", void 0);
_ts_decorate([
    (0, watch_cjs_namespaceObject.watch)('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicRefineModal.prototype, "watchEnabled", null);
_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)
], AtomicRefineModal.prototype, "render", null);
AtomicRefineModal = _ts_decorate([
    (0, decorators_js_namespaceObject.customElement)('atomic-refine-modal'),
    (0, bindings_cjs_namespaceObject.bindings)(),
    with_tailwind_styles_cjs_namespaceObject.withTailwindStyles
], AtomicRefineModal);
exports.AtomicRefineModal = __webpack_exports__.AtomicRefineModal;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AtomicRefineModal"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
