import { NumberValue, Schema } from "@coveo/bueno";
import { buildPager, buildSearchStatus } from "@coveo/headless/insight";
import { LitElement, css, 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 { 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 AtomicInsightPager extends LitElement {
    initialize() {
        this.initFocusTargets();
        this.searchStatus = buildSearchStatus(this.bindings.engine);
        this.pager = buildPager(this.bindings.engine, {
            options: {
                numberOfPages: this.numberOfPages
            }
        });
    }
    render() {
        const pagesRange = getCurrentPagesRange(this.pagerState.currentPage - 1, this.numberOfPages, this.pagerState.maxPage);
        return html`${when(this.pagerState.maxPage > 1, ()=>html`
        ${renderPagerNavigation({
                props: {
                    i18n: this.bindings.i18n
                }
            })(html`
          ${renderPagerPreviousButton({
                props: {
                    icon: arrow_left_rounded,
                    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: this.radioGroupName,
                        text: (pageNumber + 1).toLocaleString(this.bindings.i18n.language),
                        onFocusCallback: this.handleFocus
                    }
                })))}
          `)}
          ${renderPagerNextButton({
                props: {
                    icon: arrow_right_rounded,
                    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', {
            pageNumber: this.pagerState.currentPage
        });
    }
    constructor(){
        super(), this.numberOfPages = 5, this.ariaMessage = new AriaLiveRegionController(this, 'atomic-insight-pager'), this.radioGroupName = randomID('atomic-insight-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
            }), new Schema({
            numberOfPages: new NumberValue({
                min: 0
            })
        }));
    }
}
AtomicInsightPager.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */[part=page-button]{background-color:#0000}:host{align-items:center;background-color:var(--atomic-neutral-light);box-sizing:content-box;display:flex;height:100%;justify-content:center;padding-block:calc(var(--spacing,.25rem)*4);padding-inline:calc(var(--spacing,.25rem)*6)}`;
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightPager.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightPager.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('pager'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightPagerState ? Object : InsightPagerState)
], AtomicInsightPager.prototype, "pagerState", void 0);
_ts_decorate([
    bindStateToController('searchStatus'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightSearchStatusState ? Object : InsightSearchStatusState)
], AtomicInsightPager.prototype, "searchStatusState", void 0);
_ts_decorate([
    property({
        reflect: true,
        attribute: 'number-of-pages',
        type: Number
    }),
    _ts_metadata("design:type", Number)
], AtomicInsightPager.prototype, "numberOfPages", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightPager.prototype, "render", null);
AtomicInsightPager = _ts_decorate([
    customElement('atomic-insight-pager'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicInsightPager);
export { AtomicInsightPager };
