import { NumberValue, Schema } from "@coveo/bueno";
import { buildProductListing, buildSearch } from "@coveo/headless/commerce";
import { LitElement, 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 { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import "../../common/atomic-facet-placeholder/atomic-facet-placeholder.js";
import { createAppLoadedListener } from "../../common/interface/store.js";
import "../atomic-commerce-category-facet/atomic-commerce-category-facet.js";
import "../atomic-commerce-facet/atomic-commerce-facet.js";
import "../atomic-commerce-numeric-facet/atomic-commerce-numeric-facet.js";
import "../atomic-commerce-timeframe-facet/atomic-commerce-timeframe-facet.js";
import { keyed } from "lit/directives/keyed.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { LightDomMixin } from "../../../mixins/light-dom.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 AtomicCommerceFacets extends LightDomMixin(LitElement) {
    initialize() {
        this.validateProps();
        const controller = this.controllerBuilder(this.bindings.engine);
        this.facetGenerator = controller.facetGenerator();
        this.summary = controller.summary();
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    isProductListing() {
        return 'product-listing' === this.bindings.interfaceElement.type;
    }
    get controllerBuilder() {
        return this.isProductListing() ? buildProductListing : buildSearch;
    }
    validateProps() {
        new Schema({
            collapseFacetsAfter: new NumberValue({
                min: -1,
                required: true
            })
        }).validate({
            collapseFacetsAfter: this.collapseFacetsAfter
        });
    }
    shouldCollapseFacet(index, facet) {
        if (-1 === this.collapseFacetsAfter || facet.state.hasActiveValues) return false;
        return this.collapseFacetsAfter ? index + 1 > this.collapseFacetsAfter : true;
    }
    renderFacetPlaceholders() {
        return map(Array.from({
            length: this.collapseFacetsAfter
        }), ()=>html`<atomic-facet-placeholder
          value-count="8"
        ></atomic-facet-placeholder>`);
    }
    renderFacets() {
        return map(this.facetGenerator.facets, (facet, index)=>{
            if (0 === facet.state.values.length) return nothing;
            const isCollapsed = this.shouldCollapseFacet(index, facet);
            switch(facet.state.type){
                case 'regular':
                    return html`${keyed(facet.state.facetId, html`
              <atomic-commerce-facet
                .isCollapsed=${isCollapsed}
                .summary=${this.summary}
                .facet=${facet}
                .field=${facet.state.field}
              ></atomic-commerce-facet>
            `)} `;
                case 'numericalRange':
                    return html`${keyed(facet.state.facetId, html`<atomic-commerce-numeric-facet
              .isCollapsed=${isCollapsed}
              .summary=${this.summary}
              .facet=${facet}
              .field=${facet.state.field}
            ></atomic-commerce-numeric-facet>`)}`;
                case 'dateRange':
                    return html`${keyed(facet.state.facetId, html`<atomic-commerce-timeframe-facet
              .isCollapsed=${isCollapsed}
              .summary=${this.summary}
              .facet=${facet}
              .field=${facet.state.field}
            ></atomic-commerce-timeframe-facet>`)}`;
                case 'hierarchical':
                    return html`${keyed(facet.state.facetId, html`<atomic-commerce-category-facet
              .isCollapsed=${isCollapsed}
              .summary=${this.summary}
              .facet=${facet}
              .field=${facet.state.field}
            ></atomic-commerce-category-facet>`)}`;
                default:
                    this.bindings.engine.logger.warn('Unexpected facet type.');
                    return nothing;
            }
        });
    }
    render() {
        return html`${when(this.isAppLoaded, ()=>this.renderFacets(), ()=>this.renderFacetPlaceholders())}`;
    }
    constructor(...args){
        super(...args), this.collapseFacetsAfter = 4, this.isAppLoaded = false;
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceFacets.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceFacets.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('facetGenerator'),
    state(),
    _ts_metadata("design:type", Array)
], AtomicCommerceFacets.prototype, "facetGeneratorState", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'collapse-facets-after',
        type: Number
    })
], AtomicCommerceFacets.prototype, "collapseFacetsAfter", void 0);
_ts_decorate([
    state()
], AtomicCommerceFacets.prototype, "isAppLoaded", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceFacets.prototype, "render", null);
AtomicCommerceFacets = _ts_decorate([
    customElement('atomic-commerce-facets'),
    bindings()
], AtomicCommerceFacets);
export { AtomicCommerceFacets };
