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 { renderFacetContainer } from "../../common/facets/facet-container/facet-container.js";
import { renderFacetHeader } from "../../common/facets/facet-header/facet-header.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 { 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 { 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 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 { announceFacetSearchResultsWithAriaLive } from "../../common/facets/facet-search/facet-search-aria-live.js";
import { shouldDisplaySearchResults, shouldUpdateFacetSearchComponent } from "../../common/facets/facet-search/facet-search-utils.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";
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 AtomicCommerceFacet extends LitElement {
    initialize() {
        this.validateFacet();
        this.initFocusTargets();
        this.ensureSubscribed();
        this.facet && this.initAriaLive();
    }
    disconnectedCallback() {
        this.unsubscribeFacetController?.();
        this.unsubscribeFacetController = void 0;
        super.disconnectedCallback();
    }
    shouldUpdate(changedProperties) {
        const prev = changedProperties.get('facetState');
        const next = this.facetState;
        if (this.isFacetState(prev, 'facetState') && this.isFacetState(next, 'facetState')) return shouldUpdateFacetSearchComponent(next.facetSearch, prev.facetSearch);
        return true;
    }
    renderHeader() {
        return renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName,
                numberOfActiveValues: this.activeValues.length,
                isCollapsed: this.isCollapsed,
                headingLevel: 0,
                onToggleCollapse: ()=>{
                    this.isCollapsed = !this.isCollapsed;
                },
                onClearFilters: ()=>{
                    this.focusTargets.header.focusAfterSearch();
                    this.facet.deselectAll();
                },
                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: true
        }, ()=>html`${renderFacetSearchInput({
                props: {
                    i18n: this.bindings.i18n,
                    label: this.displayName,
                    query: this.facetState.facetSearch.query,
                    onClear: ()=>this.facet.facetSearch.clear(),
                    onChange: (value)=>{
                        if ('' === value) return void this.facet.facetSearch.clear();
                        this.facet.facetSearch.updateText(value);
                        this.facet.facetSearch.search();
                    }
                }
            })}`)}
      ${shouldDisplaySearchResults(this.facetState.facetSearch) ? [
            this.renderSearchResults(),
            this.renderMatches()
        ] : [
            this.renderValues(),
            this.renderShowMoreLess()
        ]}
    `;
    }
    renderValuesContainer(children, query) {
        return renderFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName,
                query
            }
        })(html`<ul part="values" class="mt-3">
        ${children}
      </ul>`);
    }
    renderSearchResults() {
        return this.renderValuesContainer(this.facetState.facetSearch.values.map((value)=>html`${renderFacetValue({
                props: {
                    ...this.facetValueProps,
                    facetState: 'idle',
                    facetCount: value.count,
                    onExclude: ()=>this.facet.facetSearch.exclude(value),
                    onSelect: ()=>this.facet.facetSearch.select(value),
                    facetValue: value.rawValue
                }
            })}`));
    }
    renderValues() {
        return this.renderValuesContainer(this.facetState.values.map((value, i)=>{
            const shouldFocusAfterInteraction = 0 === i;
            return renderFacetValue({
                props: {
                    ...this.facetValueProps,
                    facetCount: value.numberOfResults,
                    onExclude: ()=>this.facet.toggleExclude(value),
                    onSelect: ()=>this.facet.toggleSelect(value),
                    facetValue: value.value,
                    facetState: value.state,
                    setRef: (btn)=>{
                        if (shouldFocusAfterInteraction) this.showLessFocus?.setTarget(btn);
                        if (shouldFocusAfterInteraction) this.showMoreFocus?.setTarget(btn);
                    }
                }
            });
        }));
    }
    renderShowMoreLess() {
        return html`
      ${renderFacetShowMoreLess({
            props: {
                label: this.displayName,
                i18n: this.bindings.i18n,
                canShowLessValues: this.facetState.canShowLessValues,
                canShowMoreValues: this.facetState.canShowMoreValues,
                onShowLess: ()=>{
                    this.focusTargets.showLess.focusAfterSearch();
                    this.facet.showLessValues();
                },
                onShowMore: ()=>{
                    this.focusTargets.showMore.focusAfterSearch();
                    this.facet.showMoreValues();
                }
            }
        })}
    `;
    }
    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()
            }
        });
    }
    get activeValues() {
        return this.facetState.values.filter(({ state })=>'idle' !== state);
    }
    get displayName() {
        return this.facetState.displayName || 'no-label';
    }
    get facetValueProps() {
        return {
            facetSearchQuery: this.facetState.facetSearch.query,
            displayValuesAs: 'checkbox',
            enableExclusion: false,
            field: this.facetState.field,
            i18n: this.bindings.i18n
        };
    }
    initFocusTargets() {
        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);
    }
    initAriaLive() {
        announceFacetSearchResultsWithAriaLive(this.facet, this.displayName, (msg)=>{
            this.ariaLiveRegion.message = msg;
        }, this.bindings.i18n);
    }
    get focusTargets() {
        return {
            showLess: this.showLessFocus,
            showMore: this.showMoreFocus,
            header: this.headerFocus
        };
    }
    isFacetState(state, propName) {
        return 'facetState' === propName && 'string' == typeof state?.facetId;
    }
    ensureSubscribed() {
        if (this.unsubscribeFacetController) return;
        this.unsubscribeFacetController = this.facet?.subscribe(()=>{
            this.facetState = this.facet.state;
        });
    }
    render() {
        const { hasError, firstRequestExecuted } = this.summaryState;
        return html`
      ${when(!hasError && firstRequestExecuted && this.facetState.values.length > 0, ()=>renderFacetContainer()(html`${this.renderHeader()} ${this.renderBody()}`))}
    `;
    }
    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-facet>.');
    }
    constructor(...args){
        super(...args), this.isCollapsed = false, this.ariaLiveRegion = new AriaLiveRegionController(this, 'facet-search');
    }
}
AtomicCommerceFacet.styles = [
    facet_value_checkbox_tw_css,
    facet_search_tw_css,
    facet_common_tw_css,
    facet_value_exclude_tw_css,
    facet_value_box_tw_css
];
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Summary ? Object : Summary)
], AtomicCommerceFacet.prototype, "summary", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof RegularFacet ? Object : RegularFacet)
], AtomicCommerceFacet.prototype, "facet", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        converter: booleanConverter,
        attribute: 'is-collapsed'
    })
], AtomicCommerceFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceFacet.prototype, "field", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceFacet.prototype, "bindings", void 0);
_ts_decorate([
    bindStateToController('summary'),
    decorators_js_state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceFacet.prototype, "summaryState", void 0);
_ts_decorate([
    bindStateToController('facet'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof RegularFacetState ? Object : RegularFacetState)
], AtomicCommerceFacet.prototype, "facetState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceFacet.prototype, "error", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceFacet.prototype, "render", null);
AtomicCommerceFacet = _ts_decorate([
    customElement('atomic-commerce-facet'),
    bindings(),
    withTailwindStyles
], AtomicCommerceFacet);
export { AtomicCommerceFacet };
