var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") 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;
};
import { LitElement, html, nothing } from 'lit';
import { property } from 'lit/decorators.js';
import { EventEmitterMixin } from '../../util/EventEmitterMixin.js';
import { l10n } from '../../util/i18n.js';
import { ReadyMixin } from '../../util/ReadyMixin.js';
import '../circular-progress/CircularProgress.js';
import '../dropdown/Dropdown.js';
import '../dropdown/DropdownItem.js';
import '../dropdown/DropdownMenu.js';
import IconButton from '../icon-button/IconButton.js';
/**
 * A pagination component for navigating through paged content.
 *
 * Supports multiple layout variants (Search, Widget, Widget Small, Calendar)
 * through configurable props and pseudo-slots.
 *
 * **Page size modes:**
 *
 * - **Built-in** (default): When no `slot="page-size"` is provided and `page-size-changer`
 *   is true, Pagination renders its own `btu-dropdown` from the `page-size-options` attribute.
 *   Events, label sync, and page size changes are managed automatically.
 *
 * - **Custom slot**: When a child has `slot="page-size"`, the built-in dropdown is suppressed.
 *   The consumer owns all behavior — event handling, label sync, etc. Use this for non-standard
 *   selectors like a calendar week/month toggle.
 *
 * **Page jumper modes:**
 *
 * - **Built-in**: When `page-jumper` is true and no `slot="jumper"` is provided, Pagination
 *   renders a dropdown with "Page 1" through "Page N" items. Fully reactive — updates
 *   automatically when page, page size, or total items change.
 *
 * - **Custom slot**: When a child has `slot="jumper"`, the built-in dropdown is suppressed.
 *   The consumer owns all behavior. Use this for custom jumper content like a "Today" button.
 *
 * @element btu-pagination
 *
 * @slot page-size - Custom page-size selector (replaces built-in dropdown). Consumer manages all behavior.
 * @slot jumper - Custom jumper content (replaces built-in page jumper dropdown). Consumer manages all behavior.
 *
 * @fires {CustomEvent} btu-pagination-ready - Fired after first render
 * @fires {CustomEvent<{page: number, pageSize: number}>} btu-pagination-change - Fired on page navigation
 * @fires {CustomEvent<{page: number, pageSize: number}>} btu-pagination-page-size-change - Fired on page size change
 *
 * @cssprop --pagination-color-background - Background color for dropdowns, buttons, and jumper
 * @cssprop --pagination-color-foreground - Text/icon color
 */
