/**
 * Copyright IBM Corp. 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import "../../globals/settings.js";
import { carbonElement } from "../../globals/decorators/carbon-element.js";
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.126.0/helpers/decorate.js";
import iconLoader from "../../globals/internal/icon-loader.js";
import "../icon-button/index.js";
import "./defs.js";
import pagination_nav_default$1 from "./pagination-nav.scss.js";
import { LitElement, html } from "lit";
import { property, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { ifDefined } from "lit/directives/if-defined.js";
import OverflowMenuHorizontal16 from "@carbon/icons/es/overflow-menu--horizontal/16.js";
import CaretLeft16 from "@carbon/icons/es/caret--left/16.js";
import CaretRight16 from "@carbon/icons/es/caret--right/16.js";
//#region src/components/pagination-nav/pagination-nav.ts
/**
*
* Copyright IBM Corp. 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Translation IDs and default translations
*/
const translationIds = {
	"carbon.pagination-nav.next": "carbon.pagination-nav.next",
	"carbon.pagination-nav.previous": "carbon.pagination-nav.previous",
	"carbon.pagination-nav.item": "carbon.pagination-nav.item",
	"carbon.pagination-nav.active": "carbon.pagination-nav.active",
	"carbon.pagination-nav.of": "carbon.pagination-nav.of"
};
const defaultTranslations = {
	[translationIds["carbon.pagination-nav.next"]]: "Next",
	[translationIds["carbon.pagination-nav.previous"]]: "Previous",
	[translationIds["carbon.pagination-nav.item"]]: "Page",
	[translationIds["carbon.pagination-nav.active"]]: "Active",
	[translationIds["carbon.pagination-nav.of"]]: "of"
};
/**
* Default translation function
*/
const defaultTranslateWithId = (messageId) => {
	return defaultTranslations[messageId];
};
/**
* Pagination Navigation.
*
* @element cds-custom-pagination-nav
* @fires cds-custom-page-changed - The custom event fired when the the page has been changed.
*/
let CDSPaginationNav = class CDSPaginationNav extends LitElement {
	constructor(..._args) {
		super(..._args);
		this.cuts = {
			front: 0,
			back: 0
		};
		this.prevPage = null;
		this.itemsShown = 10;
		this.loop = false;
		this.page = 0;
		this.totalItems = 1;
		this.size = "lg";
		this.tooltipAlignment = "center";
		this.tooltipPosition = "bottom";
		this.translateWithId = defaultTranslateWithId;
	}
	_calculateCuts(page, totalItems, itemsDisplayedOnPage, splitPoint = null) {
		if (itemsDisplayedOnPage >= totalItems) return {
			front: 0,
			back: 0
		};
		const split = splitPoint || Math.ceil(itemsDisplayedOnPage / 2) - 1;
		let frontHidden = page + 1 - split;
		let backHidden = totalItems - page - (itemsDisplayedOnPage - split) + 1;
		if (frontHidden <= 1) {
			backHidden -= frontHidden <= 0 ? Math.abs(frontHidden) + 1 : 0;
			frontHidden = 0;
		}
		if (backHidden <= 1) {
			frontHidden -= backHidden <= 0 ? Math.abs(backHidden) + 1 : 0;
			backHidden = 0;
		}
		return {
			front: frontHidden,
			back: backHidden
		};
	}
	_pageWouldBeHidden(page) {
		const wouldBeHiddenInFront = page >= (this.itemsDisplayedOnPage <= 4 && this.page > 1 ? 0 : 1) && page <= this.cuts.front || page === 0;
		const wouldBeHiddenInBack = page >= this.totalItems - this.cuts.back - 1 && page <= this.totalItems - 2;
		return wouldBeHiddenInFront || wouldBeHiddenInBack;
	}
	/**
	* Sets the current page to a specified index.
	*/
	_setIndex(index) {
		if (index >= 0 && index < this.totalItems) {
			this.page = index;
			this.dispatchEvent(new CustomEvent(this.constructor.eventChange, {
				bubbles: true,
				composed: true,
				detail: { page: index }
			}));
		}
	}
	/**
	* Reduce current page by one, but no lower than 0.
	*/
	_decrementIndex() {
		const { loop, page, totalItems } = this;
		const wouldLoop = page - 1 < 0;
		if (loop) this.page = wouldLoop ? totalItems - 1 : page - 1;
		else this.page = Math.max(this.page - 1, 0);
		this.dispatchEvent(new CustomEvent(this.constructor.eventChange, {
			bubbles: true,
			composed: true,
			detail: { page: this.page }
		}));
	}
	/**
	* Increase current page by one, but no higher than (this.totalItems - 1).
	*/
	_incrementIndex() {
		const { loop, page, totalItems } = this;
		const wouldLoop = page + 1 >= totalItems;
		if (loop) this.page = wouldLoop ? 0 : page + 1;
		else this.page = Math.min(this.page + 1, this.totalItems - 1);
		this.dispatchEvent(new CustomEvent(this.constructor.eventChange, {
			bubbles: true,
			composed: true,
			detail: { page: this.page }
		}));
	}
	/**
	* Renders a single pagination item & button.
	*/
	_renderPaginationItem(itemPage, isActive = false) {
		const { translateWithId: t } = this;
		const itemLabel = t("carbon.pagination-nav.item");
		return html`
      <li class="${"cds-custom"}--pagination-nav__list-item">
        <button
          class=${classMap({
			[`cds-custom--pagination-nav__page`]: true,
			[`cds-custom--pagination-nav__page--active`]: isActive
		})}
          type="button"
          @click=${() => this._setIndex(itemPage)}
          data-page="${itemPage + 1}"
          aria-current=${ifDefined(isActive ? "page" : void 0)}>
          <span class="${"cds-custom"}--pagination-nav__accessibility-label">
            ${isActive ? `${t("carbon.pagination-nav.active")}, ${itemLabel}` : itemLabel}
          </span>
          ${itemPage + 1}
        </button>
      </li>
    `;
	}
	/**
	* Renders overflow items in a select list.
	*
	*/
	_renderPaginationOverflow(fromIndex, count) {
		const { translateWithId: t } = this;
		if (count > 1) return html`
        <li class="${"cds-custom"}--pagination-nav__list-item">
          <div class="${"cds-custom"}--pagination-nav__select">
            <select
              class="${"cds-custom"}--pagination-nav__page ${"cds-custom"}--pagination-nav__page--select"
              aria-label="Select ${t("carbon.pagination-nav.item")} number"
              ?disabled="${this.disableOverflow}"
              @change=${(e) => {
			const target = e.target;
			const index = Number(target.value);
			this._setIndex(index);
			e.target.value = "";
		}}>
              <option value="" hidden></option>
              ${Array.from({ length: count }).map((_, i) => html`
                  <option
                    value="${fromIndex + i}"
                    data-page="${fromIndex + i + 1}"
                    key="overflow-${fromIndex + i}">
                    ${fromIndex + i + 1}
                  </option>
                `)}
            </select>
            <div class="${"cds-custom"}--pagination-nav__select-icon-wrapper">
              ${iconLoader(OverflowMenuHorizontal16, { class: `cds-custom--pagination-nav__select-icon` })}
            </div>
          </div>
        </li>
      `;
		else if (count === 1) return this._renderPaginationItem(fromIndex);
		else return html``;
	}
	render() {
		const { loop, page, totalItems, _incrementIndex: incrementIndex, _decrementIndex: decrementIndex, translateWithId: t, size, tooltipAlignment, tooltipPosition } = this;
		const backwardButtonDisabled = !loop && page <= 0;
		const forwardButtonDisabled = !loop && page >= totalItems - 1;
		const startOffset = this.itemsDisplayedOnPage <= 4 && this.page > 1 ? 0 : 1;
		const align = tooltipAlignment === "center" ? tooltipPosition : `${tooltipPosition}-${tooltipAlignment}`;
		return html`
      <nav class="${classMap({
			[`cds-custom--pagination-nav`]: true,
			[`cds-custom--layout--size-${size}`]: size
		})}" aria-label="pagination">
        <ul class="${"cds-custom"}--pagination-nav__list">
          <li class="${"cds-custom"}--pagination-nav__list-item">
            <cds-custom-icon-button
              kind="ghost"
              align="${align}"
              size="${size}"
              ?disabled=${backwardButtonDisabled}
              @click=${decrementIndex}>
              <span slot="tooltip-content"
                >${this.translateWithId("carbon.pagination-nav.previous")}</span
              >
              ${iconLoader(CaretLeft16, { slot: "icon" })}
            </cds-custom-icon-button>
          </li>

          ${this.itemsDisplayedOnPage >= 5 || this.itemsDisplayedOnPage <= 4 && this.page <= 1 ? this._renderPaginationItem(0, this.page === 0) : ""}
          ${this._renderPaginationOverflow(startOffset, this.cuts.front)}
          ${Array.from({ length: this.totalItems }).map((_, i) => i).slice(startOffset + this.cuts.front, (1 + this.cuts.back) * -1).map((item) => this._renderPaginationItem(item, this.page === item))}
          ${this._renderPaginationOverflow(this.totalItems - this.cuts.back - 1, this.cuts.back)}
          ${this.totalItems > 1 ? this._renderPaginationItem(this.totalItems - 1, this.page === this.totalItems - 1) : ""}
          <li class="${"cds-custom"}--pagination-nav__list-item">
            <cds-custom-icon-button
              kind="ghost"
              align="${align}"
              size="${size}"
              ?disabled=${forwardButtonDisabled}
              @click=${incrementIndex}>
              <span slot="tooltip-content"
                >${this.translateWithId("carbon.pagination-nav.next")}</span
              >
              ${iconLoader(CaretRight16, { slot: "icon" })}
            </cds-custom-icon-button>
          </li>
        </ul>
        <div
          aria-live="polite"
          aria-atomic="true"
          class="${"cds-custom"}--pagination-nav__accessibility-label">
          ${`${t("carbon.pagination-nav.item")} ${this.page + 1} ${t("carbon.pagination-nav.of")} ${this.totalItems}`}
        </div>
      </nav>
    `;
	}
	shouldUpdate(changedProperties) {
		if (changedProperties.has("totalItems") || changedProperties.has("page")) {
			if (this.page > this.totalItems) this.page = this.totalItems - 1;
			if (this.page < 0) this.page = 0;
		}
		return true;
	}
	updated(changedProperties) {
		if (changedProperties.has("page")) this.prevPage = changedProperties.get("page");
		if (changedProperties.has("totalItems") || changedProperties.has("itemsShown") || changedProperties.has("size")) {
			let numberOfPages;
			switch (this.size) {
				case "md":
					numberOfPages = this.itemsShown === 4 ? this.itemsShown : 5;
					break;
				case "sm":
					numberOfPages = Math.min(Math.max(4, this.itemsShown), 7);
					break;
				default:
					numberOfPages = 4;
					break;
			}
			this.itemsDisplayedOnPage = Math.max(this.itemsShown >= 4 ? this.itemsShown : numberOfPages, 4);
			this.cuts = this._calculateCuts(this.page, this.totalItems, this.itemsDisplayedOnPage);
		}
		if (changedProperties.has("page") && this._pageWouldBeHidden(this.page)) if (this.page - (this.prevPage || 0) > 0) {
			const splitPoint = this.itemsDisplayedOnPage - 3;
			this.cuts = this._calculateCuts(this.page, this.totalItems, this.itemsDisplayedOnPage, splitPoint);
		} else {
			const splitPoint = this.itemsDisplayedOnPage > 4 ? 2 : 1;
			this.cuts = this._calculateCuts(this.page, this.totalItems, this.itemsDisplayedOnPage, splitPoint);
		}
	}
	static get eventChange() {
		return `cds-custom-page-changed`;
	}
	static {
		this.styles = pagination_nav_default$1;
	}
};
__decorate([state()], CDSPaginationNav.prototype, "itemsDisplayedOnPage", void 0);
__decorate([state()], CDSPaginationNav.prototype, "cuts", void 0);
__decorate([state()], CDSPaginationNav.prototype, "prevPage", void 0);
__decorate([property({
	attribute: "items-shown",
	reflect: true,
	type: Number
})], CDSPaginationNav.prototype, "itemsShown", void 0);
__decorate([property({
	attribute: "loop",
	type: Boolean
})], CDSPaginationNav.prototype, "loop", void 0);
__decorate([property({
	attribute: "page",
	reflect: true,
	type: Number
})], CDSPaginationNav.prototype, "page", void 0);
__decorate([property({
	attribute: "total-items",
	reflect: true,
	type: Number
})], CDSPaginationNav.prototype, "totalItems", void 0);
__decorate([property({ reflect: true })], CDSPaginationNav.prototype, "size", void 0);
__decorate([property({
	attribute: "tooltip-alignment",
	reflect: true
})], CDSPaginationNav.prototype, "tooltipAlignment", void 0);
__decorate([property({
	attribute: "tooltip-position",
	reflect: true
})], CDSPaginationNav.prototype, "tooltipPosition", void 0);
__decorate([property({
	attribute: "disable-overflow",
	reflect: true,
	type: Boolean
})], CDSPaginationNav.prototype, "disableOverflow", void 0);
__decorate([property({ attribute: false })], CDSPaginationNav.prototype, "translateWithId", void 0);
CDSPaginationNav = __decorate([carbonElement(`cds-custom-pagination-nav`)], CDSPaginationNav);
var pagination_nav_default = CDSPaginationNav;
//#endregion
export { pagination_nav_default as default };

//# sourceMappingURL=pagination-nav.js.map