import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildFacet, buildFacetConditionsManager, buildSearchStatus } from "@coveo/headless/insight";
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 { 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 { 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 { 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 { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import "../../common/atomic-facet-placeholder/atomic-facet-placeholder.js";
import facet_common_tw_css from "../../common/facets/facet-common.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 AtomicInsightFacet extends LitElement {
    initialize() {
        const options = {
            facetId: this.facetId,
            field: this.field,
            numberOfValues: this.numberOfValues,
            sortCriteria: this.sortCriteria,
            facetSearch: {
                numberOfValues: this.numberOfValues
            },
            filterFacetCount: this.filterFacetCount,
            injectionDepth: this.injectionDepth
        };
        this.facet = buildFacet(this.bindings.engine, {
            options
        });
        this.facetId = this.facet.state.facetId;
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.initAriaLive();
        this.initConditionManager();
        this.initPopover();
        this.registerFacet();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (!this.isConnected) this.facetConditionsManager?.stopWatching();
    }
    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
        };
    }
    shouldRenderFacet() {
        return this.facetState.enabled && !this.searchStatusState.hasError && (!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}"
            ?is-collapsed="${this.isCollapsed}"
          ></atomic-facet-placeholder>`)}`;
    }
    renderFacetHeader() {
        return renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.label,
                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`${this.renderValues()} ${this.renderShowMoreLess()}`;
    }
    renderValuesContainer(children) {
        return renderFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.label
            }
        })(html`<ul
      class="mt-3 ${'box' === this.displayValuesAs ? 'box-container' : ''}"
      part="values"
    >
      ${children}
    </ul>`);
    }
    renderValues() {
        const values = this.facet.state.values.map((value, i)=>{
            const shouldFocusOnShowLessAfterInteraction = 0 === i;
            const shouldFocusOnShowMoreAfterInteraction = i === ('automatic' === this.sortCriteria ? 0 : this.facetState.values.length - 1);
            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);
                    }
                }
            });
        });
        return this.renderValuesContainer(values);
    }
    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
            }
        });
    }
    get activeValues() {
        return this.facet.state.values.filter(({ state })=>'idle' !== state);
    }
    get facetValueProps() {
        return {
            facetSearchQuery: this.facetState.facetSearch.query,
            displayValuesAs: this.displayValuesAs,
            enableExclusion: this.enableExclusion,
            field: this.field,
            i18n: this.bindings.i18n
        };
    }
    initAriaLive() {
        this.facetSearchAriaLiveController = new AriaLiveRegionController(this, 'facet-search');
        announceFacetSearchResultsWithAriaLive(this.facet, this.label, (msg)=>{
            this.facetSearchAriaLiveController.message = msg;
        }, this.bindings.i18n);
    }
    initConditionManager() {
        this.facetConditionsManager = buildFacetConditionsManager(this.bindings.engine, {
            facetId: this.facetId,
            conditions: parseDependsOn(this.dependsOn)
        });
    }
    initPopover() {
        initializePopover(this, {
            ...this.facetInfo,
            hasValues: ()=>!!this.facet.state.values.length,
            numberOfActiveValues: ()=>this.activeValues.length
        });
    }
    get isHidden() {
        return !this.facet.state.enabled || !this.facet.state.values.length;
    }
    get facetInfo() {
        return {
            label: ()=>this.bindings.i18n.t(this.label),
            facetId: this.facetId,
            element: this,
            isHidden: ()=>this.isHidden
        };
    }
    registerFacet() {
        this.bindings.store.registerFacet('facets', this.facetInfo);
    }
    constructor(){
        super(), this.label = 'no-label', this.numberOfValues = 8, this.sortCriteria = 'automatic', this.displayValuesAs = 'checkbox', this.isCollapsed = false, this.headingLevel = 0, this.filterFacetCount = true, this.injectionDepth = 1000, this.enableExclusion = false, this.dependsOn = {};
        new ValidatePropsController(this, ()=>({
                field: this.field,
                numberOfValues: this.numberOfValues,
                injectionDepth: this.injectionDepth
            }), AtomicInsightFacet.propsSchema, false);
    }
}
AtomicInsightFacet.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    }),
    numberOfValues: new NumberValue({
        min: 1
    }),
    injectionDepth: new NumberValue({
        min: 0
    })
});
AtomicInsightFacet.styles = [
    facet_common_tw_css,
    facet_value_box_tw_css,
    facet_value_checkbox_tw_css,
    facet_value_exclude_tw_css
];
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicInsightFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicInsightFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'number-of-values'
    })
], AtomicInsightFacet.prototype, "numberOfValues", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'sort-criteria'
    }),
    _ts_metadata("design:type", "u" < typeof InsightFacetSortCriterion ? Object : InsightFacetSortCriterion)
], AtomicInsightFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'display-values-as'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightFacet.prototype, "displayValuesAs", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'is-collapsed'
    })
], AtomicInsightFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'heading-level'
    })
], AtomicInsightFacet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'filter-facet-count'
    })
], AtomicInsightFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'injection-depth'
    })
], AtomicInsightFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'enable-exclusion'
    })
], AtomicInsightFacet.prototype, "enableExclusion", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'facet-id'
    }),
    _ts_metadata("design:type", String)
], AtomicInsightFacet.prototype, "facetId", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightFacet.prototype, "bindings", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightFacet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('facet'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof InsightFacetState ? Object : InsightFacetState)
], AtomicInsightFacet.prototype, "facetState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof InsightSearchStatusState ? Object : InsightSearchStatusState)
], AtomicInsightFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightFacet.prototype, "render", null);
AtomicInsightFacet = _ts_decorate([
    customElement('atomic-insight-facet'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightFacet);
export { AtomicInsightFacet };