export default class Pagination extends EventEmitterMixin(ReadyMixin(LitElement)) {
    constructor() {
        super(...arguments);
        /**
         * Current page number (1-based)
         * @attr
         */
        this.page = 1;
        /**
         * Number of items per page
         * @attr page-size
         */
        this.pageSize = 0;
        /**
         * Disables all pagination controls
         * @attr
         */
        this.disabled = false;
        /**
         * Shows loading spinner and dims controls
         * @attr
         */
        this.loading = false;
        /**
         * Hide controls when there is only one page
         * @attr hide-on-single-page
         */
        this.hideOnSinglePage = true;
        /**
         * Show the page size dropdown
         * @attr page-size-changer
         */
        this.pageSizeChanger = true;
        /**
         * Comma-separated page size options
         * @attr page-size-options
         */
        this.pageSizeOptions = '10, 20, 50';
        /**
         * Total number of items across all pages
         * @attr total-items
         */
        this.totalItems = 0;
        /**
         * Show first and last page buttons
         * @attr boundary-buttons
         */
        this.boundaryButtons = true;
        /**
         * Hide the item count display (e.g., "1-10 of 200")
         * @attr hide-total-count
         */
        this.hideTotalCount = false;
        /**
         * Show the page jumper dropdown. Intended for moderate page counts (under ~100 pages).
         * For large datasets, use a custom `slot="jumper"` with a virtualized or input-based control.
         * @attr page-jumper
         */
        this.pageJumper = false;
        /** @internal */
        this._userInitiated = false;
        /** @internal */
        this.initialClasses = [];
        /** @internal */
        this._hideControls = false;
    }
    get _parsedPageSizeOptions() {
        const parsed = this.pageSizeOptions
            .split(',')
            .map(s => parseInt(s.trim(), 10))
            .filter(n => !isNaN(n) && n > 0);
        return parsed.length > 0 ? parsed : [10];
    }
    get _totalPages() {
        if (this.pageSize <= 0)
            return 1;
        return Math.max(1, Math.ceil(this.totalItems / this.pageSize));
    }
    get _startItem() {
        if (this.totalItems === 0)
            return 0;
        return (this.page - 1) * this.pageSize + 1;
    }
    get _endItem() {
        if (this.totalItems === 0)
            return 0;
        return Math.min(this.page * this.pageSize, this.totalItems);
    }
    connectedCallback() {
        super.connectedCallback();
        if (this.className) {
            this.initialClasses = this.className.split(' ').filter(c => c.trim());
        }
    }
    createRenderRoot() {
        return this;
    }
    willUpdate() {
        // Validate totalItems
        if (isNaN(this.totalItems) || this.totalItems < 0) {
            this.totalItems = 0;
        }
        // Initialize pageSize from first option if not set
        if (this.pageSize <= 0) {
            this.pageSize = this._parsedPageSizeOptions[0];
        }
        // Validate pageSize against options
        const options = this._parsedPageSizeOptions;
        if (!options.includes(this.pageSize)) {
            this.pageSize = options[0];
        }
        // Clamp page
        const totalPages = this._totalPages;
        if (this.page < 1)
            this.page = 1;
        if (this.page > totalPages)
            this.page = totalPages;
        // Build class list
        this._hideControls = this.hideOnSinglePage && this._totalPages <= 1;
        const shouldHide = this._hideControls && this.hideTotalCount;
        const classes = [
            ...this.initialClasses,
            'btu-pagination',
            shouldHide ? 'btu-pagination-hidden' : '',
            this.disabled ? 'btu-pagination-disabled' : '',
            this.loading ? 'btu-pagination-loading' : '',
        ];
        this.className = classes.filter(Boolean).join(' ');
    }
    firstUpdated() {
        this.emit('btu-pagination-ready');
    }
    updated(changed) {
        super.updated(changed);
        this._setupSlots();
        if (!this._userInitiated)
            return;
        this._userInitiated = false;
        if (changed.has('pageSize')) {
            this.emit('btu-pagination-page-size-change', { page: this.page, pageSize: this.pageSize });
        }
        if (changed.has('page')) {
            this.emit('btu-pagination-change', { page: this.page, pageSize: this.pageSize });
        }
    }
    _setupSlots() {
        const pageSizeSlot = this.querySelector(':scope > [slot="page-size"]');
        if (pageSizeSlot) {
            const container = this.querySelector('.btu-pagination-size-changer');
            if (container && pageSizeSlot.parentElement !== container) {
                container.appendChild(pageSizeSlot);
            }
        }
        const jumperSlot = this.querySelector(':scope > [slot="jumper"]');
        if (jumperSlot) {
            const container = this.querySelector('.btu-pagination-jumper');
            if (container && jumperSlot.parentElement !== container) {
                container.appendChild(jumperSlot);
            }
        }
    }
    _goToFirstPage(e) {
        this._userInitiated = true;
        this.page = 1;
        this._manageBoundaryFocus(e.currentTarget);
    }
    _goToPreviousPage(e) {
        this._userInitiated = true;
        this.page = Math.max(1, this.page - 1);
        this._manageBoundaryFocus(e.currentTarget);
    }
    _goToNextPage(e) {
        this._userInitiated = true;
        this.page = Math.min(this._totalPages, this.page + 1);
        this._manageBoundaryFocus(e.currentTarget);
    }
    _goToLastPage(e) {
        this._userInitiated = true;
        this.page = this._totalPages;
        this._manageBoundaryFocus(e.currentTarget);
    }
    _manageBoundaryFocus(clickedButton) {
        this.updateComplete.then(() => {
            if (clickedButton.disabled) {
                const enabled = this.querySelectorAll('.btu-pagination-controls > btu-icon-button:not([disabled]) .btu-button');
                if (enabled.length > 0)
                    enabled[0].focus();
            }
        });
    }
    _onBuiltinPageSizeSelect(e) {
        const detail = e.detail;
        const newSize = parseInt(detail.value, 10);
        if (isNaN(newSize) || newSize <= 0)
            return;
        this._userInitiated = true;
        this.pageSize = newSize;
        // Explicitly clamp page here (not just in willUpdate) so both pageSize and
        // page changes are batched in the same _userInitiated cycle, ensuring both
        // btu-pagination-page-size-change and btu-pagination-change events fire.
        const newTotalPages = Math.max(1, Math.ceil(this.totalItems / newSize));
        if (this.page > newTotalPages) {
            this.page = newTotalPages;
        }
    }
    _onBuiltinJumperSelect(e) {
        const page = parseInt(e.detail.value, 10);
        if (!isNaN(page) && page >= 1 && page <= this._totalPages) {
            this._userInitiated = true;
            this.page = page;
        }
    }
    render() {
        const isFirst = this.page <= 1;
        const isLast = this.page >= this._totalPages;
        const options = this._parsedPageSizeOptions;
        return html `
      <nav class="btu-pagination-nav" aria-label="${this.label ?? l10n('pagination', 'navLabel', 'Pagination')}">
        ${!this._hideControls
            ? html `<div class="btu-pagination-size-changer">
              ${this.pageSizeChanger && !this.querySelector('[slot="page-size"]')
                ? html `
                    <btu-dropdown
                      label="${this.pageSize}"
                      variant="secondary"
                      size="sm"
                      aria-label="${l10n('pagination', 'itemsPerPage', 'Items per page')}"
                      ?disabled=${this.disabled || this.loading}
                      @btu-dropdown-item-select=${this._onBuiltinPageSizeSelect}
                    >
                      <btu-dropdown-menu>
                        ${options.map(o => html `<btu-dropdown-item
                              label="${o}"
                              value="${o}"
                              ?selected=${o === this.pageSize}
                            ></btu-dropdown-item>`)}
                      </btu-dropdown-menu>
                    </btu-dropdown>
                  `
                : nothing}
            </div>`
            : nothing}
        ${!this.hideTotalCount
            ? html `<div class="btu-pagination-total" aria-live="polite" aria-atomic="true" aria-busy="${this.loading}">
              ${this.totalItems > 0
                ? l10n('pagination', 'status', '___-___ of ___', [this._startItem, this._endItem, this.totalItems])
                : nothing}
            </div>`
            : nothing}
        ${!this._hideControls
            ? html `<div
              class="btu-pagination-controls"
              role="group"
              aria-label="${l10n('pagination', 'pageNavigation', 'Page navigation')}"
            >
              ${this.boundaryButtons
                ? html `<btu-icon-button
                    symbol="chevrons-left"
                    size="sm"
                    type="secondary-clear"
                    aria-label="${l10n('pagination', 'goToFirstPage', 'Go to first page')}"
                    ?disabled=${isFirst || this.disabled || this.loading}
                    @click=${this._goToFirstPage}
                  ></btu-icon-button>`
                : nothing}

              <btu-icon-button
                symbol="chevron-left"
                size="sm"
                type="secondary-clear"
                aria-label="${l10n('pagination', 'goToPreviousPage', 'Go to previous page')}"
                ?disabled=${isFirst || this.disabled || this.loading}
                @click=${this._goToPreviousPage}
              ></btu-icon-button>

              ${this.pageJumper && !this.querySelector('[slot="jumper"]')
                ? html `<div class="btu-pagination-jumper">
                    <btu-dropdown
                      label="${l10n('pagination', 'pageLabel', 'Page ___', [this.page])}"
                      variant="secondary"
                      size="sm"
                      aria-label="${l10n('pagination', 'goToPage', 'Go to page')}"
                      ?disabled=${this.disabled || this.loading}
                      @btu-dropdown-item-select=${this._onBuiltinJumperSelect}
                    >
                      <btu-dropdown-menu>
                        ${Array.from({ length: this._totalPages }, (_, i) => html `<btu-dropdown-item
                              label="${l10n('pagination', 'pageLabel', 'Page ___', [i + 1])}"
                              value="${i + 1}"
                              ?selected=${i + 1 === this.page}
                            ></btu-dropdown-item>`)}
                      </btu-dropdown-menu>
                    </btu-dropdown>
                  </div>`
                : html `<div class="btu-pagination-jumper"></div>`}

              <btu-icon-button
                symbol="chevron-right"
                size="sm"
                type="secondary-clear"
                aria-label="${l10n('pagination', 'goToNextPage', 'Go to next page')}"
                ?disabled=${isLast || this.disabled || this.loading}
                @click=${this._goToNextPage}
              ></btu-icon-button>

              ${this.boundaryButtons
                ? html `<btu-icon-button
                    symbol="chevrons-right"
                    size="sm"
                    type="secondary-clear"
                    aria-label="${l10n('pagination', 'goToLastPage', 'Go to last page')}"
                    ?disabled=${isLast || this.disabled || this.loading}
                    @click=${this._goToLastPage}
                  ></btu-icon-button>`
                : nothing}
              ${this.loading ? html `<btu-circular-progress size="sm"></btu-circular-progress>` : nothing}
            </div>`
            : nothing}
      </nav>
    `;
    }
}
__decorate([
    property({ type: Number })
], Pagination.prototype, "page", void 0);
__decorate([
    property({ type: Number, attribute: 'page-size' })
], Pagination.prototype, "pageSize", void 0);
__decorate([
    property({ type: Boolean })
], Pagination.prototype, "disabled", void 0);
__decorate([
    property({ type: Boolean })
], Pagination.prototype, "loading", void 0);
__decorate([
    property({ type: Boolean, attribute: 'hide-on-single-page' })
], Pagination.prototype, "hideOnSinglePage", void 0);
__decorate([
    property({ type: Boolean, attribute: 'page-size-changer' })
], Pagination.prototype, "pageSizeChanger", void 0);
__decorate([
    property({ type: String, attribute: 'page-size-options' })
], Pagination.prototype, "pageSizeOptions", void 0);
__decorate([
    property({ type: Number, attribute: 'total-items' })
], Pagination.prototype, "totalItems", void 0);
__decorate([
    property({ type: Boolean, attribute: 'boundary-buttons' })
], Pagination.prototype, "boundaryButtons", void 0);
__decorate([
    property({ type: Boolean, attribute: 'hide-total-count' })
], Pagination.prototype, "hideTotalCount", void 0);
__decorate([
    property({ type: Boolean, attribute: 'page-jumper' })
], Pagination.prototype, "pageJumper", void 0);
__decorate([
    property({ type: String })
], Pagination.prototype, "label", void 0);
if (!customElements.get('btu-pagination')) {
    customElements.define('btu-pagination', Pagination);
}
//# sourceMappingURL=Pagination.js.map