/**
 * Alpine Pagination Component
 */
export function registerPagination(Alpine) {
    Alpine.data('pagination', (currentPage = 1, pageSize = 10, totalItems = 0) => ({
        page: currentPage,
        pageSize,
        totalItems,
        totalPages: Math.max(1, Math.ceil(totalItems / pageSize)),

        init() {
            this.totalPages = Math.max(1, Math.ceil(this.totalItems / this.pageSize));
        },

        get startItem() { return this.totalItems === 0 ? 0 : (this.page - 1) * this.pageSize + 1; },
        get endItem() { return Math.min(this.page * this.pageSize, this.totalItems); },
        get hasPrev() { return this.page > 1; },
        get hasNext() { return this.page < this.totalPages; },

        goTo(p) { this.page = Math.max(1, Math.min(p, this.totalPages)); this._dispatch(); },
        prev() { if (this.hasPrev) { this.page--; this._dispatch(); } },
        next() { if (this.hasNext) { this.page++; this._dispatch(); } },
        setPageSize(s) {
            this.pageSize = parseInt(s, 10) || 10;
            this.totalPages = Math.max(1, Math.ceil(this.totalItems / this.pageSize));
            this.page = 1;
            this._dispatch();
        },
        update(total, perPage, current) {
            this.totalItems = total;
            this.pageSize = perPage || this.pageSize;
            this.page = current || this.page;
            this.totalPages = Math.max(1, Math.ceil(this.totalItems / this.pageSize));
        },

        _dispatch() {
            this.$el.dispatchEvent(new CustomEvent('pagination-change', {
                detail: { page: this.page, pageSize: this.pageSize },
            }));
        },
    }));
}
