import { ArrayValue, NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildFacet, buildFacetConditionsManager, buildSearchStatus, buildTabManager } from "@coveo/headless";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state as decorators_js_state } from "lit/decorators.js";
import { when } from "lit/directives/when.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 { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import { mapProperty } from "../../../utils/props-utils.js";
import { getFieldCaptions } from "../../../utils/field-utils.js";
import { parseDependsOn } from "../../common/facets/depends-on.js";
import { renderFacetContainer } from "../../common/facets/facet-container/facet-container.js";
import { renderFacetHeader } from "../../common/facets/facet-header/facet-header.js";
import { announceFacetSearchResultsWithAriaLive } from "../../common/facets/facet-search/facet-search-aria-live.js";
import { renderFacetSearchInput } from "../../common/facets/facet-search/facet-search-input.js";
import { facetSearchInputGuard } from "../../common/facets/facet-search/facet-search-input-guard.js";
import { renderFacetSearchMatches } from "../../common/facets/facet-search/facet-search-matches.js";
import { shouldDisplaySearchResults, shouldUpdateFacetSearchComponent } from "../../common/facets/facet-search/facet-search-utils.js";
import { renderFacetShowMoreLess } from "../../common/facets/facet-show-more-less/facet-show-more-less.js";
import { renderFacetValue } from "../../common/facets/facet-value/facet-value.js";
import { renderFacetValuesGroup } from "../../common/facets/facet-values-group/facet-values-group.js";
import { initializePopover } from "../../common/facets/popover/popover-type.js";
import "../../common/atomic-facet-placeholder/atomic-facet-placeholder.js";
import { arrayConverter } from "../../../converters/array-converter.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { bindings } from "../../../decorators/bindings.js";
import facet_common_tw_css from "../../common/facets/facet-common.tw.css.js";
import facet_search_tw_css from "../../common/facets/facet-search/facet-search.tw.css.js";
import facet_value_box_tw_css from "../../common/facets/facet-value-box/facet-value-box.tw.css.js";
import facet_value_checkbox_tw_css from "../../common/facets/facet-value-checkbox/facet-value-checkbox.tw.css.js";
import facet_value_exclude_tw_css from "../../common/facets/facet-value-exclude/facet-value-exclude.tw.css.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.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 AtomicFacet 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.');
        if ('checkbox' !== this.displayValuesAs && this.enableExclusion) console.warn('The "enableExclusion" property is only available when "displayValuesAs" is set to "checkbox".');
        this.facet = buildFacet(this.bindings.engine, {
            options: this.facetOptions
        });
        this.facetId = this.facet.state.facetId;
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        this.initAriaLive();
        this.initConditionManager();
        this.initPopover();
        this.registerFacet();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (!this.isConnected) this.facetConditionsManager?.stopWatching();
    }
    shouldUpdate(changedProperties) {
        if (changedProperties.has('facetState')) {
            const currentFacetState = this.facetState;
            const previousFacetState = changedProperties.get('facetState');
            if (previousFacetState && currentFacetState) return shouldUpdateFacetSearchComponent(currentFacetState.facetSearch, previousFacetState.facetSearch);
        }
        return super.shouldUpdate(changedProperties);
    }
    shouldRenderFacet() {
        return !this.searchStatusState.hasError && this.facetState.enabled && (!this.searchStatusState.firstSearchExecuted || this.facetState.values.length > 0);
    }
    render() {
        return html`${when(this.shouldRenderFacet(), ()=>this.searchStatusState.firstSearchExecuted ? renderFacetContainer()(html`
            ${this.renderFacetHeader()} ${this.renderBody()}
          `) : html`<atomic-facet-placeholder
            value-count="${this.numberOfValues}"
          ></atomic-facet-placeholder>`)}`;
    }
    renderFacetHeader() {
        return html`${renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.definedLabel,
                onClearFilters: ()=>{
                    this.focusTargets.header.focusAfterSearch();
                    this.facet.deselectAll();
                },
                numberOfActiveValues: this.activeValues.length,
                isCollapsed: this.isCollapsed,
                headingLevel: this.headingLevel,
                onToggleCollapse: ()=>{
                    this.isCollapsed = !this.isCollapsed;
                },
                headerRef: (el)=>this.focusTargets.header.setTarget(el)
            }
        })}`;
    }
    renderBody() {
        if (this.isCollapsed) return nothing;
        return html`
      ${facetSearchInputGuard({
            canShowMoreValues: this.facetState.canShowMoreValues,
            numberOfDisplayedValues: this.facetState.values.length,
            withSearch: this.withSearch
        }, ()=>renderFacetSearchInput({
                props: {
                    i18n: this.bindings.i18n,
                    label: this.definedLabel,
                    onChange: (value)=>{
                        if ('' === value) return void this.facet.facetSearch.clear();
                        this.facet.facetSearch.updateCaptions(getFieldCaptions(this.field, this.bindings.i18n));
                        this.facet.facetSearch.updateText(value);
                        this.facet.facetSearch.search();
                    },
                    onClear: ()=>this.facet.facetSearch.clear(),
                    query: this.facetState.facetSearch.query
                }
            }))}
      ${shouldDisplaySearchResults(this.facetState.facetSearch) ? html`${this.renderSearchResults()}${this.renderMatches()}` : html`${this.renderValues()}${this.renderShowMoreLess()}`}
    `;
    }
    renderValuesContainer(children, query) {
        const classes = `mt-3 ${'box' === this.displayValuesAs ? 'box-container' : ''}`;
        return renderFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.label,
                query
            }
        })(html`<ul class="${classes}" part="values">
        ${children}
      </ul>`);
    }
    renderSearchResults() {
        return this.renderValuesContainer(this.facet.state.facetSearch.values.map((value)=>renderFacetValue({
                props: {
                    ...this.facetValueProps,
                    facetState: 'idle',
                    facetCount: value.count,
                    onExclude: ()=>this.facet.facetSearch.exclude(value),
                    onSelect: ()=>'link' === this.displayValuesAs ? this.facet.facetSearch.singleSelect(value) : this.facet.facetSearch.select(value),
                    facetValue: value.rawValue
                }
            })));
    }
    renderValues() {
        return this.renderValuesContainer(this.facet.state.values.map((value, i)=>{
            const shouldFocusOnShowLessAfterInteraction = 0 === i;
            const shouldFocusOnShowMoreAfterInteraction = i === ('automatic' === this.sortCriteria ? 0 : this.facet.state.values.length - this.numberOfValues);
            return renderFacetValue({
                props: {
                    ...this.facetValueProps,
                    facetCount: value.numberOfResults,
                    onExclude: ()=>this.facet.toggleExclude(value),
                    onSelect: ()=>'link' === this.displayValuesAs ? this.facet.toggleSingleSelect(value) : this.facet.toggleSelect(value),
                    facetValue: value.value,
                    facetState: value.state,
                    setRef: (btn)=>{
                        if (shouldFocusOnShowLessAfterInteraction) this.showLessFocus?.setTarget(btn);
                        if (shouldFocusOnShowMoreAfterInteraction) this.showMoreFocus?.setTarget(btn);
                    }
                }
            });
        }));
    }
    renderShowMoreLess() {
        return renderFacetShowMoreLess({
            props: {
                label: this.label,
                i18n: this.bindings.i18n,
                onShowMore: ()=>{
                    this.focusTargets.showMore.focusAfterSearch();
                    this.facet.showMoreValues();
                },
                onShowLess: ()=>{
                    this.focusTargets.showLess.focusAfterSearch();
                    this.facet.showLessValues();
                },
                canShowMoreValues: this.facet.state.canShowMoreValues,
                canShowLessValues: this.facet.state.canShowLessValues
            }
        });
    }
    renderMatches() {
        return renderFacetSearchMatches({
            props: {
                i18n: this.bindings.i18n,
                query: this.facet.state.facetSearch.query,
                numberOfMatches: this.facet.state.facetSearch.values.length,
                hasMoreMatches: this.facet.state.facetSearch.moreValuesAvailable,
                showMoreMatches: ()=>this.facet.facetSearch.showMoreResults()
            }
        });
    }
    get activeValues() {
        return this.facet.state.values.filter(({ state })=>'idle' !== state);
    }
    get facetOptions() {
        return {
            facetId: this.facetId,
            field: this.field,
            numberOfValues: this.numberOfValues,
            sortCriteria: this.sortCriteria,
            resultsMustMatch: this.resultsMustMatch,
            facetSearch: {
                numberOfValues: this.numberOfValues
            },
            filterFacetCount: this.filterFacetCount,
            injectionDepth: this.injectionDepth,
            allowedValues: this.allowedValues.length ? [
                ...this.allowedValues
            ] : void 0,
            customSort: this.customSort.length ? [
                ...this.customSort
            ] : void 0,
            tabs: {
                included: [
                    ...this.tabsIncluded
                ],
                excluded: [
                    ...this.tabsExcluded
                ]
            }
        };
    }
    get facetValueProps() {
        return {
            facetSearchQuery: this.facetState.facetSearch.query,
            displayValuesAs: this.displayValuesAs,
            enableExclusion: this.enableExclusion,
            field: this.field,
            i18n: this.bindings.i18n
        };
    }
    get isHidden() {
        return !this.facet.state.enabled || !this.facet.state.values.length;
    }
    get host() {
        return this;
    }
    initConditionManager() {
        this.facetConditionsManager = buildFacetConditionsManager(this.bindings.engine, {
            facetId: this.facetId,
            conditions: parseDependsOn(this.dependsOn || {})
        });
    }
    registerFacet() {
        this.bindings.store.registerFacet('facets', this.facetInfo);
    }
    initPopover() {
        initializePopover(this.host, {
            ...this.facetInfo,
            hasValues: ()=>!!this.facet.state.values.length,
            numberOfActiveValues: ()=>this.activeValues.length
        });
    }
    initAriaLive() {
        this.facetSearchAriaLive = new AriaLiveRegionController(this, 'facet-search');
        announceFacetSearchResultsWithAriaLive(this.facet, this.label, (msg)=>{
            this.facetSearchAriaLive.message = msg;
        }, this.bindings.i18n);
    }
    get facetInfo() {
        return {
            label: ()=>this.bindings.i18n.t(this.label),
            facetId: this.facetId,
            element: this.host,
            isHidden: ()=>this.isHidden
        };
    }
    get definedLabel() {
        return 'no-label' === this.label && this.facetState?.label ? this.facetState.label : this.label;
    }
    get focusTargets() {
        if (!this.showLessFocus) this.showLessFocus = new FocusTargetController(this, this.bindings);
        if (!this.showMoreFocus) this.showMoreFocus = new FocusTargetController(this, this.bindings);
        if (!this.headerFocus) this.headerFocus = new FocusTargetController(this, this.bindings);
        return {
            showLess: this.showLessFocus,
            showMore: this.showMoreFocus,
            header: this.headerFocus
        };
    }
    constructor(){
        super(), this.label = 'no-label', this.tabsIncluded = [], this.tabsExcluded = [], this.numberOfValues = 8, this.withSearch = true, this.sortCriteria = 'automatic', this.resultsMustMatch = 'atLeastOneValue', this.displayValuesAs = 'checkbox', this.isCollapsed = false, this.headingLevel = 0, this.filterFacetCount = true, this.enableExclusion = false, this.injectionDepth = 1000, this.allowedValues = [], this.customSort = [];
        new ValidatePropsController(this, ()=>({
                field: this.field,
                numberOfValues: this.numberOfValues,
                headingLevel: this.headingLevel,
                injectionDepth: this.injectionDepth,
                sortCriteria: this.sortCriteria,
                resultsMustMatch: this.resultsMustMatch,
                displayValuesAs: this.displayValuesAs,
                allowedValues: Array.isArray(this.allowedValues) ? this.allowedValues : [],
                customSort: Array.isArray(this.customSort) ? this.customSort : [],
                tabsExcluded: this.tabsExcluded,
                tabsIncluded: this.tabsIncluded
            }), AtomicFacet.propsSchema);
    }
}
AtomicFacet.styles = [
    facet_common_tw_css,
    facet_search_tw_css,
    facet_value_checkbox_tw_css,
    facet_value_exclude_tw_css,
    facet_value_box_tw_css
];
AtomicFacet.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    }),
    numberOfValues: new NumberValue({
        min: 1,
        required: false
    }),
    headingLevel: new NumberValue({
        min: 0,
        max: 6,
        required: false
    }),
    injectionDepth: new NumberValue({
        min: 0,
        required: false
    }),
    sortCriteria: new StringValue({
        constrainTo: [
            'score',
            'alphanumeric',
            'alphanumericDescending',
            'occurrences',
            'alphanumericNatural',
            'alphanumericNaturalDescending',
            'automatic'
        ],
        required: false
    }),
    resultsMustMatch: new StringValue({
        constrainTo: [
            'atLeastOneValue',
            'allValues'
        ],
        required: false
    }),
    displayValuesAs: new StringValue({
        constrainTo: [
            'checkbox',
            'link',
            'box'
        ],
        required: false
    }),
    allowedValues: new ArrayValue({
        each: new StringValue({
            emptyAllowed: false
        }),
        max: 25,
        required: false
    }),
    customSort: new ArrayValue({
        each: new StringValue({
            emptyAllowed: false
        }),
        max: 25,
        required: false
    }),
    tabsExcluded: new ArrayValue({
        each: new StringValue({
            emptyAllowed: false
        }),
        required: false
    }),
    tabsIncluded: new ArrayValue({
        each: new StringValue({
            emptyAllowed: false
        }),
        required: false
    })
});
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicFacet.prototype, "bindings", void 0);
_ts_decorate([
    bindStateToController('facet'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof FacetState ? Object : FacetState)
], AtomicFacet.prototype, "facetState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicFacet.prototype, "tabManagerState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicFacet.prototype, "error", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'facet-id',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicFacet.prototype, "facetId", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-included',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicFacet.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'tabs-excluded',
        converter: arrayConverter,
        reflect: true
    }),
    _ts_metadata("design:type", Array)
], AtomicFacet.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'number-of-values',
        reflect: true
    })
], AtomicFacet.prototype, "numberOfValues", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'with-search',
        reflect: true
    })
], AtomicFacet.prototype, "withSearch", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'sort-criteria',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof FacetSortCriterion ? Object : FacetSortCriterion)
], AtomicFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'results-must-match',
        reflect: true
    }),
    _ts_metadata("design:type", "u" < typeof FacetResultsMustMatch ? Object : FacetResultsMustMatch)
], AtomicFacet.prototype, "resultsMustMatch", void 0);
_ts_decorate([
    property({
        type: String,
        attribute: 'display-values-as',
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicFacet.prototype, "displayValuesAs", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'is-collapsed',
        reflect: true
    })
], AtomicFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'heading-level'
    })
], AtomicFacet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'filter-facet-count',
        reflect: true
    })
], AtomicFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'enable-exclusion',
        reflect: true
    })
], AtomicFacet.prototype, "enableExclusion", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'injection-depth'
    })
], AtomicFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    mapProperty({
        attributePrefix: 'depends-on'
    }),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicFacet.prototype, "dependsOn", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'allowed-values'
    }),
    _ts_metadata("design:type", Object)
], AtomicFacet.prototype, "allowedValues", void 0);
_ts_decorate([
    property({
        type: Array,
        attribute: 'custom-sort'
    }),
    _ts_metadata("design:type", Object)
], AtomicFacet.prototype, "customSort", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicFacet.prototype, "render", null);
AtomicFacet = _ts_decorate([
    customElement('atomic-facet'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicFacet);
export { AtomicFacet };
