import { buildContext } from "@coveo/headless/commerce";
import { LitElement, html } from "lit";
import { customElement, property, state as decorators_js_state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { renderNumericFacetValuesGroup } from "../../common/facets/numeric-facet/values-container.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { FocusTargetController } from "../../../utils/accessibility-utils.js";
import { shouldDisplayInputForFacetRange } from "../../common/facets/facet-common.js";
import { renderFacetContainer } from "../../common/facets/facet-container/facet-container.js";
import { renderFacetHeader } from "../../common/facets/facet-header/facet-header.js";
import { renderNumericFacetValue } from "../../common/facets/numeric-facet/value-link.js";
import { defaultCurrencyFormatter, defaultNumberFormatter } from "../../common/formats/format-common.js";
import "../atomic-commerce-facet-number-input/atomic-commerce-facet-number-input.js";
import { bindings } from "../../../decorators/bindings.js";
import numeric_facet_common_tw_css from "../../common/facets/numeric-facet-common.tw.css.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 AtomicCommerceNumericFacet extends LitElement {
    initialize() {
        this.validateFacet();
        this.context = buildContext(this.bindings.engine);
        this.ensureSubscribed();
    }
    disconnectedCallback() {
        this.unsubscribeFacetController?.();
        this.unsubscribeFacetController = void 0;
        super.disconnectedCallback();
    }
    updated(changedProps) {
        super.updated(changedProps);
        if (changedProps.has('facet')) this.validateFacet();
    }
    get formatter() {
        if ('ec_price' === this.field || 'ec_promo_price' === this.field) return defaultCurrencyFormatter(this.contextState.currency);
        return defaultNumberFormatter;
    }
    get focusTarget() {
        if (!this.headerFocus) this.headerFocus = new FocusTargetController(this, this.bindings);
        return this.headerFocus;
    }
    get displayName() {
        return this.facetState.displayName || 'no-label';
    }
    get numberOfSelectedValues() {
        return this.facetState.values.filter(({ state })=>'selected' === state).length || 0;
    }
    get hasInputRange() {
        return !!this.facetState.manualRange;
    }
    get shouldRenderValues() {
        return !this.hasInputRange && !!this.valuesToRender.length;
    }
    get valuesToRender() {
        return this.facetState.values.filter((value)=>value.numberOfResults || 'idle' !== value.state) || [];
    }
    get shouldRenderInput() {
        const { firstRequestExecuted: firstSearchExecuted, hasError, isLoading, hasProducts: hasResults } = this.summaryState;
        return shouldDisplayInputForFacetRange({
            hasInputRange: this.hasInputRange,
            searchStatusState: {
                firstSearchExecuted,
                hasError,
                hasResults,
                isLoading
            },
            facetValues: this.facetState.values,
            hasInput: true
        });
    }
    get shouldRenderFacet() {
        return this.shouldRenderInput || this.shouldRenderValues;
    }
    ensureSubscribed() {
        if (this.unsubscribeFacetController) return;
        this.unsubscribeFacetController = this.facet?.subscribe(()=>{
            this.facetState = this.facet.state;
        });
    }
    renderValues() {
        return renderNumericFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName
            }
        })(html`${this.valuesToRender.map((value)=>renderNumericFacetValue({
                props: {
                    formatter: this.formatter,
                    displayValuesAs: 'checkbox',
                    facetValue: value,
                    field: this.facetState.field,
                    i18n: this.bindings.i18n,
                    logger: this.bindings.engine.logger,
                    manualRanges: [],
                    onClick: ()=>this.facet.toggleSelect(value)
                }
            }))} `);
    }
    onNumberInputApply(event) {
        const { detail: { start, end } } = event;
        this.facet.setRanges([
            {
                start,
                end,
                endInclusive: true,
                state: 'selected'
            }
        ]);
    }
    render() {
        const { firstRequestExecuted } = this.summaryState;
        return html`${when(!firstRequestExecuted || this.shouldRenderFacet, ()=>renderFacetContainer()(html`${renderFacetHeader({
                props: {
                    i18n: this.bindings.i18n,
                    label: this.displayName,
                    numberOfActiveValues: this.numberOfSelectedValues,
                    isCollapsed: this.isCollapsed,
                    headingLevel: 0,
                    onToggleCollapse: ()=>{
                        this.isCollapsed = !this.isCollapsed;
                    },
                    onClearFilters: ()=>{
                        this.focusTarget.focusAfterSearch();
                        this.facet.deselectAll();
                    },
                    headerRef: (el)=>this.focusTarget.setTarget(el)
                }
            })}
        ${when(!this.isCollapsed, ()=>html`${when(this.shouldRenderValues, ()=>this.renderValues())}
            ${when(this.shouldRenderInput, ()=>html`<atomic-commerce-facet-number-input
                  label=${this.displayName}
                  .facet=${this.facet}
                  .range=${this.facetState.manualRange}
                  @atomic-number-input-apply=${this.onNumberInputApply}
                ></atomic-commerce-facet-number-input>`)}`)}`))}`;
    }
    validateFacet() {
        if (!this.facet) this.error = new Error('The "facet" property is required for <atomic-commerce-facet>.');
    }
    constructor(...args){
        super(...args), this.isCollapsed = false;
    }
}
AtomicCommerceNumericFacet.styles = numeric_facet_common_tw_css;
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Summary ? Object : Summary)
], AtomicCommerceNumericFacet.prototype, "summary", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof NumericFacet ? Object : NumericFacet)
], AtomicCommerceNumericFacet.prototype, "facet", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'is-collapsed',
        converter: booleanConverter
    })
], AtomicCommerceNumericFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceNumericFacet.prototype, "field", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceNumericFacet.prototype, "bindings", void 0);
_ts_decorate([
    bindStateToController('facet'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof NumericFacetState ? Object : NumericFacetState)
], AtomicCommerceNumericFacet.prototype, "facetState", void 0);
_ts_decorate([
    bindStateToController('summary'),
    decorators_js_state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceNumericFacet.prototype, "summaryState", void 0);
_ts_decorate([
    bindStateToController('context'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof ContextState ? Object : ContextState)
], AtomicCommerceNumericFacet.prototype, "contextState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceNumericFacet.prototype, "error", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceNumericFacet.prototype, "render", null);
AtomicCommerceNumericFacet = _ts_decorate([
    customElement('atomic-commerce-numeric-facet'),
    bindings(),
    withTailwindStyles
], AtomicCommerceNumericFacet);
export { AtomicCommerceNumericFacet };
