import { NumberValue, Schema } from "@coveo/bueno";
import { buildPager, buildSearchStatus } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { keyed } from "lit/directives/keyed.js";
import { when } from "lit/directives/when.js";
import { createAppLoadedListener } from "../../common/interface/store.js";
import { renderPageButtons, renderPagerNextButton, renderPagerPageButton, renderPagerPreviousButton } from "../../common/pager/pager-buttons.js";
import { renderPagerNavigation } from "../../common/pager/pager-navigation.js";
import { getCurrentPagesRange } from "../../common/pager/pager-utils.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.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 { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import { buildCustomEvent } from "../../../utils/event-utils.js";
import { randomID } from "../../../utils/utils.js";
import arrow_left_rounded from "../../../images/arrow-left-rounded.js";
import arrow_right_rounded from "../../../images/arrow-right-rounded.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 AtomicPager extends InitializeBindingsMixin(LitElement) {
    initialize() {
        this.initFocusTargets();
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.pager = buildPager(this.bindings.engine, {
            options: {
                numberOfPages: this.numberOfPages
            }
        });
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    render() {
        const currentGroupName = `${this.radioGroupName}-${this.pagerState.currentPages.join('-')}`;
        const pagesRange = getCurrentPagesRange(this.pagerState.currentPage - 1, this.numberOfPages, this.pagerState.maxPage - 1);
        return html`${when(this.pagerState.maxPage > 1 && this.isAppLoaded, ()=>html` ${renderPagerNavigation({
                props: {
                    i18n: this.bindings.i18n
                }
            })(html`
          ${renderPagerPreviousButton({
                props: {
                    icon: this.previousButtonIcon,
                    disabled: !this.pagerState.hasPreviousPage,
                    i18n: this.bindings.i18n,
                    onClick: async ()=>{
                        this.pager.previousPage();
                        await this.focusOnFirstResultAndScrollToTop();
                    },
                    ref: (el)=>this.previousButton.setTarget(el)
                }
            })}
          ${renderPageButtons({
                props: {
                    i18n: this.bindings.i18n
                }
            })(html` ${pagesRange.map((pageNumber, index)=>keyed(`page-${pageNumber}-${index}`, renderPagerPageButton({
                    props: {
                        isSelected: pageNumber === this.pager.state.currentPage - 1,
                        ariaLabel: this.bindings.i18n.t('page-number', {
                            pageNumber: pageNumber + 1
                        }),
                        onChecked: async ()=>{
                            this.pager.selectPage(pageNumber + 1);
                            await this.focusOnFirstResultAndScrollToTop();
                        },
                        page: pageNumber,
                        groupName: currentGroupName,
                        text: (pageNumber + 1).toLocaleString(this.bindings.i18n.language),
                        onFocusCallback: this.handleFocus
                    }
                })))}`)}
          ${renderPagerNextButton({
                props: {
                    icon: this.nextButtonIcon,
                    disabled: !this.pagerState.hasNextPage,
                    i18n: this.bindings.i18n,
                    onClick: async ()=>{
                        this.pager.nextPage();
                        await this.focusOnFirstResultAndScrollToTop();
                    },
                    ref: (el)=>this.nextButton.setTarget(el)
                }
            })}
        `)}`)}`;
    }
    initFocusTargets() {
        if (!this.previousButton) this.previousButton = new FocusTargetController(this, this.bindings);
        if (!this.nextButton) this.nextButton = new FocusTargetController(this, this.bindings);
    }
    async focusOnFirstResultAndScrollToTop() {
        await this.bindings.store.state.resultList?.focusOnFirstResultAfterNextSearch();
        this.dispatchEvent(buildCustomEvent('atomic/scrollToTop'));
        this.announcePageLoaded();
    }
    announcePageLoaded() {
        this.ariaMessage.message = this.bindings.i18n.t('pager-page-loaded', {
            page: this.pagerState.currentPage
        });
    }
    constructor(){
        super(), this.isAppLoaded = false, this.numberOfPages = 5, this.previousButtonIcon = arrow_left_rounded, this.nextButtonIcon = arrow_right_rounded, this.ariaMessage = new AriaLiveRegionController(this, 'atomic-pager'), this.radioGroupName = randomID('atomic-pager-'), this.handleFocus = async (elements, currentFocus, newFocus)=>{
            const currentIndex = elements.indexOf(currentFocus);
            const newIndex = elements.indexOf(newFocus);
            if (currentIndex === elements.length - 1 && 0 === newIndex) await this.nextButton.focus();
            else if (0 === currentIndex && newIndex === elements.length - 1) await this.previousButton.focus();
            else newFocus.focus();
        };
        new ValidatePropsController(this, ()=>({
                numberOfPages: this.numberOfPages
            }), AtomicPager.propsSchema);
    }
}
AtomicPager.propsSchema = new Schema({
    numberOfPages: new NumberValue({
        min: 0
    })
});
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicPager.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicPager.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicPager.prototype, "isAppLoaded", void 0);
_ts_decorate([
    bindStateToController('pager'),
    state(),
    _ts_metadata("design:type", "u" < typeof PagerState ? Object : PagerState)
], AtomicPager.prototype, "pagerState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof SearchStatusState ? Object : SearchStatusState)
], AtomicPager.prototype, "searchStatusState", void 0);
_ts_decorate([
    property({
        reflect: true,
        useDefault: true,
        attribute: 'number-of-pages',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicPager.prototype, "numberOfPages", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'previous-button-icon',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicPager.prototype, "previousButtonIcon", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'next-button-icon',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicPager.prototype, "nextButtonIcon", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicPager.prototype, "render", null);
AtomicPager = _ts_decorate([
    customElement('atomic-pager'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicPager);
export { AtomicPager };
