'use strict';

var index = require('./index-pX0sBY0-.js');
var domUtils = require('./dom-utils-BdvOgC2b.js');
var tracking = require('./tracking-BPjaTlNR.js');

const chipItemCss = () => `.chip-item{display:flex;align-items:center;gap:8px;padding:8px 16px;user-select:none;transition:all 100ms ease;transition-property:background, color}.chip-item:hover{cursor:pointer;background-color:#EEEDED}.chip-item:active{background-color:#BFBBBB}.chip-item:focus{outline:2px solid #0A8276}.chip-item.chip-item--large{font:400 1rem/1.5rem "Source Sans 3"}.chip-item.chip-item--small{font:400 0.875rem/1.25rem "Source Sans 3"}.chip-item.chip-item--selected{color:#0A8276}.chip-item.chip-item--selected .chip-item__selected-indicator{display:block}.chip-item__selected-indicator{display:none;margin-left:auto}`;

const ChipItem = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.ifxChipItemSelect = index.createEvent(this, "ifxChipItemSelect", 5);
    }
    get chipItem() { return index.getElement(this); }
    /** Emitted on chip select/deselect. */
    ifxChipItemSelect;
    /** Identifier value for this chip. */
    value = undefined;
    /** Bahaviour and appearance configuration. */
    chipState = {
        emitIfxChipItemSelect: true,
        variant: "multi",
        size: "large",
    };
    /** Wether the chip is selected (reflected). */
    selected = false;
    updateItemSelection(event) {
        if (this.chipState.variant === "single") {
            const target = event.target;
            /* Also making sure chip items are from the same group (parent) while unselecting. */
            if (this.chipItem !== target &&
                this.chipItem.parentElement === target.parentElement) {
                this.selected = false;
            }
        }
    }
    validateSelected(newValue, oldValue) {
        if (newValue !== oldValue) {
            /* Do not emit if ChipState does not allow. */
            if (this.chipState.emitIfxChipItemSelect) {
                this.emitIfxChipItemSelectEvent();
            }
            else {
                this.chipState.emitIfxChipItemSelect = true;
            }
        }
    }
    getItemLabel() {
        return this.chipItem.innerText;
    }
    toggleItemSelection() {
        this.selected = !this.selected;
    }
    emitIfxChipItemSelectEvent(emitIfxChange = true) {
        this.ifxChipItemSelect.emit({
            emitIfxChange: emitIfxChange,
            key: this.chipState.key,
            label: this.getItemLabel(),
            selected: this.selected,
            value: this.value,
        });
    }
    handleItemClick() {
        this.toggleItemSelection();
    }
    handleItemKeyDown(event) {
        if (event.code === "Enter" || event.code === "Space") {
            this.toggleItemSelection();
        }
    }
    handleSelectedState() {
        if (this.selected) {
            this.emitIfxChipItemSelectEvent(false);
        }
    }
    componentWillLoad() {
        /* Propogating the selected state to the Chip (Parent) component if it is set. */
        this.handleSelectedState();
    }
    render() {
        return (index.h("div", { key: '981d58d270509d5cfebcd7eb6ae670d05fae9d6e', class: `chip-item chip-item--${this.chipState.size} 
                    chip-item--${(this.selected && this.chipState.variant) === "single" ? "selected" : ""}`, tabIndex: 0, onClick: () => {
                this.handleItemClick();
            }, onKeyDown: (e) => {
                this.handleItemKeyDown(e);
            }, role: "option", "aria-selected": this.selected.toString() }, this.chipState.variant === "multi" && (index.h("ifx-checkbox", { key: 'e731be959fbf3c07c6c45097b668b32fcbbedaca', checked: this.selected, tabIndex: -1, size: "s" })), index.h("div", { key: 'b87fa6a5c3099e1a8ad566f25e793fa8836cd883', class: "chip-item__label" }, " ", index.h("slot", { key: '20a4dd0e12f940907a7da4a742bc39c66306d01a' }), " "), index.h("div", { key: '413f5dbeeea4d0b05b6e57611e0cf83846b1c292', class: "chip-item__selected-indicator" }, index.h("ifx-icon", { key: 'c040b07c497de6213ce35ba655e6fcb5d490c16a', icon: "check-16" }, " "))));
    }
    static get watchers() { return {
        "selected": [{
                "validateSelected": 0
            }]
    }; }
};
ChipItem.style = chipItemCss();

