import { Schema, StringValue } from "@coveo/bueno";
import { buildFacetConditionsManager, buildNumericFacet, buildNumericFilter, buildNumericRange, buildSearchStatus, buildTabManager, loadNumericFacetSetActions } from "@coveo/headless";
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 { parseDependsOn } from "../../common/facets/depends-on.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 { renderFacetPlaceholder } from "../../common/facets/facet-placeholder/facet-placeholder.js";
import { formatHumanReadable } from "../../common/facets/numeric-facet/formatter.js";
import { renderNumericFacetValue } from "../../common/facets/numeric-facet/value-link.js";
import { renderNumericFacetValuesGroup } from "../../common/facets/numeric-facet/values-container.js";
import numeric_facet_common_tw_css from "../../common/facets/numeric-facet-common.tw.css.js";
import { initializePopover } from "../../common/facets/popover/popover-type.js";
import { defaultNumberFormatter } from "../../common/formats/format-common.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { arrayConverter } from "../../../converters/array-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 { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { FocusTargetController } from "../../../utils/accessibility-utils.js";
import { mapProperty } from "../../../utils/props-utils.js";
import { randomID } from "../../../utils/utils.js";
import "../../common/atomic-facet-number-input/atomic-facet-number-input.js";
import "../../common/atomic-numeric-range/atomic-numeric-range.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 AtomicNumericFacet extends LitElement {
    initialize() {
        this.validateTabs();
        this.initializeTabManager();
        this.computeFacetId();
        this.initializeFacetForInput();
        this.initializeFacetForRange();
        this.initializeFilter();
        this.initializeSearchStatus();
        this.registerFacetToStore();
        this.registerNumberInputApplyListener();
    }
    connectedCallback() {
        super.connectedCallback();
        this.registerNumberFormatListener();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (!this.isConnected) {
            this.filterDependenciesManager?.stopWatching();
            this.removeNumberFormatListener?.();
            this.removeNumberInputApplyListener?.();
            this.unsubscribeFacetForRange?.();
            this.unsubscribeFacetForInput?.();
            this.unsubscribeFilter?.();
        }
    }
    get focusTarget() {
        if (!this.headerFocus) this.headerFocus = new FocusTargetController(this, this.bindings);
        return this.headerFocus;
    }
    get numberOfSelectedValues() {
        if (this.filter?.state.range) return 1;
        return this.facetForRange?.state.values.filter(({ state })=>'selected' === state).length || 0;
    }
    get shouldRenderValues() {
        return !this.hasInputRange && this.numberOfValues > 0 && !!this.valuesToRender.length;
    }
    get hasInputRange() {
        return !!this.filter?.state.range;
    }
    get valuesToRender() {
        return this.facetForRange?.state.values.filter((value)=>value.numberOfResults || 'idle' !== value.state) || [];
    }
    get shouldRenderInput() {
        return shouldDisplayInputForFacetRange({
            hasInputRange: this.hasInputRange,
            searchStatusState: this.searchStatusState,
            facetValues: this.facetForInput?.state.values || [],
            hasInput: !!this.withInput
        });
    }
    get shouldRenderFacet() {
        return this.shouldRenderInput || this.shouldRenderValues;
    }
    get enabled() {
        return this.facetState?.enabled ?? this.filter?.state.enabled ?? true;
    }
    get isHidden() {
        return !this.shouldRenderFacet || !this.enabled;
    }
    get hasValues() {
        if (this.facetForInput?.state.values.length) return true;
        return !!this.valuesToRender.length;
    }
    validateTabs() {
        if (this.tabsIncluded.length > 0 && this.tabsExcluded.length > 0) console.warn('Values for both "tabs-included" and "tabs-excluded" have been provided. This could lead to unexpected behaviors.');
    }
    initializeSearchStatus() {
        this.searchStatus = buildSearchStatus(this.bindings.engine);
    }
    initializeTabManager() {
        this.tabManager = buildTabManager(this.bindings.engine);
    }
    initializeFacetForInput() {
        if (!this.withInput) return;
        this.facetForInput = buildNumericFacet(this.bindings.engine, {
            options: {
                numberOfValues: 1,
                generateAutomaticRanges: true,
                facetId: `${this.facetId}_input_range`,
                field: this.field,
                sortCriteria: this.sortCriteria,
                rangeAlgorithm: this.rangeAlgorithm,
                filterFacetCount: this.filterFacetCount,
                injectionDepth: this.injectionDepth,
                tabs: {
                    included: this.tabsIncluded,
                    excluded: this.tabsExcluded
                }
            }
        });
        this.facetForInputState = this.facetForInput.state;
        this.unsubscribeFacetForInput = this.facetForInput.subscribe(()=>{
            this.facetForInputState = this.facetForInput.state;
        });
        return this.facetForInput;
    }
    initializeFacetForRange() {
        if (this.numberOfValues <= 0) return;
        this.manualRanges = Array.from(this.querySelectorAll('atomic-numeric-range')).map((range)=>{
            const { start, end, endInclusive, label } = range;
            return {
                ...buildNumericRange({
                    start,
                    end,
                    endInclusive
                }),
                label
            };
        });
        this.facetForRange = buildNumericFacet(this.bindings.engine, {
            options: {
                facetId: this.facetId,
                field: this.field,
                numberOfValues: this.numberOfValues,
                sortCriteria: this.sortCriteria,
                rangeAlgorithm: this.rangeAlgorithm,
                currentValues: this.manualRanges,
                generateAutomaticRanges: !this.manualRanges.length,
                filterFacetCount: this.filterFacetCount,
                injectionDepth: this.injectionDepth,
                tabs: {
                    included: this.tabsIncluded,
                    excluded: this.tabsExcluded
                }
            }
        });
        this.facetState = this.facetForRange.state;
        this.unsubscribeFacetForRange = this.facetForRange.subscribe(()=>{
            this.facetState = this.facetForRange.state;
        });
        return this.facetForRange;
    }
    initializeFilter() {
        if (!this.withInput) return;
        this.filter = buildNumericFilter(this.bindings.engine, {
            options: {
                facetId: `${this.facetId}_input`,
                field: this.field,
                tabs: {
                    included: this.tabsIncluded,
                    excluded: this.tabsExcluded
                }
            }
        });
        this.filterDependenciesManager = this.initializeDependenciesManager(this.filter.state.facetId);
        this.filterState = this.filter.state;
        this.unsubscribeFilter = this.filter.subscribe(()=>{
            this.filterState = this.filter.state;
        });
    }
    initializeDependenciesManager(facetId) {
        return buildFacetConditionsManager(this.bindings.engine, {
            facetId,
            conditions: parseDependsOn(this.dependsOn || {})
        });
    }
    registerFacetToStore() {
        const facetInfo = {
            label: ()=>this.bindings.i18n.t(this.label),
            facetId: this.facetId,
            element: this,
            isHidden: ()=>this.isHidden
        };
        this.bindings.store.registerFacet('numericFacets', {
            ...facetInfo,
            format: (value)=>formatHumanReadable({
                    facetValue: value,
                    logger: this.bindings.engine.logger,
                    i18n: this.bindings.i18n,
                    field: this.field,
                    manualRanges: this.manualRanges,
                    formatter: this.formatter
                })
        });
        initializePopover(this, {
            ...facetInfo,
            hasValues: ()=>this.hasValues,
            numberOfActiveValues: ()=>this.numberOfSelectedValues
        });
        if (this.filter) this.bindings.store.state.numericFacets[this.filter.state.facetId] = this.bindings.store.state.numericFacets[this.facetId];
    }
    registerNumberFormatListener() {
        const handleNumberFormat = (event)=>{
            event.preventDefault();
            event.stopPropagation();
            this.formatter = event.detail;
        };
        this.addEventListener('atomic/numberFormat', handleNumberFormat);
        this.removeNumberFormatListener = ()=>{
            this.removeEventListener('atomic/numberFormat', handleNumberFormat);
        };
    }
    registerNumberInputApplyListener() {
        const handleNumberInputApply = ()=>{
            if (this.facetId) this.bindings.engine.dispatch(loadNumericFacetSetActions(this.bindings.engine).deselectAllNumericFacetValues(this.facetId));
        };
        this.addEventListener('atomic/numberInputApply', handleNumberInputApply);
        this.removeNumberInputApplyListener = ()=>{
            this.removeEventListener('atomic/numberInputApply', handleNumberInputApply);
        };
    }
    computeFacetId() {
        if (this.facetId) return;
        if (this.bindings.store.state.numericFacets[this.field]) {
            this.facetId = randomID(`${this.field}_`);
            return;
        }
        this.facetId = this.field;
    }
    handleClearFilters() {
        this.focusTarget.focusAfterSearch();
        if (this.filterState?.range) return void this.filter?.clear();
        this.facetForRange?.deselectAll();
    }
    handleToggleCollapse() {
        this.isCollapsed = !this.isCollapsed;
    }
    handleValueClick(value) {
        if ('link' === this.displayValuesAs) this.facetForRange.toggleSingleSelect(value);
        else this.facetForRange.toggleSelect(value);
    }
    renderValues() {
        const { displayValuesAs, field, manualRanges, label, bindings: { i18n, engine: { logger } }, formatter } = this;
        return renderNumericFacetValuesGroup({
            props: {
                i18n,
                label
            }
        })(html`${this.valuesToRender.map((value)=>renderNumericFacetValue({
                props: {
                    formatter,
                    displayValuesAs,
                    facetValue: value,
                    field,
                    i18n,
                    logger,
                    manualRanges,
                    onClick: ()=>this.handleValueClick(value)
                }
            }))}`);
    }
    renderInput() {
        return html`<atomic-facet-number-input
      .type=${this.withInput}
      .bindings=${this.bindings}
      .label=${this.label}
      .filter=${this.filter}
      .filterState=${this.filter.state}
    ></atomic-facet-number-input>`;
    }
    render() {
        const { searchStatusState: { firstSearchExecuted, hasError } } = this;
        if (hasError || !this.enabled) return html``;
        if (!firstSearchExecuted) return html`${renderFacetPlaceholder({
            props: {
                numberOfValues: this.numberOfValues,
                isCollapsed: this.isCollapsed
            }
        })}`;
        return html`${when(this.shouldRenderFacet, ()=>renderFacetContainer()(html`${renderFacetHeader({
                props: {
                    i18n: this.bindings.i18n,
                    label: this.label,
                    onClearFilters: ()=>this.handleClearFilters(),
                    numberOfActiveValues: this.numberOfSelectedValues,
                    isCollapsed: this.isCollapsed,
                    headingLevel: this.headingLevel,
                    onToggleCollapse: ()=>this.handleToggleCollapse(),
                    headerRef: (el)=>this.focusTarget.setTarget(el)
                }
            })}
        ${when(!this.isCollapsed, ()=>html`${when(this.shouldRenderValues, ()=>this.renderValues())}
            ${when(this.shouldRenderInput, ()=>this.renderInput())}`)}`))}`;
    }
    constructor(){
        super(), this.label = 'no-label', this.tabsIncluded = [], this.tabsExcluded = [], this.numberOfValues = 8, this.sortCriteria = 'ascending', this.rangeAlgorithm = 'equiprobable', this.displayValuesAs = 'checkbox', this.isCollapsed = false, this.headingLevel = 0, this.filterFacetCount = true, this.injectionDepth = 1000, this.manualRanges = [], this.formatter = defaultNumberFormatter;
        new ValidatePropsController(this, ()=>({
                displayValuesAs: this.displayValuesAs,
                withInput: this.withInput
            }), AtomicNumericFacet.propsSchema);
    }
}
AtomicNumericFacet.propsSchema = new Schema({
    displayValuesAs: new StringValue({
        constrainTo: [
            'checkbox',
            'link'
        ]
    }),
    withInput: new StringValue({
        constrainTo: [
            'integer',
            'decimal'
        ]
    })
});
AtomicNumericFacet.styles = numeric_facet_common_tw_css;
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'facet-id'
    }),
    _ts_metadata("design:type", String)
], AtomicNumericFacet.prototype, "facetId", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicNumericFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicNumericFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-included',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicNumericFacet.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-excluded',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicNumericFacet.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'number-of-values'
    })
], AtomicNumericFacet.prototype, "numberOfValues", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'with-input'
    }),
    _ts_metadata("design:type", "u" < typeof NumberInputType ? Object : NumberInputType)
], AtomicNumericFacet.prototype, "withInput", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'sort-criteria'
    }),
    _ts_metadata("design:type", "u" < typeof RangeFacetSortCriterion ? Object : RangeFacetSortCriterion)
], AtomicNumericFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'range-algorithm'
    }),
    _ts_metadata("design:type", "u" < typeof RangeFacetRangeAlgorithm ? Object : RangeFacetRangeAlgorithm)
], AtomicNumericFacet.prototype, "rangeAlgorithm", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'display-values-as'
    }),
    _ts_metadata("design:type", String)
], AtomicNumericFacet.prototype, "displayValuesAs", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'is-collapsed'
    })
], AtomicNumericFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'heading-level'
    })
], AtomicNumericFacet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'filter-facet-count'
    })
], AtomicNumericFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'injection-depth'
    })
], AtomicNumericFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    mapProperty({
        attributePrefix: 'depends-on'
    }),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicNumericFacet.prototype, "dependsOn", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicNumericFacet.prototype, "bindings", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof NumericFacetState ? Object : NumericFacetState)
], AtomicNumericFacet.prototype, "facetState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof NumericFilterState ? Object : NumericFilterState)
], AtomicNumericFacet.prototype, "filterState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicNumericFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicNumericFacet.prototype, "tabManagerState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicNumericFacet.prototype, "error", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof NumericFacetState ? Object : NumericFacetState)
], AtomicNumericFacet.prototype, "facetForInputState", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicNumericFacet.prototype, "render", null);
AtomicNumericFacet = _ts_decorate([
    customElement('atomic-numeric-facet'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicNumericFacet);
export { AtomicNumericFacet };
