'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-d337cd8a.js');
const helpers = require('./helpers-81cd6930.js');
require('./constants-4d389abc.js');

const icPaginationBarCss = ":host(){display:block}.pagination-bar{height:3.5rem;display:flex;align-items:center;justify-content:flex-end;gap:var(--ic-space-xl);padding:var(--ic-space-xs) var(--ic-space-md);box-sizing:border-box;--ic-typography-color:var(--ic-pagination-text)}.pagination-bar-left{justify-content:flex-start}.item-controls{display:flex;align-items:center;gap:var(--ic-space-xl)}.pagination-bar-space-between .item-controls{margin-right:auto}.items-per-page-holder{display:flex;align-items:center;gap:var(--ic-space-xs)}.items-per-page-input{--input-width:5rem;--ic-typography-color:var(--ic-pagination-select-content)}.pagination-controls{display:flex;align-items:center;gap:var(--ic-space-xl)}.pagination-controls-wrap{flex-direction:column;align-items:flex-end;gap:var(--ic-space-xs)}.pagination-bar-space-between .pagination-controls{margin-left:auto}.go-to-page-holder{display:flex;align-items:center;gap:var(--ic-space-xs)}.go-to-page-input{--input-width:var(--ic-space-xl)}.go-to-page-button{--min-width:var(--ic-space-xl)}.items-per-page-control-label{white-space:nowrap}@media screen and (max-width: 768px){.pagination-bar{flex-direction:column;align-items:flex-end;height:-moz-fit-content;height:fit-content;gap:var(--ic-space-xs)}.pagination-bar-left{align-items:flex-start}}@media screen and (max-width: 320px){.item-controls,.pagination-controls{flex-direction:column;align-items:flex-end;gap:var(--ic-space-xs)}.pagination-bar-left .item-controls,.pagination-bar-left .pagination-controls,.pagination-bar-space-between .item-controls,.pagination-bar-space-between .pagination-controls{align-items:flex-start}}";
const IcPaginationBarStyle0 = icPaginationBarCss;

