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 { 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 { 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 { 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 { getFieldValueCaption } from "../../../utils/field-utils.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 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";
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 AtomicCommerceCategoryFacet extends LitElement {
    initialize() {
        this.validateFacet();
        this.facet && announceFacetSearchResultsWithAriaLive(this.facet, this.displayName, (msg)=>{
            this.facetSearchAriaMessage.message = msg;
        }, this.bindings.i18n);
    }
    get displayName() {
        return this.facetState?.displayName || 'no-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);
        if (!this.activeValueFocus) this.activeValueFocus = new FocusTargetController(this, this.bindings);
        return {
            showLessFocus: this.showLessFocus,
            showMoreFocus: this.showMoreFocus,
            headerFocus: this.headerFocus,
            activeValueFocus: this.activeValueFocus
        };
    }
    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);
    }
    get hasParents() {
        return !!this.facetState.selectedValueAncestry?.length;
    }
    renderHeader() {
        return renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName,
                numberOfActiveValues: this.facetState.hasActiveValues && this.isCollapsed ? 1 : 0,
                isCollapsed: this.isCollapsed,
                headingLevel: 0,
                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);
                }
            }
        });
    }
    renderValuesTree(parents, isRoot) {
        if (!this.hasParents) return this.renderChildren();
        if (isRoot) return renderCategoryFacetTreeValueContainer()(html`
        ${renderCategoryFacetAllCategoryButton({
            props: {
                i18n: this.bindings.i18n,
                onClick: ()=>{
                    this.focusTargets.activeValueFocus.focusAfterSearch();
                    this.facet.deselectAll();
                },
                facetId: this.facetState.facetId,
                field: this.facet.state.field
            }
        })}
        ${renderCategoryFacetParentAsTreeContainer({
            props: {
                isTopLevel: false
            }
        })(html`${this.renderValuesTree(parents, false)} `)}
      `);
        if (parents.length > 1) {
            const parentValue = parents[0];
            return renderCategoryFacetTreeValueContainer()(html`
        ${renderCategoryFacetParentButton({
                props: {
                    i18n: this.bindings.i18n,
                    field: this.facetState?.field,
                    facetValue: parentValue,
                    onClick: ()=>{
                        this.focusTargets.activeValueFocus.focusAfterSearch();
                        this.facet.toggleSelect(parentValue);
                    }
                }
            })}
        ${renderCategoryFacetParentAsTreeContainer({
                props: {
                    isTopLevel: false
                }
            })(this.renderValuesTree(parents.slice(1), false))}
      `);
        }
        const activeParent = parents[0];
        const activeParentDisplayValue = getFieldValueCaption(this.facetState?.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: {}
        })(html` ${this.renderChildren()}`)}
      `)}
    `;
    }
    renderChild(facetValue, isShowLessFocusTarget, isShowMoreFocusTarget) {
        const displayValue = getFieldValueCaption(this.facetState?.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() {
        const { values, selectedValueAncestry, hasActiveValues } = this.facetState;
        const nextValues = hasActiveValues ? selectedValueAncestry : values;
        const children = nextValues?.length ? hasActiveValues ? nextValues[nextValues.length - 1].children : nextValues : [];
        return html`${map(children, (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.facetState.field,
                    facetId: this.facetState.facetId,
                    searchQuery: this.facetState.facetSearch.query,
                    i18n: this.bindings.i18n,
                    onClick: ()=>{
                        this.focusTargets.activeValueFocus.focusAfterSearch();
                        this.facet.facetSearch.select(value);
                    }
                }
            }))}`);
    }
    renderShowMoreLess() {
        return html`
      <div class=${this.hasParents ? 'pl-9' : ''}>
        ${renderFacetShowMoreLess({
            props: {
                label: this.displayName,
                i18n: this.bindings.i18n,
                onShowMore: ()=>{
                    this.resultIndexToFocusOnShowMore = this.facetState.values.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() {
        const { bindings: { i18n }, facetState: { facetSearch, selectedValueAncestry, values } } = this;
        const { hasError, firstRequestExecuted } = this.summaryState;
        if (!firstRequestExecuted || hasError || 0 === values.length) return nothing;
        return renderFacetContainer()(html`
      ${this.renderHeader()}
      ${when(!this.isCollapsed, ()=>html`
          ${renderFacetSearchInput({
                props: {
                    i18n: this.bindings.i18n,
                    label: this.displayName,
                    query: this.facetState.facetSearch.query,
                    onChange: (value)=>{
                        if ('' === value) return void this.facet.facetSearch.clear();
                        this.facet.facetSearch.updateText(value);
                        this.facet.facetSearch.search();
                    },
                    onClear: ()=>this.facet.facetSearch.clear()
                }
            })}
          ${when(shouldDisplaySearchResults(facetSearch), ()=>html`
              ${when(facetSearch.values.length > 0, ()=>renderFacetValuesGroup({
                        props: {
                            i18n,
                            label: this.displayName,
                            query: facetSearch.query
                        }
                    })(this.renderSearchResults()), ()=>html`<div class="mt-3"></div>`)}
              ${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()
                    }
                })}
            `, ()=>html`
              ${renderFacetValuesGroup({
                    props: {
                        i18n,
                        label: this.displayName
                    }
                })(when(this.hasParents, ()=>html`
                    ${renderCategoryFacetParentAsTreeContainer({
                        props: {
                            isTopLevel: true,
                            className: 'mt-3'
                        }
                    })(html`${when(selectedValueAncestry, ()=>selectedValueAncestry && this.renderValuesTree(selectedValueAncestry, true))}`)}
                  `, ()=>html`
                    ${renderCategoryFacetChildrenAsTreeContainer({
                        props: {
                            className: 'mt-3'
                        }
                    })(this.renderChildren())}
                  `))}
              ${this.renderShowMoreLess()}
            `)}
        `)}
    `);
    }
    updated(changedProps) {
        super.updated(changedProps);
        if (changedProps.has('facet')) this.validateFacet();
    }
    validateFacet() {
        if (!this.facet) this.error = new Error('The "facet" property is required for <atomic-commerce-category-facet>.');
    }
    constructor(...args){
        super(...args), this.isCollapsed = false, this.resultIndexToFocusOnShowMore = 0, this.facetSearchAriaMessage = new AriaLiveRegionController(this, 'facet-search');
    }
}
AtomicCommerceCategoryFacet.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 CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceCategoryFacet.prototype, "bindings", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Summary ? Object : Summary)
], AtomicCommerceCategoryFacet.prototype, "summary", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof CategoryFacet ? Object : CategoryFacet)
], AtomicCommerceCategoryFacet.prototype, "facet", void 0);
_ts_decorate([
    property({
        reflect: true,
        type: Boolean,
        attribute: 'is-collapsed',
        converter: booleanConverter
    })
], AtomicCommerceCategoryFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceCategoryFacet.prototype, "field", void 0);
_ts_decorate([
    state(),
    bindStateToController('facet'),
    _ts_metadata("design:type", "u" < typeof CategoryFacetState ? Object : CategoryFacetState)
], AtomicCommerceCategoryFacet.prototype, "facetState", void 0);
_ts_decorate([
    bindStateToController('summary'),
    state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceCategoryFacet.prototype, "summaryState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceCategoryFacet.prototype, "error", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceCategoryFacet.prototype, "render", null);
AtomicCommerceCategoryFacet = _ts_decorate([
    customElement('atomic-commerce-category-facet'),
    bindings(),
    withTailwindStyles
], AtomicCommerceCategoryFacet);
export { AtomicCommerceCategoryFacet };
