import { buildBreadcrumbManager, buildQuerySummary } from "@coveo/headless/insight";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { renderButton } from "../../common/button.js";
import { getClonedFacetElements } from "../../common/refine-modal/cloned-facet-elements.js";
import { renderRefineModal } from "../../common/refine-modal/modal.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 { rectEquals } from "../../../utils/dom-utils.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 AtomicInsightRefineModal extends LitElement {
    initialize() {
        this.querySummary = buildQuerySummary(this.bindings.engine);
        this.breadcrumbManager = buildBreadcrumbManager(this.bindings.engine);
    }
    connectedCallback() {
        super.connectedCallback();
        this.style.display = '';
        this.shadowRoot?.adoptedStyleSheets.push(this.backdropStyleSheet);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (this.animationFrameId) window.cancelAnimationFrame(this.animationFrameId);
    }
    willUpdate(changedProperties) {
        if (changedProperties.has('interfaceDimensions')) this.updateBackdropStyles();
    }
    watchEnabled() {
        if (this.isOpen) {
            if (!this.querySelector('div[slot="facets"]')) this.appendChild(getClonedFacetElements(this.bindings.store.getFacetElements(), 0, this.bindings.interfaceElement));
            this.onAnimationFrame();
        }
    }
    onAnimationFrame() {
        if (!this.isOpen) return;
        if (this.dimensionChanged()) this.updateDimensions();
        this.animationFrameId = window.requestAnimationFrame(()=>this.onAnimationFrame());
    }
    dimensionChanged() {
        if (!this.interfaceDimensions) return true;
        return !rectEquals(this.interfaceDimensions, this.bindings.interfaceElement.getBoundingClientRect());
    }
    updateDimensions() {
        this.interfaceDimensions = this.bindings.interfaceElement.getBoundingClientRect();
        this.updateBackdropStyles();
    }
    updateBackdropStyles() {
        if (this.interfaceDimensions) this.backdropStyleSheet.replaceSync(`
        atomic-modal::part(backdrop) {
          top: ${this.interfaceDimensions.top}px;
          left: ${this.interfaceDimensions.left}px;
          width: ${this.interfaceDimensions.width}px;
          height: ${this.interfaceDimensions.height}px;
        }
      `);
        else this.backdropStyleSheet.replaceSync('');
    }
    renderHeader() {
        if (!this.breadcrumbManagerState.hasBreadcrumbs) return nothing;
        return html`
      <div class="mb-3 flex w-full justify-between">
        ${renderButton({
            props: {
                onClick: ()=>this.breadcrumbManager.deselectAll(),
                style: 'text-primary',
                text: this.bindings.i18n.t('clear-all-filters'),
                class: 'px-2 py-1'
            }
        })(nothing)}
      </div>
    `;
    }
    renderBody() {
        if (!this.bindings.store.getFacetElements().length) return nothing;
        return html`
      <aside
        slot="body"
        class="flex w-full flex-col"
        aria-label=${this.bindings.i18n.t('refine-modal-content')}
      >
        ${this.renderHeader()}
        <slot name="facets"></slot>
      </aside>
    `;
    }
    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('filters'),
                numberOfItems: this.querySummaryState.total,
                openButton: this.openButton,
                scope: this.bindings.interfaceElement
            }
        })(this.renderBody())}
    `;
    }
    constructor(...args){
        super(...args), this.isOpen = false, this.backdropStyleSheet = new CSSStyleSheet();
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightRefineModal.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightRefineModal.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('querySummary'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightQuerySummaryState ? Object : InsightQuerySummaryState)
], AtomicInsightRefineModal.prototype, "querySummaryState", void 0);
_ts_decorate([
    bindStateToController('breadcrumbManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBreadcrumbManagerState ? Object : InsightBreadcrumbManagerState)
], AtomicInsightRefineModal.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof DOMRect ? Object : DOMRect)
], AtomicInsightRefineModal.prototype, "interfaceDimensions", void 0);
_ts_decorate([
    property({
        attribute: 'open-button',
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof HTMLElement ? Object : HTMLElement)
], AtomicInsightRefineModal.prototype, "openButton", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        reflect: true,
        attribute: 'is-open'
    })
], AtomicInsightRefineModal.prototype, "isOpen", void 0);
_ts_decorate([
    watch('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightRefineModal.prototype, "watchEnabled", null);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightRefineModal.prototype, "render", null);
AtomicInsightRefineModal = _ts_decorate([
    customElement('atomic-insight-refine-modal'),
    bindings(),
    withTailwindStyles
], AtomicInsightRefineModal);
export { AtomicInsightRefineModal };