const PaginationBar = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.icPageChange = index.createEvent(this, "icPageChange", 7);
        this.icItemsPerPageChange = index.createEvent(this, "icItemsPerPageChange", 7);
        this.PAGE_INPUT_FIELD_ID = "go-to-page-input";
        this.INVALID_PAGE_ERROR = "Please enter a valid page";
        this.resizeObserver = null;
        this.activePage = 1;
        this.inputError = "Please enter a valid page";
        this.itemsPerPage = 10;
        this.itemsPerPageString = "10";
        this.lowerBound = 1;
        this.paginationWrapped = false;
        /**
         * The accessible label passed down to the pagination component to provide context for screen reader users.
         */
        this.accessibleLabel = "Pagination Navigation";
        /**
         * Sets the alignment of the items in the pagination bar.
         */
        this.alignment = "right";
        /**
         * The current page number to be displayed on the pagination bar.
         */
        this.currentPage = 1;
        /**
         * If `true`, the 'All' option will be hidden from the 'items per page' select input.
         */
        this.hideAllFromItemsPerPage = false;
        /**
         * If `true`, the current page of the simple pagination will not be displayed.
         */
        this.hideCurrentPage = false;
        /**
         * If `true`, the first and last page buttons will not be displayed.
         */
        this.hideFirstAndLastPageButton = false;
        /**
         * The text which will be used in place of 'Item' on the pagination bar.
         */
        this.itemLabel = "Item";
        /**
         * If `true`, the pagination bar will display as black in the light theme, and white in dark theme.
         */
        this.monochrome = false;
        /**
         * Sets the theme color to the dark or light theme color. "inherit" will set the color based on the system settings or ic-theme component.
         */
        this.theme = "inherit";
        /**
         * Whether the displayed pagination is simple or complex.
         */
        this.type = "simple";
        /**
         * Whether total number of items and current item range or total number of pages and current page is displayed.
         */
        this.rangeLabelType = "page";
        /**
         * The text which will be used in place of 'Page' on the pagination bar.
         */
        this.pageLabel = "Page";
        /**
         * If `true`, the 'go to page' control should be displayed.
         */
        this.showGoToPageControl = false;
        /**
         * If `true`, the number of total items and current item range or number of total pages and current page will be hidden.
         */
        this.hideRangeLabel = false;
        /**
         * If `false`, the value in the items per page control will be set immediately on ArrowUp and ArrowDown instead of when Enter is pressed.
         */
        this.selectItemsPerPageOnEnter = true;
        /**
         * If `true`, the select input to control 'items per page' should be displayed.
         */
        this.showItemsPerPageControl = false;
        /**
         If `true`, the pagination bar is set to the first page when the 'items per page' changes
         */
        this.setToFirstPageOnPaginationChange = false;
        this.setSelectedItemsPerPage = (selectedItemsPerPage, displayedItemsPerPageOptions = []) => {
            const isSelectedItemsPerPagePresent = displayedItemsPerPageOptions === null || displayedItemsPerPageOptions === void 0 ? void 0 : displayedItemsPerPageOptions.some(({ value }) => { var _a; return value === ((_a = this.selectedItemsPerPage) === null || _a === void 0 ? void 0 : _a.toString()); });
            if (isSelectedItemsPerPagePresent) {
                this.setItemsPerPage(selectedItemsPerPage, false);
            }
            else {
                console.error(`The selected items per page option "${this.selectedItemsPerPage}" does not exist`);
                this.setItemsPerPage(+this.totalItems, false);
            }
        };
        this.changeItemsPerPage = () => {
            this.setItemsPerPage(Number(this.pageDropdownEl.value));
            this.userSetItemsPerPage = Number(this.pageDropdownEl.value);
        };
        this.changePage = (page) => {
            this.activePage = page;
            this.lowerBound = page !== 1 ? (page - 1) * this.itemsPerPage + 1 : page;
            this.setUpperBound();
        };
        this.focusElFromLabel = (el) => {
            var _a, _b;
            (_b = (_a = this.paginationBarEl) === null || _a === void 0 ? void 0 : _a.querySelector(el)) === null || _b === void 0 ? void 0 : _b.setFocus();
        };
        this.goToPage = () => {
            var _a;
            const input = this.pageInputEl;
            const page = Number(input.value);
            if (page <= this.totalPages && page > 0) {
                this.changePage(page);
                (_a = this.paginationEl) === null || _a === void 0 ? void 0 : _a.setCurrentPage(page);
                this.activePage = page;
                input.value = "";
                this.icPageChange.emit({ value: page });
                this.pageInputTooltipEl.displayTooltip(false, false);
                input.validationStatus = "";
            }
            else {
                this.setInputError(input, this.INVALID_PAGE_ERROR);
            }
        };
        this.goToPageLabelClickHandler = () => {
            this.focusElFromLabel("ic-text-field");
        };
        this.handleBlur = () => {
            const textField = this.pageInputEl;
            if ((Number(textField.value) <= this.totalPages &&
                Number(textField.value) > 0) ||
                textField.value === "") {
                textField.validationStatus = "";
            }
            this.pageInputTooltipEl.displayTooltip(false, false);
        };
        this.handleFocus = () => {
            if (this.pageInputEl.validationStatus === "error") {
                this.pageInputTooltipEl.displayTooltip(true, true);
            }
        };
        this.handleInputChange = () => {
            const inputValue = parseInt(this.pageInputEl.value);
            if (inputValue > this.totalPages || inputValue <= 0) {
                this.setInputError(this.pageInputEl, this.INVALID_PAGE_ERROR);
                this.pageInputTooltipEl.displayTooltip(true, true);
            }
        };
        this.handleKeydown = (ev) => {
            if (ev.key === "Enter") {
                if (this.pageInputEl.validationStatus === "error") {
                    this.pageInputTooltipEl.displayTooltip(true, true);
                }
                else {
                    this.goToPage();
                }
            }
            else {
                this.pageInputTooltipEl.displayTooltip(false, false);
                this.pageInputEl.validationStatus = "";
            }
        };
        this.handleKeyUp = (ev) => {
            if (Number.isNaN(parseInt(this.pageInputEl.value)) &&
                ev.key !== "Backspace" &&
                ev.key !== "Enter" &&
                ev.key !== "Tab" &&
                ev.key !== "Shift") {
                this.setInputError(this.pageInputEl, "Please enter a number", false);
                this.pageInputTooltipEl.displayTooltip(true, false);
            }
        };
        this.itemsPerPageLabelClickHandler = () => {
            this.focusElFromLabel("ic-select");
        };
        this.paginationShouldWrap = () => {
            if (this.type === "simple") {
                this.paginationWrapped = this.paginationEl.clientHeight > 63;
            }
        };
        this.runResizeObserver = () => {
            if (this.paginationBarEl) {
                this.resizeObserver = new ResizeObserver(() => {
                    const { clientWidth } = this.paginationBarEl;
                    if (clientWidth - this.paginationWidth > 50 ||
                        clientWidth - this.paginationWidth < -50) {
                        this.paginationWidth = clientWidth;
                        this.paginationShouldWrap();
                    }
                });
                this.resizeObserver.observe(this.paginationBarEl);
            }
        };
        this.setInputError = (el, error, focus = true) => {
            this.inputError = error;
            el.validationStatus = "error";
            if (focus)
                el.setFocus();
        };
        this.setToFirstPage = () => {
            var _a;
            const firstPage = 1;
            this.changePage(firstPage);
            (_a = this.paginationEl) === null || _a === void 0 ? void 0 : _a.setCurrentPage(firstPage);
            this.activePage = firstPage;
            this.icPageChange.emit({ value: firstPage });
        };
        this.setItemsPerPage = (newValue, isUserAction = true) => {
            var _a;
            if (this.itemsPerPage !== newValue) {
                this.itemsPerPage = newValue;
                this.itemsPerPageString = newValue.toString();
                this.icItemsPerPageChange.emit({
                    value: this.itemsPerPage,
                    isUserAction,
                });
                if (this.setToFirstPageOnPaginationChange) {
                    this.setToFirstPage();
                }
            }
            this.totalPages =
                this.totalItems > this.itemsPerPage
                    ? Math.ceil(this.totalItems / this.itemsPerPage)
                    : 1;
            this.setUpperBound();
            if (this.activePage > this.totalPages) {
                (_a = this.paginationEl) === null || _a === void 0 ? void 0 : _a.setCurrentPage(this.totalPages);
                this.activePage = this.totalPages;
            }
            this.icPageChange.emit({ value: this.activePage, fromItemsPerPage: true });
        };
        this.setPaginationBarContent = () => {
            const clonedItemsPerPageOptions = this.itemsPerPageOptions
                ? JSON.parse(JSON.stringify(this.itemsPerPageOptions))
                : null;
            const displayedItemsPerPageOptions = clonedItemsPerPageOptions ||
                (this.totalItems <= 100
                    ? [
                        { label: "10", value: "10" },
                        { label: "25", value: "25" },
                        { label: "50", value: "50" },
                    ]
                    : [
                        { label: "25", value: "25" },
                        { label: "100", value: "100" },
                        { label: "1000", value: "1000" },
                    ]);
            !this.hideAllFromItemsPerPage &&
                displayedItemsPerPageOptions.push({
                    label: "All",
                    value: String(this.totalItems),
                });
            this.displayedItemsPerPageOptions = displayedItemsPerPageOptions.filter(({ value }) => this.totalItems >= Number(value));
            let lastOptionValue = 0;
            if (this.userSetItemsPerPage) {
                this.displayedItemsPerPageOptions.some(({ value }) => {
                    lastOptionValue = Number(value);
                    return this.userSetItemsPerPage <= lastOptionValue;
                });
                this.setItemsPerPage(lastOptionValue);
            }
            else {
                if (this.selectedItemsPerPage !== null &&
                    this.selectedItemsPerPage !== undefined) {
                    this.setSelectedItemsPerPage(this.selectedItemsPerPage, this.displayedItemsPerPageOptions);
                }
                else {
                    const updated = this.displayedItemsPerPageOptions.some(({ value }) => {
                        lastOptionValue = Number(value);
                        return this.itemsPerPage <= lastOptionValue;
                    });
                    this.setItemsPerPage(updated || (!updated && this.itemsPerPage > lastOptionValue)
                        ? lastOptionValue
                        : this.itemsPerPage, false);
                }
            }
        };
        this.setUpperBound = () => {
            this.upperBound = Math.min(this.lowerBound + this.itemsPerPage - 1, this.totalItems);
        };
    }
    watchPageNumberHandler() {
        this.setPaginationBarContent();
        if (typeof this.currentPage === "number" && this.currentPage) {
            if (this.currentPage < 1 ||
                (this.totalPages && this.currentPage > this.totalPages)) {
                console.warn(`The current page (${this.currentPage}) must be a number greater than zero but less than or equal to the total number of pages (${this.totalPages})`);
            }
            else {
                this.activePage = this.currentPage;
            }
        }
    }
    watchSelectedItemsPerPageHandler() {
        if (this.selectedItemsPerPage !== null &&
            this.selectedItemsPerPage !== undefined) {
            this.setSelectedItemsPerPage(this.selectedItemsPerPage, this.displayedItemsPerPageOptions);
        }
    }
    watchItemLabelHandler() {
        this.capitalizedItemLabel = helpers.capitalize(this.itemLabel);
        this.lowerCaseItemLabel = this.itemLabel.toLowerCase();
    }
    watchItemsPerPageOptionsHandler(newVal, oldVal) {
        if (JSON.stringify(newVal) === JSON.stringify(oldVal))
            return;
        this.setPaginationBarContent();
    }
    watchPageLabelHandler() {
        this.capitalizedPageLabel = helpers.capitalize(this.pageLabel);
        this.lowerCasePageLabel = this.pageLabel.toLowerCase();
    }
    watchTotalItemsHandler() {
        this.setPaginationBarContent();
    }
    watchSetToFirstPageOnPaginationChange() {
        this.setPaginationBarContent();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
    }
    componentWillLoad() {
        this.watchPageNumberHandler();
        this.watchPageLabelHandler();
        this.watchItemLabelHandler();
        this.setPaginationBarContent();
    }
    componentDidLoad() {
        var _a, _b, _c;
        this.paginationWidth = ((_a = this.paginationBarEl) === null || _a === void 0 ? void 0 : _a.clientWidth) || 0;
        helpers.checkResizeObserver(this.runResizeObserver);
        const textField = (_b = this.el.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector(`.${this.PAGE_INPUT_FIELD_ID}`);
        if (textField) {
            const input = (_c = textField === null || textField === void 0 ? void 0 : textField.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelector("input");
            if (input) {
                input.style.textAlign = "center";
                input.style.padding = "0";
            }
        }
        this.paginationShouldWrap();
    }
    pageChangeHandler(ev) {
        const page = ev.detail.value;
        this.changePage(page);
    }
    render() {
        const { accessibleLabel, alignment, displayedItemsPerPageOptions, PAGE_INPUT_FIELD_ID, type, rangeLabelType, hideRangeLabel, showItemsPerPageControl, showGoToPageControl, pageLabel, capitalizedPageLabel, lowerCasePageLabel, capitalizedItemLabel, lowerCaseItemLabel, totalPages, activePage, itemsPerPageString, theme, monochrome, selectItemsPerPageOnEnter, hideCurrentPage, hideFirstAndLastPageButton, } = this;
        return (index.h(index.Host, { key: 'c11938d14250e5435166136014565a78c8fbe1b0', class: { [`ic-theme-${theme}`]: theme !== "inherit" } }, index.h("div", { key: '14cef9faa92a11d48b0f569524f69a75924fcea5', class: {
                ["pagination-bar"]: true,
                [`pagination-bar-${alignment}`]: true,
            }, ref: (el) => (this.paginationBarEl = el) }, (!hideRangeLabel || showItemsPerPageControl) && (index.h("div", { key: 'ce45782788e8a0fa10c1c4be4c88dd66238abc0d', class: "item-controls" }, showItemsPerPageControl && (index.h("div", { key: '988fd5587d581f707c859b116c0523a09b1fc629', class: "items-per-page-holder" }, index.h("ic-typography", { key: '78062c53ca82dcc53fa6de6da987284760a75411', class: {
                ["items-per-page-control-label"]: true,
            }, variant: "label", onClick: this.itemsPerPageLabelClickHandler }, capitalizedItemLabel, "s per ", lowerCasePageLabel), index.h("ic-select", { key: '5f661cc9f2aa0f691d2e099d34531651acfd4623', theme: theme, size: "small", label: "items-per-page-input", class: "items-per-page-input", hideLabel: true, options: displayedItemsPerPageOptions, selectOnEnter: selectItemsPerPageOnEnter, value: itemsPerPageString, onIcChange: this.changeItemsPerPage, ref: (el) => (this.pageDropdownEl = el) }))), !hideRangeLabel &&
            (rangeLabelType === "data" ? (index.h("ic-typography", { class: {
                    ["item-pagination-label"]: true,
                }, variant: "label", "aria-live": "polite" }, this.upperBound === 0 && `0 ${lowerCaseItemLabel}s`, this.upperBound > 0 &&
                `${this.lowerBound} - ${this.upperBound} of ${this.totalItems} ${lowerCaseItemLabel}${this.totalItems > 1 ? "s" : ""}`)) : (index.h("ic-typography", { class: {
                    ["page-pagination-label"]: true,
                }, variant: "label", "aria-live": "polite" }, capitalizedPageLabel, " ", activePage, " of ", totalPages))))), index.h("div", { key: '2fe098d17de85749fb85b9da97e821c1102e30d5', class: {
                ["pagination-controls"]: true,
                ["pagination-controls-wrap"]: this.paginationWrapped,
            } }, index.h("div", { key: '2df84c3e3e46f8915c3cc223343af2d628025f9f', class: "pagination-holder" }, index.h("ic-pagination", { key: 'ad3217739a5828cbd6e438692ca5a987eab25d51', accessibleLabel: accessibleLabel, type: type, pages: totalPages, label: pageLabel, ref: (el) => (this.paginationEl = el), currentPage: activePage, theme: theme, monochrome: monochrome, hideCurrentPage: hideCurrentPage, hideFirstAndLastPageButton: hideFirstAndLastPageButton })), showGoToPageControl && (index.h("div", { key: '107a7b12ce7d9dd3f3ea2b62bd43c5556dfc2145', class: "go-to-page-holder" }, index.h("ic-typography", { key: '6042313933f74fa385a6cd5244eb32f650b3efe6', variant: "label", onClick: this.goToPageLabelClickHandler }, "Go to ", lowerCasePageLabel), index.h("ic-tooltip", { key: '2667de79e971e45b48b17f6479f17c34b94b9630', label: this.inputError, target: `#${PAGE_INPUT_FIELD_ID}`, disableHover: true, disableClick: true, ref: (el) => (this.pageInputTooltipEl = el) }, index.h("ic-text-field", { key: 'd0039eb822e6bc06d9e9c35c24c962017fffc818', theme: theme, type: "number", size: "small", label: PAGE_INPUT_FIELD_ID, class: PAGE_INPUT_FIELD_ID, id: PAGE_INPUT_FIELD_ID, hideLabel: true, onKeyDown: this.handleKeydown, onKeyUp: this.handleKeyUp, onInput: this.handleInputChange, max: totalPages, min: "1", validationInlineInternal: true, onBlur: this.handleBlur, onFocus: this.handleFocus, ref: (el) => (this.pageInputEl = el) })), index.h("ic-button", { key: 'a5159ea7b8994d71d04a13e4e7dd2f778b9e6e63', variant: "secondary", onClick: this.goToPage, size: "small", class: "go-to-page-button" }, "Go")))))));
    }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "currentPage": ["watchPageNumberHandler"],
        "selectedItemsPerPage": ["watchSelectedItemsPerPageHandler"],
        "itemLabel": ["watchItemLabelHandler"],
        "itemsPerPageOptions": ["watchItemsPerPageOptionsHandler"],
        "pageLabel": ["watchPageLabelHandler"],
        "totalItems": ["watchTotalItemsHandler"],
        "setToFirstPageOnPaginationChange": ["watchSetToFirstPageOnPaginationChange"]
    }; }
};
PaginationBar.style = IcPaginationBarStyle0;

exports.ic_pagination_bar = PaginationBar;

//# sourceMappingURL=ic-pagination-bar.cjs.entry.js.map