import { NumberValue, Schema, StringValue } from "@coveo/bueno";
import { buildCategoryFacet, buildFacetConditionsManager, buildSearchStatus, buildTabManager } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { map } from "lit/directives/map.js";
import { when } from "lit/directives/when.js";
import { renderCategoryFacetAllCategoryButton } from "../../common/facets/category-facet/all-categories-button.js";
import { renderCategoryFacetChildrenAsTreeContainer } from "../../common/facets/category-facet/children-as-tree-container.js";
import { renderCategoryFacetParentAsTreeContainer } from "../../common/facets/category-facet/parent-as-tree-container.js";
import { renderCategoryFacetParentButton } from "../../common/facets/category-facet/parent-button.js";
import { renderCategoryFacetParentValueLink } from "../../common/facets/category-facet/parent-value-link.js";
import { renderCategoryFacetSearchResultsContainer } from "../../common/facets/category-facet/search-results-container.js";
import { renderCategoryFacetSearchValue } from "../../common/facets/category-facet/search-value.js";
import { renderCategoryFacetTreeValueContainer } from "../../common/facets/category-facet/value-as-tree-container.js";
import { renderCategoryFacetValueLink } from "../../common/facets/category-facet/value-link.js";
import { parseDependsOn } from "../../common/facets/depends-on.js";
import facet_common_tw_css from "../../common/facets/facet-common.tw.css.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 facet_search_tw_css from "../../common/facets/facet-search/facet-search.tw.css.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 { 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 { renderFacetValuesGroup } from "../../common/facets/facet-values-group/facet-values-group.js";
import { initializePopover } from "../../common/facets/popover/popover-type.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.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 { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import { getFieldCaptions, 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 AtomicCategoryFacet 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 could lead to unexpected behaviors.');
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.tabManager = buildTabManager(this.bindings.engine);
        const options = {
            facetId: this.facetId,
            field: this.field,
            numberOfValues: this.numberOfValues,
            sortCriteria: this.sortCriteria,
            facetSearch: {
                numberOfValues: this.numberOfValues
            },
            basePath: this.basePath,
            delimitingCharacter: this.delimitingCharacter,
            filterByBasePath: this.filterByBasePath,
            injectionDepth: this.injectionDepth,
            filterFacetCount: this.filterFacetCount,
            tabs: {
                included: this.tabsIncluded,
                excluded: this.tabsExcluded
            }
        };
        this.facet = buildCategoryFacet(this.bindings.engine, {
            options
        });
        this.facetId = this.facet.state.facetId;
        announceFacetSearchResultsWithAriaLive(this.facet, this.label, (msg)=>{
            this.facetSearchAriaMessage.message = msg;
        }, this.bindings.i18n);
        const facetInfo = {
            label: ()=>this.bindings.i18n.t(this.label),
            facetId: this.facetId,
            element: this,
            isHidden: ()=>this.isHidden
        };
        this.bindings.store.registerFacet('categoryFacets', facetInfo);
        initializePopover(this, {
            ...facetInfo,
            hasValues: ()=>!!this.facet.state.valuesAsTrees.length,
            numberOfActiveValues: ()=>this.facetState.hasActiveValues ? 1 : 0
        });
        this.initializeDependenciesManager();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        if (!this.isConnected) this.dependenciesManager?.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);
        if (!this.activeValueFocus) this.activeValueFocus = new FocusTargetController(this, this.bindings);
        return {
            showLessFocus: this.showLessFocus,
            showMoreFocus: this.showMoreFocus,
            headerFocus: this.headerFocus,
            activeValueFocus: this.activeValueFocus
        };
    }
    get isHidden() {
        return this.searchStatusState.hasError || !this.facet.state.enabled || !this.facet.state.selectedValueAncestry.length && !this.facet.state.valuesAsTrees.length;
    }
    get hasParents() {
        return !!this.facetState.selectedValueAncestry.length;
    }
    shouldUpdate(changedProperties) {
        if (changedProperties.has('facetState')) {
            const newState = this.facetState;
            const oldState = changedProperties.get('facetState');
            if (newState && oldState) return shouldUpdateFacetSearchComponent(newState.facetSearch, oldState.facetSearch);
        }
        return super.shouldUpdate(changedProperties);
    }
    initializeDependenciesManager() {
        this.dependenciesManager = buildFacetConditionsManager(this.bindings.engine, {
            facetId: this.facetId,
            conditions: parseDependsOn(this.dependsOn || {})
        });
    }
    renderHeader() {
        return renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.label,
                numberOfActiveValues: this.facetState.hasActiveValues && this.isCollapsed ? 1 : 0,
                isCollapsed: this.isCollapsed,
                headingLevel: this.headingLevel,
                onToggleCollapse: ()=>{
                    this.isCollapsed = !this.isCollapsed;
                },
                onClearFilters: ()=>{
                    this.focusTargets.headerFocus.focusAfterSearch();
                    this.facet.deselectAll();
                },
                headerRef: (header)=>{
                    this.focusTargets.headerFocus.setTarget(header);
                    if (!this.hasParents) this.focusTargets.activeValueFocus.setTarget(header);
                }
            }
        });
    }
    renderSearchInput() {
        if (!this.withSearch) return nothing;
        return renderFacetSearchInput({
            props: {
                i18n: this.bindings.i18n,
                label: this.label,
                query: this.facetState.facetSearch.query,
                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()
            }
        });
    }
    renderValuesTree(valuesAsTrees, isRoot) {
        if (!this.hasParents) return this.renderChildren();
        if (isRoot) return renderCategoryFacetTreeValueContainer()(html`
        ${renderCategoryFacetAllCategoryButton({
            props: {
                i18n: this.bindings.i18n,
                facetId: this.facet.state.facetId,
                field: this.field,
                onClick: ()=>{
                    this.focusTargets.activeValueFocus.focusAfterSearch();
                    this.facet.deselectAll();
                }
            }
        })}
        ${renderCategoryFacetParentAsTreeContainer({
            props: {
                isTopLevel: false
            }
        })(this.renderValuesTree(valuesAsTrees, false))}
      `);
        if (valuesAsTrees.length > 1) {
            const parentValue = valuesAsTrees[0];
            return renderCategoryFacetTreeValueContainer()(html`
        ${renderCategoryFacetParentButton({
                props: {
                    facetValue: parentValue,
                    field: this.field,
                    i18n: this.bindings.i18n,
                    onClick: ()=>{
                        this.focusTargets.activeValueFocus.focusAfterSearch();
                        this.facet.toggleSelect(parentValue);
                    }
                }
            })}
        ${renderCategoryFacetParentAsTreeContainer({
                props: {
                    isTopLevel: false
                }
            })(this.renderValuesTree(valuesAsTrees.slice(1), false))}
      `);
        }
        const activeParent = valuesAsTrees[0];
        const activeParentDisplayValue = getFieldValueCaption(this.field, activeParent.value, this.bindings.i18n);
        return html`
      ${renderCategoryFacetParentValueLink({
            props: {
                displayValue: activeParentDisplayValue,
                numberOfResults: activeParent.numberOfResults,
                i18n: this.bindings.i18n,
                isLeafValue: activeParent.isLeafValue,
                onClick: ()=>{
                    this.focusTargets.activeValueFocus.focusAfterSearch();
                    this.facet.deselectAll();
                },
                searchQuery: this.facetState.facetSearch.query,
                setRef: (el)=>{
                    this.focusTargets.activeValueFocus.setTarget(el);
                }
            }
        })(html`
        ${renderCategoryFacetChildrenAsTreeContainer({
            props: {}
        })(this.renderChildren())}
      `)}
    `;
    }
    renderChild(facetValue, isShowLessFocusTarget, isShowMoreFocusTarget) {
        const displayValue = getFieldValueCaption(this.field, facetValue.value, this.bindings.i18n);
        const isSelected = 'selected' === facetValue.state;
        return html`${renderCategoryFacetValueLink({
            props: {
                displayValue,
                numberOfResults: facetValue.numberOfResults,
                i18n: this.bindings.i18n,
                onClick: ()=>{
                    this.focusTargets.activeValueFocus.focusAfterSearch();
                    this.facet.toggleSelect(facetValue);
                },
                isParent: false,
                isSelected,
                searchQuery: this.facetState.facetSearch.query,
                isLeafValue: facetValue.isLeafValue,
                setRef: (el)=>{
                    isShowLessFocusTarget && this.focusTargets.showLessFocus.setTarget(el);
                    isShowMoreFocusTarget && this.focusTargets.showMoreFocus.setTarget(el);
                }
            }
        })()}`;
    }
    renderChildren() {
        if (!this.facetState.valuesAsTrees.length) return html``;
        if (this.facetState.selectedValueAncestry.length > 0) {
            const selectedValue = this.facetState.selectedValueAncestry.find((value)=>'selected' === value.state);
            if (selectedValue) return html`${map(selectedValue.children, (value, i)=>this.renderChild(value, 0 === i, i === this.resultIndexToFocusOnShowMore))}`;
        }
        return html`${map(this.facetState.valuesAsTrees, (value, i)=>this.renderChild(value, 0 === i, i === this.resultIndexToFocusOnShowMore))}`;
    }
    renderSearchResults() {
        return renderCategoryFacetSearchResultsContainer()(html`${map(this.facetState.facetSearch.values, (value)=>renderCategoryFacetSearchValue({
                props: {
                    value,
                    field: this.field,
                    facetId: this.facetId,
                    searchQuery: this.facetState.facetSearch.query,
                    i18n: this.bindings.i18n,
                    onClick: ()=>{
                        this.focusTargets.activeValueFocus.focusAfterSearch();
                        this.facet.facetSearch.select(value);
                    }
                }
            }))}`);
    }
    renderMatches() {
        return renderFacetSearchMatches({
            props: {
                i18n: this.bindings.i18n,
                query: this.facetState.facetSearch.query,
                numberOfMatches: this.facetState.facetSearch.values.length,
                hasMoreMatches: this.facetState.facetSearch.moreValuesAvailable,
                showMoreMatches: ()=>this.facet.facetSearch.showMoreResults()
            }
        });
    }
    renderShowMoreLess() {
        return html`
      <div class=${this.hasParents ? 'pl-9' : ''}>
        ${renderFacetShowMoreLess({
            props: {
                label: this.label,
                i18n: this.bindings.i18n,
                onShowMore: ()=>{
                    const selectedValue = this.facetState.selectedValueAncestry.find((value)=>'selected' === value.state);
                    this.resultIndexToFocusOnShowMore = selectedValue?.children.length ?? this.facetState.valuesAsTrees.length;
                    this.focusTargets.showMoreFocus.focusAfterSearch();
                    this.facet.showMoreValues();
                },
                onShowLess: ()=>{
                    this.focusTargets.showLessFocus.focusAfterSearch();
                    this.facet.showLessValues();
                },
                canShowLessValues: this.facetState.canShowLessValues,
                canShowMoreValues: this.facetState.canShowMoreValues
            }
        })}
      </div>
    `;
    }
    render() {
        if (!this.facetState || !this.searchStatusState) return nothing;
        const { bindings: { i18n }, label, facetState: { facetSearch, enabled, valuesAsTrees, selectedValueAncestry }, searchStatusState: { hasError, firstSearchExecuted } } = this;
        if (hasError || !enabled || firstSearchExecuted && !valuesAsTrees.length) return nothing;
        if (!firstSearchExecuted) return html`${renderFacetPlaceholder({
            props: {
                numberOfValues: this.numberOfValues,
                isCollapsed: this.isCollapsed
            }
        })}`;
        return renderFacetContainer()(html`
      ${this.renderHeader()}
      ${when(!this.isCollapsed, ()=>html`
          ${this.renderSearchInput()}
          ${when(shouldDisplaySearchResults(facetSearch), ()=>html`
              ${when(facetSearch.values.length > 0, ()=>renderFacetValuesGroup({
                        props: {
                            i18n,
                            label,
                            query: facetSearch.query
                        }
                    })(this.renderSearchResults()), ()=>html`<div class="mt-3"></div>`)}
              ${this.renderMatches()}
            `, ()=>html`
              ${renderFacetValuesGroup({
                    props: {
                        i18n,
                        label
                    }
                })(when(this.hasParents, ()=>html`
                    ${renderCategoryFacetParentAsTreeContainer({
                        props: {
                            isTopLevel: true,
                            className: 'mt-3'
                        }
                    })(this.renderValuesTree(selectedValueAncestry, true))}
                  `, ()=>html`
                    ${renderCategoryFacetChildrenAsTreeContainer({
                        props: {
                            className: 'mt-3'
                        }
                    })(this.renderChildren())}
                  `))}
              ${this.renderShowMoreLess()}
            `)}
        `)}
    `);
    }
    constructor(){
        super(), this.resultIndexToFocusOnShowMore = 0, this.label = 'no-label', this.tabsIncluded = [], this.tabsExcluded = [], this.numberOfValues = 8, this.withSearch = false, this.sortCriteria = 'occurrences', this.delimitingCharacter = ';', this.basePath = [], this.filterByBasePath = true, this.isCollapsed = false, this.headingLevel = 0, this.filterFacetCount = true, this.injectionDepth = 1000, this.facetSearchAriaMessage = new AriaLiveRegionController(this, 'facet-search');
        new ValidatePropsController(this, ()=>({
                field: this.field,
                numberOfValues: this.numberOfValues,
                sortCriteria: this.sortCriteria,
                headingLevel: this.headingLevel,
                injectionDepth: this.injectionDepth,
                delimitingCharacter: this.delimitingCharacter
            }), AtomicCategoryFacet.propsSchema, false);
    }
}
AtomicCategoryFacet.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    }),
    numberOfValues: new NumberValue({
        min: 1
    }),
    sortCriteria: new StringValue({
        constrainTo: [
            'alphanumeric',
            'occurrences'
        ]
    }),
    headingLevel: new NumberValue({
        min: 0,
        max: 6
    }),
    injectionDepth: new NumberValue({
        min: 0
    }),
    delimitingCharacter: new StringValue()
});
AtomicCategoryFacet.styles = [
    facet_common_tw_css,
    facet_search_tw_css,
    css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */[part~=active-parent],[part~=parents] [part~=values]{padding-left:calc(var(--spacing,.25rem)*9)}[part~=all-categories-button],[part~=parent-button]{align-items:center;display:flex;padding-block:calc(var(--spacing,.25rem)*2.5);padding-left:calc(var(--spacing,.25rem)*7);padding-right:calc(var(--spacing,.25rem)*2);position:relative;text-align:left;width:100%}[part~=back-arrow]{height:calc(var(--spacing,.25rem)*5);left:calc(var(--spacing,.25rem)*1);position:absolute;width:calc(var(--spacing,.25rem)*5)}`
];
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicCategoryFacet.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCategoryFacet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('facet'),
    state(),
    _ts_metadata("design:type", "u" < typeof CategoryFacetState ? Object : CategoryFacetState)
], AtomicCategoryFacet.prototype, "facetState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicCategoryFacet.prototype, "searchStatusState", void 0);
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicCategoryFacet.prototype, "tabManagerState", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'facet-id'
    }),
    _ts_metadata("design:type", String)
], AtomicCategoryFacet.prototype, "facetId", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicCategoryFacet.prototype, "label", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCategoryFacet.prototype, "field", void 0);
_ts_decorate([
    property({
        type: Array,
        reflect: true,
        attribute: 'tabs-included',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicCategoryFacet.prototype, "tabsIncluded", void 0);
_ts_decorate([
    property({
        type: Array,
        reflect: true,
        attribute: 'tabs-excluded',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicCategoryFacet.prototype, "tabsExcluded", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: Number,
        attribute: 'number-of-values'
    })
], AtomicCategoryFacet.prototype, "numberOfValues", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'with-search',
        converter: booleanConverter
    })
], AtomicCategoryFacet.prototype, "withSearch", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'sort-criteria'
    }),
    _ts_metadata("design:type", "u" < typeof CategoryFacetSortCriterion ? Object : CategoryFacetSortCriterion)
], AtomicCategoryFacet.prototype, "sortCriteria", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'delimiting-character'
    })
], AtomicCategoryFacet.prototype, "delimitingCharacter", void 0);
_ts_decorate([
    property({
        type: Array,
        reflect: true,
        attribute: 'base-path',
        converter: arrayConverter
    }),
    _ts_metadata("design:type", Array)
], AtomicCategoryFacet.prototype, "basePath", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'filter-by-base-path',
        converter: booleanConverter
    })
], AtomicCategoryFacet.prototype, "filterByBasePath", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'is-collapsed',
        converter: booleanConverter
    })
], AtomicCategoryFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: Number,
        attribute: 'heading-level'
    })
], AtomicCategoryFacet.prototype, "headingLevel", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'filter-facet-count',
        converter: booleanConverter
    })
], AtomicCategoryFacet.prototype, "filterFacetCount", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: Number,
        attribute: 'injection-depth'
    })
], AtomicCategoryFacet.prototype, "injectionDepth", void 0);
_ts_decorate([
    mapProperty({
        attributePrefix: 'depends-on'
    }),
    _ts_metadata("design:type", "u" < typeof Record ? Object : Record)
], AtomicCategoryFacet.prototype, "dependsOn", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCategoryFacet.prototype, "render", null);
AtomicCategoryFacet = _ts_decorate([
    customElement('atomic-category-facet'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicCategoryFacet);
export { AtomicCategoryFacet };
