import { buildFacet, buildFacetConditionsManager, buildSearchStatus, buildTabManager } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { parseDependsOn } from "../../common/facets/depends-on.js";
import facet_common_tw_css from "../../common/facets/facet-common.tw.css.js";
import { renderFacetValuesGroup } from "../../common/facets/facet-values-group/facet-values-group.js";
import { renderFacetSegmentedValue } from "../facets/facet-segmented-value/facet-segmented-value.js";
import facet_segmented_value_tw_css from "../facets/facet-segmented-value/facet-segmented-value.tw.css.js";
import { arrayConverter } from "../../../converters/array-converter.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 { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { getFieldValueCaption } from "../../../utils/field-utils.js";
import { mapProperty } from "../../../utils/props-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 AtomicSegmentedFacet extends LitElement {
    initialize() {
        if (this.tabsIncluded.length > 0 && this.tabsExcluded.length > 0) console.warn('Values for both "tabs-included" and "tabs-excluded" have been provided. This is could lead to unexpected behaviors.');
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        this.facet = buildFacet(this.bindings.engine, {
            options: this.facetOptions
        });
        this.facetId = this.facet.state.facetId;
        this.dependenciesManager = buildFacetConditionsManager(this.bindings.engine, {
            facetId: this.facetId,
            conditions: parseDependsOn(this.dependsOn)
        });
    }
    render() {
        if (this.searchStatusState.hasError || !this.facetState.enabled) return html``;
        if (!this.searchStatusState.firstSearchExecuted) return html`
        <div
          part="placeholder"
          aria-hidden="true"
          class="bg-neutral h-8 w-48 animate-pulse rounded"
        ></div>
      `;
        if (!this.facetState.values.length) return html``;
        return html`
      <div
        part="segmented-container"
        class="mr-2 flex h-10 items-center whitespace-nowrap"
      >
        ${this.renderLabel()} ${this.renderValues()}
      </div>
    `;
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (!this.isConnected) this.dependenciesManager?.stopWatching();
    }
    renderValuesContainer(children) {
        const classes = 'box-container flex h-10';
        return renderFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.label
            }
        })(html`
      <ul class=${classes} part="values">
        ${children}
      </ul>
    `);
    }
    renderValue(facetValue, onClick) {
        const displayValue = getFieldValueCaption(this.field, facetValue.value, this.bindings.i18n);
        const isSelected = 'idle' !== facetValue.state;
        return renderFacetSegmentedValue({
            props: {
                displayValue,
                numberOfResults: facetValue.numberOfResults,
                isSelected,
                i18n: this.bindings.i18n,
                onClick,
                searchQuery: this.facetState.facetSearch.query
            }
        });
    }
    renderValues() {
        return this.renderValuesContainer(this.facetState.values.map((value)=>this.renderValue(value, ()=>this.facet.toggleSingleSelect(value))));
    }
    renderLabel() {
        return when(this.label, ()=>html` <b class="mr-2" part="label"> ${this.label}: </b> `);
    }
    get facetOptions() {
        return {
            facetId: this.facetId,
            field: this.field,
            numberOfValues: this.numberOfValues,
            sortCriteria: this.sortCriteria,
            facetSearch: {
                numberOfValues: this.numberOfValues
            },
            filterFacetCount: this.filterFacetCount,
            injectionDepth: this.injectionDepth,
            hasBreadcrumbs: false,
            allowedValues: this.allowedValues.length ? this.allowedValues : void 0,
            customSort: this.customSort.length ? this.customSort : void 0,
            tabs: {
                included: this.tabsIncluded,
                excluded: this.tabsExcluded
            }
        };
    }
    constructor(...args){
        super(...args), this.tabsIncluded = [], this.tabsExcluded = [], this.filterFacetCount = true, this.injectionDepth = 1000, this.numberOfValues = 6, this.sortCriteria = 'automatic', this.allowedValues = [], this.customSort = [];
    }
}
AtomicSegmentedFacet.styles = [
    facet_common_tw_css,
    facet_segmented_value_tw_css
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicSegmentedFacet.prototype, "bindings", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof SearchStatus ? Object : SearchStatus)
], AtomicSegmentedFacet.prototype, "searchStatus", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof TabManager ? Object : TabManager)
], AtomicSegmentedFacet.prototype, "tabManager", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Facet ? Object : Facet)
], AtomicSegmentedFacet.prototype, "facet", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicSegmentedFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicSegmentedFacet.prototype, "tabManagerState", void 0);
_ts_decorate([
    bindStateToController('facet'),
    state(),
    _ts_metadata("design:type", "u" < typeof FacetState ? Object : FacetState)
], AtomicSegmentedFacet.prototype, "facetState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicSegmentedFacet.prototype, "error", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'facet-id'
    }),
    _ts_metadata("design:type", String)
], AtomicSegmentedFacet.prototype, "facetId", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSegmentedFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicSegmentedFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-included',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicSegmentedFacet.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-excluded',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicSegmentedFacet.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'filter-facet-count',
        reflect: true
    })
], AtomicSegmentedFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'injection-depth'
    })
], AtomicSegmentedFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: Number,
        attribute: 'number-of-values'
    })
], AtomicSegmentedFacet.prototype, "numberOfValues", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'sort-criteria'
    }),
    _ts_metadata("design:type", "u" < typeof FacetSortCriterion ? Object : FacetSortCriterion)
], AtomicSegmentedFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    mapProperty({
        attributePrefix: 'depends-on'
    }),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicSegmentedFacet.prototype, "dependsOn", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'allowed-values',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicSegmentedFacet.prototype, "allowedValues", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'custom-sort',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicSegmentedFacet.prototype, "customSort", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicSegmentedFacet.prototype, "render", null);
AtomicSegmentedFacet = _ts_decorate([
    customElement('atomic-segmented-facet'),
    bindings(),
    withTailwindStyles
], AtomicSegmentedFacet);
export { AtomicSegmentedFacet };
