import { NumberValue, Schema } from "@coveo/bueno";
import { buildProductListing, buildSearch } from "@coveo/headless/commerce";
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 { 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 AtomicCommercePager extends LitElement {
    initialize() {
        this.initFocusTargets();
        if ('product-listing' === this.bindings.interfaceElement.type) this.listingOrSearch = buildProductListing(this.bindings.engine);
        else this.listingOrSearch = buildSearch(this.bindings.engine);
        this.pager = this.listingOrSearch.pagination();
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    render() {
        const pagesRange = getCurrentPagesRange(this.pagerState.page, this.numberOfPages, this.pagerState.totalPages - 1);
        return html`
      ${when(this.pagerState.totalPages > 1 && this.isAppLoaded, ()=>html`
          ${renderPagerNavigation({
                props: {
                    i18n: this.bindings.i18n
                }
            })(html`
            ${renderPagerPreviousButton({
                props: {
                    icon: this.previousButtonIcon,
                    disabled: 0 === this.pagerState.page,
                    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.pagerState.page,
                        ariaLabel: this.bindings.i18n.t('page-number', {
                            pageNumber: pageNumber + 1
                        }),
                        onChecked: async ()=>{
                            this.pager.selectPage(pageNumber);
                            await this.focusOnFirstResultAndScrollToTop();
                        },
                        page: pageNumber,
                        groupName: this.radioGroupName,
                        text: (pageNumber + 1).toLocaleString(this.bindings.i18n.language),
                        onFocusCallback: this.handleFocus
                    }
                })))}
            `)}
            ${renderPagerNextButton({
                props: {
                    icon: this.nextButtonIcon,
                    disabled: this.pagerState.page + 1 >= this.pagerState.totalPages,
                    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', {
            pageNumber: this.pagerState.page
        });
    }
    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-commerce-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
            }), AtomicCommercePager.propsSchema);
    }
}
AtomicCommercePager.propsSchema = new Schema({
    numberOfPages: new NumberValue({
        min: 0
    })
});
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicCommercePager.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommercePager.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicCommercePager.prototype, "isAppLoaded", void 0);
_ts_decorate([
    bindStateToController('pager'),
    state(),
    _ts_metadata("design:type", "u" < typeof PaginationState ? Object : PaginationState)
], AtomicCommercePager.prototype, "pagerState", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-pages',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicCommercePager.prototype, "numberOfPages", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'previous-button-icon',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommercePager.prototype, "previousButtonIcon", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'next-button-icon',
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicCommercePager.prototype, "nextButtonIcon", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommercePager.prototype, "render", null);
AtomicCommercePager = _ts_decorate([
    customElement('atomic-commerce-pager'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicCommercePager);
export { AtomicCommercePager };
