import { buildProductListing, buildSearch } from "@coveo/headless/commerce";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.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 { 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 { getSortByLabel, renderCommerceSortOption } from "../sort/option.js";
import "../atomic-commerce-facets/atomic-commerce-facets.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 AtomicCommerceRefineModal extends LitElement {
    initialize() {
        const searchOrListing = 'search' === this.bindings.interfaceElement.type ? buildSearch(this.bindings.engine) : buildProductListing(this.bindings.engine);
        this.summary = searchOrListing.summary();
        this.sort = searchOrListing.sort();
        this.facetGenerator = searchOrListing.facetGenerator();
        this.breadcrumbManager = searchOrListing.breadcrumbManager();
        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');
        const facets = document.createElement('atomic-commerce-facets');
        facets.style.display = 'flex';
        facets.style.flexDirection = 'column';
        facets.style.gap = 'var(--atomic-refine-modal-facet-margin, 20px)';
        facets.collapseFacetsAfter = this.collapseFacetsAfter;
        divSlot.append(facets);
        return divSlot;
    }
    renderSort() {
        return renderRefineModalSortSection({
            props: {
                i18n: this.bindings.i18n,
                onSelect: this.onSelectSortOption
            }
        })(html`${this.sortState.availableSorts.map((sort)=>renderCommerceSortOption({
                props: {
                    i18n: this.bindings.i18n,
                    selected: this.sort.isSortedBy(sort),
                    sort
                }
            }))}`);
    }
    renderFilters() {
        if (0 === this.facetGeneratorState.length) return;
        const { i18n } = this.bindings;
        return renderRefineModalFiltersSection({
            props: {
                i18n,
                withFacets: true,
                withAutomaticFacets: false
            }
        })(this.breadcrumbManagerState.hasBreadcrumbs ? renderRefineModalFiltersClearButton({
            props: {
                i18n,
                onClick: ()=>this.breadcrumbManager.deselectAll()
            }
        }) : nothing);
    }
    render() {
        return html`${renderRefineModal({
            props: {
                i18n: this.bindings.i18n,
                i18nFooterButtonTextKey: 'view-products',
                host: this,
                isOpen: this.isOpen,
                onClose: ()=>{
                    this.isOpen = false;
                },
                title: this.bindings.i18n.t('sort-and-filter'),
                numberOfItems: this.summaryState.totalNumberOfProducts,
                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];
            this.sort.sortBy(getSortByLabel(select.value, this.sortState.availableSorts));
        };
    }
}
AtomicCommerceRefineModal.styles = [
    css`:host{position:absolute}`
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceRefineModal.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceRefineModal.prototype, "error", void 0);
_ts_decorate([
    property({
        attribute: 'open-button',
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicCommerceRefineModal.prototype, "openButton", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true,
        attribute: 'is-open'
    })
], AtomicCommerceRefineModal.prototype, "isOpen", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'collapse-facets-after'
    })
], AtomicCommerceRefineModal.prototype, "collapseFacetsAfter", void 0);
_ts_decorate([
    bindStateToController('summary'),
    state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceRefineModal.prototype, "summaryState", void 0);
_ts_decorate([
    bindStateToController('sort'),
    state(),
    _ts_metadata("design:type", "u" < typeof SortState ? Object : SortState)
], AtomicCommerceRefineModal.prototype, "sortState", void 0);
_ts_decorate([
    bindStateToController('facetGenerator'),
    state(),
    _ts_metadata("design:type", "u" < typeof FacetGeneratorState ? Object : FacetGeneratorState)
], AtomicCommerceRefineModal.prototype, "facetGeneratorState", void 0);
_ts_decorate([
    bindStateToController('breadcrumbManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof BreadcrumbManagerState ? Object : BreadcrumbManagerState)
], AtomicCommerceRefineModal.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    watch('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRefineModal.prototype, "watchEnabled", null);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceRefineModal.prototype, "render", null);
AtomicCommerceRefineModal = _ts_decorate([
    customElement('atomic-commerce-refine-modal'),
    bindings(),
    withTailwindStyles
], AtomicCommerceRefineModal);
export { AtomicCommerceRefineModal };