const paginationCss = () => `:host{display:inline-flex}.container{display:inline-flex;justify-content:center;align-items:center;gap:32px;font-family:var(--ifx-font-family);flex-wrap:wrap}.container .items__per-page-wrapper{display:flex;align-items:center;gap:16px}.container .items__per-page-wrapper .items__per-page-label{color:#1D1D1D;font-size:14px;font-style:normal;font-weight:600;line-height:20px}.container .items__per-page-wrapper .items__per-page-field{display:flex;flex-direction:column;align-items:flex-start}.container .items__per-page-wrapper .items__per-page-field ifx-select{width:92px}.container .items__total-wrapper{display:flex;justify-content:center;align-items:center;gap:12px}.container .items__total-wrapper .items__total-button{display:flex;width:40px;height:40px;justify-content:center;align-items:center;border-radius:100px;border:1px solid #BFBBBB;background:#FFF}.container .items__total-wrapper .page__numbers-wrapper{display:flex;justify-content:center;align-items:center;gap:12px}.container .items__total-wrapper .page__numbers-wrapper .page__number-item{display:flex;padding:6px;flex-direction:column;justify-content:center;align-items:center;gap:10px;border-radius:100px}.container .items__total-wrapper .page__numbers-wrapper .page__number-item.active{background-color:#0A8276}.container .items__total-wrapper .page__numbers-wrapper .page__number-item.active span{color:#fff}.container .items__total-wrapper .page__numbers-wrapper .page__number-item:hover{cursor:pointer}.container .items__total-wrapper .page__numbers-wrapper .page__number-item:hover:not(.active){background-color:#ddd}.container .items__total-wrapper .page__numbers-wrapper .page__number-item:active:not(.active){background-color:#575352}.container .items__total-wrapper .page__numbers-wrapper .page__number-item span{display:flex;width:16px;height:16px;flex-direction:column;justify-content:center;color:#1D1D1D;text-align:center;font-size:13px;font-style:normal;font-weight:400;line-height:20px}.pagination{display:flex}.pagination ifx-icon-button:first-of-type{margin-right:12px}.pagination ifx-icon-button:last-of-type{margin-left:12px}.page__button{padding:8px;border-radius:100px}ol{list-style-type:none;padding:0;margin:0;display:inline-flex;align-items:center;gap:12px}li{display:flex;flex-direction:column;justify-content:center;align-items:center;border-radius:100px}li:hover:not(.active) page__button{background-color:#EEEDED}li:active:not(.active) .page__button{background-color:#575352;color:#fff}li.active{background-color:#0A8276}li.active .page__button{color:#fff}li:hover{cursor:pointer}li .page__button{text-decoration:none;display:flex;width:16px;height:16px;flex-direction:column;justify-content:center;color:#1D1D1D;text-align:center;font-size:13px;font-style:normal;font-weight:400;line-height:20px;align-items:center}.prev.disabled,.next.disabled{cursor:default}.prev.disabled:hover,.next.disabled:hover{cursor:default;text-decoration:none}.prev{margin-right:2.5px}.next{margin-left:2.5px}@media (max-width: 768px){.container{gap:16px;justify-content:left}.container .items__total-wrapper .pagination ol{gap:12px}}@media (max-width: 374px){.pagination .ellipsis+.active{margin-left:8px}.pagination .active+.ellipsis{margin-left:8px}}`;

