import { deserializeRelativeDate } from "@coveo/headless/commerce";
import { LitElement, html } 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 { renderFacetValueLabelHighlight } from "../../common/facets/facet-value-label-highlight/facet-value-label-highlight.js";
import { renderFacetValueLink } from "../../common/facets/facet-value-link/facet-value-link.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 { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { FocusTargetController } from "../../../utils/accessibility-utils.js";
import { parseDate } from "../../../utils/date-utils.js";
import "../../common/atomic-facet-date-input/atomic-facet-date-input.js";
import { bindings } from "../../../decorators/bindings.js";
import { shouldDisplayInputForFacetRange } from "../../common/facets/facet-common.js";
import facet_common_tw_css from "../../common/facets/facet-common.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 AtomicCommerceTimeframeFacet extends LitElement {
    get displayName() {
        return this.facetState.displayName || 'no-label';
    }
    get focusTarget() {
        if (!this.headerFocus) this.headerFocus = new FocusTargetController(this, this.bindings);
        return this.headerFocus;
    }
    initialize() {
        this.validateFacet();
    }
    applyDateInput(event) {
        this.inputRange = {
            start: event.detail.start,
            end: event.detail.end
        };
    }
    get valuesToRender() {
        return this.facetState.values.filter((value)=>value.numberOfResults || 'idle' !== value.state) || [];
    }
    get shouldRenderValues() {
        return !this.hasInputRange && !!this.valuesToRender.length;
    }
    get shouldRenderFacet() {
        return this.shouldRenderInput || this.shouldRenderValues;
    }
    get shouldRenderInput() {
        const { firstRequestExecuted: firstSearchExecuted, hasError, isLoading, hasProducts: hasResults } = this.summaryState;
        return shouldDisplayInputForFacetRange({
            hasInputRange: this.hasInputRange,
            searchStatusState: {
                firstSearchExecuted,
                hasError,
                hasResults,
                isLoading
            },
            facetValues: this.facetState.values || [],
            hasInput: true
        });
    }
    get numberOfSelectedValues() {
        if (this.hasInputRange) return 1;
        return this.facetState.values.filter(({ state })=>'selected' === state).length || 0;
    }
    get hasInputRange() {
        return !!this.inputRange;
    }
    resetRange() {
        this.inputRange = void 0;
        this.facet.setRanges([]);
    }
    formatFacetValue(facetValue) {
        try {
            const startDate = deserializeRelativeDate(facetValue.start);
            const relativeDate = 'past' === startDate.period ? startDate : deserializeRelativeDate(facetValue.end);
            return this.bindings.i18n.t(`${relativeDate.period}-${relativeDate.unit}`, {
                count: relativeDate.amount
            });
        } catch (_error) {
            return this.bindings.i18n.t('to', {
                start: parseDate(facetValue.start).format('YYYY-MM-DD'),
                end: parseDate(facetValue.end).format('YYYY-MM-DD')
            });
        }
    }
    renderValues() {
        return this.renderValuesContainer(this.valuesToRender.map((value)=>this.renderValue(value)));
    }
    renderValue(facetValue) {
        const displayValue = this.formatFacetValue(facetValue);
        const isSelected = 'selected' === facetValue.state;
        const isExcluded = 'excluded' === facetValue.state;
        return renderFacetValueLink({
            props: {
                displayValue,
                isSelected,
                numberOfResults: facetValue.numberOfResults,
                i18n: this.bindings.i18n,
                onClick: ()=>this.facet.toggleSingleSelect(facetValue)
            }
        })(renderFacetValueLabelHighlight({
            props: {
                displayValue,
                isSelected,
                isExcluded
            }
        }));
    }
    renderValuesContainer(children) {
        return renderFacetValuesGroup({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName
            }
        })(html`<ul class="mt-3" part="values">
        ${children}
      </ul>`);
    }
    renderHeader() {
        return renderFacetHeader({
            props: {
                i18n: this.bindings.i18n,
                label: this.displayName,
                onClearFilters: ()=>{
                    this.focusTarget.focusAfterSearch();
                    if (this.hasInputRange) return void this.resetRange();
                    this.facet.deselectAll();
                },
                numberOfActiveValues: this.numberOfSelectedValues,
                isCollapsed: this.isCollapsed,
                headingLevel: 0,
                onToggleCollapse: ()=>{
                    this.isCollapsed = !this.isCollapsed;
                },
                headerRef: (el)=>this.focusTarget.setTarget(el)
            }
        });
    }
    renderDateInput() {
        return html`
      <atomic-facet-date-input
        .label=${this.displayName}
        .inputRange=${this.inputRange}
        .facetId=${this.facetState.facetId}
        @atomic-date-input-apply=${(event)=>{
            const { start, end, endInclusive } = event.detail;
            this.facet.setRanges([
                {
                    start,
                    end,
                    endInclusive,
                    state: 'selected'
                }
            ]);
            this.applyDateInput(event);
        }}
      ></atomic-facet-date-input>
    `;
    }
    render() {
        const { hasError, firstRequestExecuted } = this.summaryState;
        return html`${when(!hasError && firstRequestExecuted && this.shouldRenderFacet, ()=>renderFacetContainer()(html`${this.renderHeader()}
          ${when(!this.isCollapsed, ()=>html`
              ${when(this.shouldRenderValues, ()=>this.renderValues())}
              ${when(this.shouldRenderInput, ()=>this.renderDateInput())}
            `)}`))}`;
    }
    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-timeframe-facet>.');
    }
    constructor(...args){
        super(...args), this.isCollapsed = false;
    }
}
AtomicCommerceTimeframeFacet.styles = facet_common_tw_css;
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof Summary ? Object : Summary)
], AtomicCommerceTimeframeFacet.prototype, "summary", void 0);
_ts_decorate([
    property({
        type: Object
    }),
    _ts_metadata("design:type", "u" < typeof DateFacet ? Object : DateFacet)
], AtomicCommerceTimeframeFacet.prototype, "facet", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        converter: booleanConverter,
        attribute: 'is-collapsed'
    })
], AtomicCommerceTimeframeFacet.prototype, "isCollapsed", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicCommerceTimeframeFacet.prototype, "field", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommerceTimeframeFacet.prototype, "bindings", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceTimeframeFacet.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('summary'),
    decorators_js_state(),
    _ts_metadata("design:type", Object)
], AtomicCommerceTimeframeFacet.prototype, "summaryState", void 0);
_ts_decorate([
    bindStateToController('facet'),
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof DateFacetState ? Object : DateFacetState)
], AtomicCommerceTimeframeFacet.prototype, "facetState", void 0);
_ts_decorate([
    decorators_js_state(),
    _ts_metadata("design:type", "u" < typeof DateFilterRange ? Object : DateFilterRange)
], AtomicCommerceTimeframeFacet.prototype, "inputRange", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceTimeframeFacet.prototype, "render", null);
AtomicCommerceTimeframeFacet = _ts_decorate([
    customElement('atomic-commerce-timeframe-facet'),
    bindings(),
    withTailwindStyles
], AtomicCommerceTimeframeFacet);
export { AtomicCommerceTimeframeFacet };
