import { buildResultsPerPage, buildSearchStatus } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { renderFieldsetGroup } from "../../common/fieldset-group.js";
import { createAppLoadedListener } from "../../common/interface/store.js";
import { renderChoices } from "../../common/items-per-page/choices.js";
import { ChoiceIsNaNError, InitialChoiceNotInChoicesError } from "../../common/items-per-page/error.js";
import { renderLabel } from "../../common/items-per-page/label.js";
import { convertChoicesToNumbers, validateInitialChoice } from "../../common/items-per-page/validate.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 { InitializeBindingsMixin } from "../../../mixins/bindings-mixin.js";
import { buildCustomEvent } from "../../../utils/event-utils.js";
import { randomID } from "../../../utils/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 AtomicResultsPerPage extends InitializeBindingsMixin(LitElement) {
    initialize() {
        try {
            this.choices = convertChoicesToNumbers(this.choicesDisplayed);
            this.initialChoice = this.initialChoice ?? this.choices[0];
            validateInitialChoice(this.initialChoice, this.choices);
        } catch (error) {
            if (error instanceof ChoiceIsNaNError || error instanceof InitialChoiceNotInChoicesError) {
                this.bindings.engine.logger.error(error.message);
                throw error;
            }
        }
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.resultPerPage = buildResultsPerPage(this.bindings.engine, {
            initialState: {
                numberOfResults: this.initialChoice
            }
        });
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    scrollToTopEvent() {
        this.dispatchEvent(buildCustomEvent('atomic/scrollToTop'));
    }
    get label() {
        return this.bindings.i18n.t('results-per-page');
    }
    render() {
        if (!this.searchStatusState) return html``;
        return html`
      ${when(!this.searchStatusState.hasError && this.isAppLoaded && this.searchStatusState.hasResults, ()=>html`
          <div class="flex items-center">
            ${renderLabel()(html`${this.label}`)}
            ${renderFieldsetGroup({
                props: {
                    label: this.label
                }
            })(renderChoices({
                props: {
                    label: this.label,
                    groupName: this.radioGroupName,
                    pageSize: this.resultPerPageState.numberOfResults,
                    choices: this.choices,
                    lang: this.bindings.i18n.language,
                    scrollToTopEvent: ()=>this.scrollToTopEvent(),
                    setItemSize: (size)=>this.resultPerPage.set(size),
                    focusOnFirstResultAfterNextSearch: ()=>this.bindings.store.state.resultList?.focusOnFirstResultAfterNextSearch(),
                    focusOnNextNewResult: ()=>this.bindings.store.state.resultList?.focusOnNextNewResult()
                }
            }))}
          </div>
        `)}
    `;
    }
    constructor(...args){
        super(...args), this.radioGroupName = randomID('atomic-results-per-page-'), this.isAppLoaded = false, this.choicesDisplayed = '10,25,50,100';
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultsPerPage.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultsPerPage.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('resultPerPage'),
    state(),
    _ts_metadata("design:type", "u" < typeof ResultsPerPageState ? Object : ResultsPerPageState)
], AtomicResultsPerPage.prototype, "resultPerPageState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicResultsPerPage.prototype, "searchStatusState", void 0);
_ts_decorate([
    state()
], AtomicResultsPerPage.prototype, "isAppLoaded", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'choices-displayed'
    })
], AtomicResultsPerPage.prototype, "choicesDisplayed", void 0);
_ts_decorate([
    property({
        type: Number,
        reflect: true,
        attribute: 'initial-choice'
    }),
    _ts_metadata("design:type", Number)
], AtomicResultsPerPage.prototype, "initialChoice", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultsPerPage.prototype, "render", null);
AtomicResultsPerPage = _ts_decorate([
    customElement('atomic-results-per-page'),
    bindings(),
    withTailwindStyles
], AtomicResultsPerPage);
export { AtomicResultsPerPage };