const Pagination = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.ifxPageChange = index.createEvent(this, "ifxPageChange", 7);
        this.ifxItemsPerPageChange = index.createEvent(this, "ifxItemsPerPageChange", 7);
    }
    get el() { return index.getElement(this); }
    /** Emitted when the current page changes */
    ifxPageChange;
    /** Emitted when the items-per-page value changes */
    ifxItemsPerPageChange;
    /** The current page number passed from the outside */
    currentPage = 1;
    /** Wether to display the items-per-page selector */
    showItemsPerPage = true;
    showAllItems = false;
    internalPage = 1;
    internalItemsPerPage = 10;
    numberOfPages = [];
    /** Total number of items to paginate */
    total = 1;
    /** Items-per-page options */
    itemsPerPage;
    filteredItemsPerPage = [];
    visiblePages = [];
    itemsPerPageLabel = "Results per Page";
    CLASS_DISABLED = "disabled";
    CLASS_ACTIVE = "active";
    prevInternalPage;
    watchTotalHandler() {
        if (this.showAllItems) {
            this.internalItemsPerPage = this.total;
        }
        this.calculateNumberOfPages();
        this.updateVisiblePages();
    }
    currentPageWatcher(newVal) {
        this.internalPage = Math.max(1, Math.min(newVal, this.numberOfPages.length));
        this.calculateNumberOfPages();
        this.updateVisiblePages();
    }
    setItemsPerPage(e) {
        const value = e.detail?.value || e.detail?.label;
        if (value === "all") {
            if (this.showAllItems)
                return;
            this.showAllItems = true;
            this.internalItemsPerPage = this.total;
            this.internalPage = 1;
            this.calculateNumberOfPages();
            this.updateVisiblePages();
            this.handleEventEmission();
            return;
        }
        this.showAllItems = false;
        const newItemsPerPage = parseInt(value) || 10;
        if (newItemsPerPage === this.internalItemsPerPage) {
            return;
        }
        this.internalItemsPerPage = newItemsPerPage;
        this.internalPage = 1;
        this.calculateNumberOfPages();
        this.updateVisiblePages();
        this.handleEventEmission();
    }
    emitItemsPerPage(e) {
        this.ifxItemsPerPageChange.emit(e.detail.label);
    }
    async componentDidLoad() {
        if (this.showItemsPerPage) {
            const select = this.el.shadowRoot.querySelector("#itemsPerPageSelect");
            if (select) {
                select.addEventListener("ifxSelect", (e) => this.emitItemsPerPage(e));
            }
        }
        // Add resize listener to update pagination on screen size changes
        window.addEventListener("resize", this.handleResize);
        if (!domUtils.isNestedInIfxComponent(this.el)) {
            const framework = tracking.detectFramework();
            tracking.trackComponent("ifx-pagination", await framework);
        }
        this.initPagination();
    }
    disconnectedCallback() {
        if (this.showItemsPerPage) {
            const select = this.el.shadowRoot.querySelector("#itemsPerPageSelect");
            if (select) {
                select.removeEventListener("ifxSelect", (e) => this.emitItemsPerPage(e));
            }
        }
        // Remove resize listener
        window.removeEventListener("resize", this.handleResize);
        // Clear any pending resize timeout
        if (this.resizeTimeout) {
            clearTimeout(this.resizeTimeout);
        }
    }
    updateVisiblePages() {
        // Check if screen is mobile (< 400px)
        const isMobile = window.innerWidth < 400;
        const totalPages = this.numberOfPages.length;
        const current = this.internalPage;
        let pages = [];
        if (isMobile) {
            // Mobile logic: maximum 5 elements
            if (totalPages <= 5) {
                pages = [...this.numberOfPages];
            }
            else {
                // Always show first page
                pages.push(1);
                if (current <= 2) {
                    // Show: 1 2 3 … 10 (for pages 1 and 2)
                    pages.push(2, 3, "...", totalPages);
                }
                else if (current >= totalPages - 1) {
                    // Show: 1 … 23 24 25 (for last 2 pages only)
                    pages.push("...", totalPages - 2, totalPages - 1, totalPages);
                }
                else {
                    // Show: 1 … 5 … 10 (for middle pages, including page 3 and third-to-last page)
                    pages.push("...", current, "...", totalPages);
                }
            }
        }
        else {
            // Desktop logic: maximum 7 elements
            const buffer = 2;
            if (totalPages <= 7) {
                pages = [...this.numberOfPages];
            }
            else {
                // Always show first page
                pages.push(1);
                // Determine the range around current page
                let start = Math.max(2, current - buffer);
                let end = Math.min(totalPages - 1, current + buffer);
                // Adjust range to ensure we show enough pages
                // If we're close to the beginning, extend the end
                if (current <= 4) {
                    start = 2;
                    end = Math.min(totalPages - 1, 5);
                }
                // If we're close to the end, extend the start
                else if (current >= totalPages - 3) {
                    start = Math.max(2, totalPages - 4);
                    end = totalPages - 1;
                }
                // For middle pages, show current +/- 1
                else {
                    start = current - 1;
                    end = current + 1;
                }
                // Add ellipsis before the range if there's a gap
                if (start > 2) {
                    pages.push("...");
                }
                // Add the range of pages
                for (let i = start; i <= end; i++) {
                    pages.push(i);
                }
                // Add ellipsis after the range if there's a gap
                if (end < totalPages - 1) {
                    pages.push("...");
                }
                // Always show last page
                pages.push(totalPages);
            }
        }
        this.visiblePages = pages;
    }
    calculateNumberOfPages() {
        if (this.showAllItems) {
            this.numberOfPages = [1];
            this.internalPage = 1;
            return;
        }
        const totalPages = Math.ceil(this.total / this.internalItemsPerPage);
        this.numberOfPages = Array.from({ length: totalPages }, (_, i) => i + 1);
        this.internalPage = Math.max(1, Math.min(this.currentPage, totalPages));
    }
    filterOptionsArray() {
        const items = typeof this.itemsPerPage === "string"
            ? JSON.parse(this.itemsPerPage)
            : this.itemsPerPage;
        this.filteredItemsPerPage = items.map((item) => ({
            ...item,
            label: item.label || item.value,
        }));
    }
    componentWillLoad() {
        this.filterOptionsArray();
        const selectedOption = this.filteredItemsPerPage.find((option) => option.selected);
        if (selectedOption) {
            const value = selectedOption.value || selectedOption.label;
            if (value === "all") {
                this.showAllItems = true;
                this.internalItemsPerPage = this.total;
            }
            else {
                this.internalItemsPerPage = Number(selectedOption.value);
            }
        }
        else if (this.filteredItemsPerPage.length > 0) {
            const firstItem = this.filteredItemsPerPage[0];
            const value = firstItem.value || firstItem.label;
            if (value === "all") {
                this.showAllItems = true;
                this.internalItemsPerPage = this.total;
            }
            else {
                this.internalItemsPerPage = Number(firstItem.value);
            }
        }
        this.calculateNumberOfPages();
        this.internalPage = Math.max(1, Math.min(this.currentPage, this.numberOfPages.length));
        this.updateVisiblePages();
    }
    componentWillUpdate() {
        if (this.prevInternalPage !== this.internalPage) {
            this.updateVisiblePages();
            this.prevInternalPage = this.internalPage;
        }
    }
    componentDidUpdate() {
        this.initPagination();
    }
    handleEventEmission() {
        this.ifxPageChange.emit({
            currentPage: this.internalPage,
            totalPages: this.numberOfPages.length,
            itemsPerPage: this.internalItemsPerPage,
        });
    }
    initPagination() {
        const pagination = this.el.shadowRoot.querySelector(".pagination");
        if (!pagination)
            return;
        const updateButtons = () => {
            const prev = pagination.querySelector(".prev");
            const next = pagination.querySelector(".next");
            if (prev) {
                prev.disabled = this.internalPage === 1;
                prev.classList.toggle(this.CLASS_DISABLED, this.internalPage === 1);
            }
            if (next) {
                next.disabled = this.internalPage === this.numberOfPages.length;
                next.classList.toggle(this.CLASS_DISABLED, this.internalPage === this.numberOfPages.length);
            }
        };
        pagination.querySelectorAll("li").forEach((li) => {
            li.removeEventListener("click", this.handlePageClick);
            li.addEventListener("click", this.handlePageClick);
        });
        updateButtons();
    }
    handlePageClick = (e) => {
        const li = e.currentTarget;
        const page = parseInt(li.dataset.page);
        if (!isNaN(page))
            this.changePage(page);
    };
    handleResize = () => {
        // Debounce resize events to prevent excessive calls
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(() => {
            this.updateVisiblePages();
        }, 100);
    };
    resizeTimeout;
    changePage(newPage) {
        newPage = Math.max(1, Math.min(newPage, this.numberOfPages.length));
        if (newPage === this.internalPage)
            return;
        this.internalPage = newPage;
        this.handleEventEmission();
        this.initPagination();
    }
    render() {
        return (index.h("div", { key: 'a61d4169b15fc02f4f4fdc26b3248fc75a0d4ce1', class: "container" }, this.showItemsPerPage && (index.h("div", { key: '980abee57e9d8bb70b849a55f08727ea2cc9eec2', class: "items__per-page-wrapper" }, index.h("div", { key: '4f45bba5e76ae694c6769a400cabb098205ad2ff', class: "items__per-page-label" }, this.itemsPerPageLabel), index.h("div", { key: '4deba5b390790ed678da6b21ec5495296a6ae54f', class: "items__per-page-field" }, index.h("ifx-select", { key: 'a1c5883263b69c7826f1bd0c41e9cd418d793d4e', id: "itemsPerPageSelect", placeholder: "false", "show-search": "false", value: undefined, disabled: false, error: false, size: "s", options: this.filteredItemsPerPage, "placeholder-value": "Select" })))), index.h("div", { key: '8531ae8613e046bc1f89fd5a557a78c2824c0dfb', class: "items__total-wrapper" }, index.h("div", { key: '752adc6c57bf3dedc96a28bc4c20bf805d05e68d', class: "pagination" }, index.h("ifx-icon-button", { key: '18f63188e9f43a9cfece7b4cf456277ee52840e1', class: "prev", icon: "arrow-left-16", "aria-label": "Previous Page", onClick: () => this.changePage(this.internalPage - 1), variant: "secondary" }), index.h("ol", { key: 'aabb324178481bc572cc13feb86241c5c0baf4da' }, this.visiblePages.map((page, i) => typeof page === "number" ? (index.h("li", { key: `page-${page}`, class: { [this.CLASS_ACTIVE]: page === this.internalPage }, "data-page": page }, index.h("span", { class: "page__button", role: "button", tabindex: "0", "aria-current": page === this.internalPage ? "page" : undefined, "aria-label": `Page ${page}`, onClick: () => this.changePage(page), onKeyDown: (e) => (e.key === "Enter" || e.key === " ") &&
                this.changePage(page) }, page))) : (index.h("li", { class: "ellipsis", key: `ellipsis-${i}` }, index.h("span", { "aria-hidden": "true" }, "..."))))), index.h("ifx-icon-button", { key: '12003fc5ccee8131b9b0ae745178d7f2634a9051', class: "next", icon: "arrow-right-16", "aria-label": "Next Page", onClick: () => this.changePage(this.internalPage + 1), variant: "secondary" })))));
    }
    static get watchers() { return {
        "total": [{
                "watchTotalHandler": 0
            }],
        "currentPage": [{
                "currentPageWatcher": 0
            }]
    }; }
};
Pagination.style = paginationCss();

exports.ifx_chip_item = ChipItem;
exports.ifx_pagination = Pagination;
