import { Fragment, Host, h } from "@stencil/core";
export class SpwPagination {
    constructor() {
        /** Indique si la pagination est désactivée */
        this.isDisabled = false;
        /** Type de variante de la pagination : 'numbers' ou 'input' */
        this.variant = 'numbers';
        /** Page actuellement sélectionnée, mutable */
        this.currentPage = 1;
        /** Texte pour le bouton "suivant" */
        this.nextButtonText = 'Suivant';
        /** Texte pour le bouton "précédent" */
        this.previousButtonText = 'Précédent';
        /** Mode de pagination : true = changement interne de page, false = émission d'événement uniquement */
        this.isDynamic = true;
        this.inputPageValue = '';
        this.isMobile = window.innerWidth < 800;
        this.updateIsMobile = () => {
            this.isMobile = window.innerWidth < 800;
        };
    }
    componentWillLoad() {
        this.calculateTotalPages();
        this.inputPageValue = this.currentPage.toString();
        window.addEventListener('resize', this.updateIsMobile);
    }
    disconnectedCallback() {
        window.removeEventListener('resize', this.updateIsMobile);
    }
    calculateTotalPages() {
        this.totalPages = Math.ceil(this.totalItems / this.itemsPerPage);
    }
    onCurrentPageChange(newPage) {
        this.inputPageValue = newPage.toString();
    }
    onItemsPerPageChange() {
        this.currentPage = 1;
        this.pageChanged.emit(this.currentPage);
    }
    onTotalItemsChange() {
        if (!this.totalItems || this.totalItems <= 0) {
            return;
        }
        const newTotalPages = Math.ceil(this.totalItems / this.itemsPerPage);
        if (this.currentPage > newTotalPages) {
            this.currentPage = newTotalPages;
            this.pageChanged.emit(this.currentPage);
        }
    }
    /** Méthode publique pour définir la page courante */
    async setPage(page) {
        this.goToPage(page);
    }
    goToPage(page) {
        if (page !== this.currentPage && !this.isDisabled && page >= 1 && page <= this.totalPages) {
            if (this.isDynamic) {
                this.currentPage = page;
            }
            this.pageChanged.emit(page);
        }
    }
    handleInputChange(event) {
        const inputValue = event.target.value;
        this.inputPageValue = inputValue;
        const page = parseInt(inputValue, 10);
        if (!isNaN(page) && page >= 1 && page <= this.totalPages) {
            clearTimeout(this.debounceTimer);
            this.debounceTimer = setTimeout(() => {
                this.goToPage(page);
            }, 500);
        }
    }
    getPaginationClass() {
        var _a, _b;
        const pages = this.calculatePageRange();
        const ellipsisCount = pages.filter(({ page }) => page === '...').length;
        const hasEllipsisStart = ellipsisCount > 0 && ((_a = pages[1]) === null || _a === void 0 ? void 0 : _a.page) === '...';
        const hasEllipsisEnd = ellipsisCount > 0 && ((_b = pages[pages.length - 2]) === null || _b === void 0 ? void 0 : _b.page) === '...';
        let paginationClass = `spw-pagination spw-pagination--${this.currentPage} spw-pagination--total-${this.totalPages}`;
        if (ellipsisCount === 2) {
            paginationClass += ' spw-pagination--double-ellipsis';
        }
        else if (hasEllipsisStart) {
            paginationClass += ' spw-pagination--ellipsis-start';
        }
        else if (hasEllipsisEnd) {
            paginationClass += ' spw-pagination--ellipsis-end';
        }
        return paginationClass;
    }
    handleKeyDown(event) {
        if (event.key === 'Enter') {
            const page = parseInt(this.inputPageValue, 10);
            if (!isNaN(page)) {
                this.goToPage(page);
            }
        }
    }
    calculatePageRange() {
        const pages = [];
        const { currentPage, totalPages, isMobile } = this;
        if (isMobile) {
            // Mode mobile
            if (totalPages <= 5) {
                for (let i = 1; i <= totalPages; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--small-range' });
                }
            }
            else if (currentPage <= 3) {
                for (let i = 1; i <= 3; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--start-range' });
                }
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                pages.push({ page: totalPages, class: 'spw-pagination__item--end' });
            }
            else if (currentPage >= totalPages - 2) {
                pages.push({ page: 1, class: 'spw-pagination__item--start' });
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                for (let i = totalPages - 2; i <= totalPages; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--end-range' });
                }
            }
            else {
                pages.push({ page: 1, class: 'spw-pagination__item--start' });
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                for (let i = currentPage - 1; i <= currentPage + 1; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--middle-range' });
                }
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                pages.push({ page: totalPages, class: 'spw-pagination__item--end' });
            }
        }
        else {
            // Mode desktop
            if (totalPages <= 7) {
                for (let i = 1; i <= totalPages; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--small-range' });
                }
            }
            else if (currentPage <= 4) {
                for (let i = 1; i <= 4; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--start-range' });
                }
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                pages.push({ page: totalPages, class: 'spw-pagination__item--end' });
            }
            else if (currentPage >= totalPages - 3) {
                pages.push({ page: 1, class: 'spw-pagination__item--start' });
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                for (let i = totalPages - 3; i <= totalPages; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--end-range' });
                }
            }
            else {
                pages.push({ page: 1, class: 'spw-pagination__item--start' });
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                for (let i = currentPage - 2; i <= currentPage + 2; i++) {
                    pages.push({ page: i, class: 'spw-pagination__item--middle-range' });
                }
                pages.push({ page: '...', class: 'spw-pagination__item--ellipsis' });
                pages.push({ page: totalPages, class: 'spw-pagination__item--end' });
            }
        }
        return pages;
    }
    render() {
        const pages = this.calculatePageRange();
        const showPrevArrow = this.currentPage > 1;
        const showNextArrow = this.currentPage < this.totalPages;
        const prevArrow = showPrevArrow && (h("li", { key: 'dcd1498e29ee3fb0a7aacfcf837cf779941390c0', class: "spw-pagination__item spw-pagination__item--desktop spw-pagination__item--arrow" }, h("button", { key: 'b15634e85c1082de7220d634d703583cfe000cc0', onClick: () => this.goToPage(this.currentPage - 1) }, h("spw-icon", { key: 'e15c7fd09d198cced97501c8eeac814e6c72e45e', icon: "fa-chevron-left" }), " ", h("span", { key: '417047243b0821163a0e107fb5f810c60758a899', class: "spw-pagination__item-arrow-text" }, this.previousButtonText))));
        const nextArrow = showNextArrow && (h("li", { key: 'dfad6e553a19c22f6f7ecca0a0c0b41a190370a9', class: "spw-pagination__item spw-pagination__item--desktop spw-pagination__item--arrow" }, h("button", { key: '278d707a4394e2225cf6c9bf50ae1146b54914fd', onClick: () => this.goToPage(this.currentPage + 1) }, h("span", { key: '47b58d5f383d2aee5335ce3e3520593ae6b8fdc1', class: "spw-pagination__item-arrow-text" }, this.nextButtonText), " ", h("spw-icon", { key: 'aaeb333a63ce999845ff481283d65d359b498626', icon: "fa-chevron-right" }))));
        const prevArrowMobile = this.currentPage > 1 && (h("li", { key: '67d470dd7ec978d778bf9501f7ff4f0d53e8fd74', class: "spw-pagination__item spw-pagination__item--arrow" }, h("button", { key: '1ef874caef38ad58bfef892f7ff3d3c6a92f1e13', onClick: () => this.goToPage(this.currentPage - 1) }, h("spw-icon", { key: '615092ac9a6fd45d24fba1625ff16f5ab83bcd08', icon: "fa-chevron-left" }), " ", h("span", { key: '68890a0dc95b5356e08002ecd2e8917f024ea2dd' }, this.previousButtonText))));
        const nextArrowMobile = this.currentPage < this.totalPages && (h("li", { key: 'b3ec5c4edbbf33b3c3597e2e8269d390cdf13f3d', class: "spw-pagination__item spw-pagination__item--arrow" }, h("button", { key: '183cf1b1d5d6a92f7738674e3d2e9cb7f060af57', onClick: () => this.goToPage(this.currentPage + 1), disabled: this.currentPage >= this.totalPages }, h("span", { key: '7dfbc497fa94d90984af376e5e20a46621ef4402' }, this.nextButtonText), " ", h("spw-icon", { key: '0aa1fef8996bf23df1eda494cb8f1d9ef6a857b9', icon: "fa-chevron-right" }))));
        const mobileArrows = (h("ul", { key: 'bb0d46915afe5a30ed9751d858a7046a026d0ff4', class: "spw-pagination__mobile-arrows" }, prevArrowMobile, nextArrowMobile));
        return (h(Host, { key: '044cde627233453d74e4a55bfea69d8199513b72' }, h("div", { key: '7e49988f7e2331a3b986cb9644fb51b5e3e25997', class: this.getPaginationClass() }, this.variant === 'input' && (h(Fragment, { key: '721f2508e7980a7d017d57bd35571bea3d7e7478' }, h("ul", { key: 'ed8562aa281db341405e2d7a7374e1890e63ae16' }, prevArrow, h("li", { key: '0f0a0a41bc898e82c1293d59892a2278de1f3e2a', class: "spw-pagination__input" }, h("spw-text-field", { key: '09eb4b0c43e1bc8b0d598d5144bf8defcf772f4b', value: this.inputPageValue, type: "text", name: "pagination-input", onInput: event => this.handleInputChange(event), onKeyDown: event => this.handleKeyDown(event), disabled: this.isDisabled })), h("li", { key: '638c548a6d33678719f9c9543eb3b99a9b52a7d9', class: "spw-pagination__total-pages" }, "sur ", this.totalPages, " ", this.totalPages === 1 ? 'page' : 'pages'), nextArrow), mobileArrows)), this.variant === 'numbers' && (h(Fragment, { key: 'a88d47012d933c68cb648223cf0e2de3e0b4b1e5' }, h("ul", { key: '88d35c75e74693c3cefc806a9592bbf96103add8' }, prevArrow, pages.map(({ page, class: pageClass }) => {
            if (page === '...') {
                return (h("li", { class: `spw-pagination__item spw-pagination__item--dots ${pageClass}` }, h("spw-icon", { icon: "fa-ellipsis" })));
            }
            return (h("li", { class: {
                    'spw-pagination__item': true,
                    'spw-pagination__item--active': page === this.currentPage,
                    [pageClass]: true,
                } }, h("button", { onClick: () => this.goToPage(page), disabled: page === this.currentPage }, page)));
        }), nextArrow), mobileArrows)))));
    }
    static get is() { return "spw-pagination"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-pagination.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-pagination.css"]
        };
    }
    static get properties() {
        return {
            "totalItems": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Nombre total d'\u00E9l\u00E9ments \u00E0 paginer"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "total-items"
            },
            "itemsPerPage": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Nombre d'\u00E9l\u00E9ments \u00E0 afficher par page"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "items-per-page"
            },
            "isDisabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Indique si la pagination est d\u00E9sactiv\u00E9e"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-disabled",
                "defaultValue": "false"
            },
            "variant": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'numbers' | 'input'",
                    "resolved": "\"input\" | \"numbers\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Type de variante de la pagination : 'numbers' ou 'input'"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "variant",
                "defaultValue": "'numbers'"
            },
            "currentPage": {
                "type": "number",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Page actuellement s\u00E9lectionn\u00E9e, mutable"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "current-page",
                "defaultValue": "1"
            },
            "nextButtonText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte pour le bouton \"suivant\""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "next-button-text",
                "defaultValue": "'Suivant'"
            },
            "previousButtonText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte pour le bouton \"pr\u00E9c\u00E9dent\""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "previous-button-text",
                "defaultValue": "'Pr\u00E9c\u00E9dent'"
            },
            "isDynamic": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Mode de pagination : true = changement interne de page, false = \u00E9mission d'\u00E9v\u00E9nement uniquement"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-dynamic",
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "inputPageValue": {},
            "isMobile": {}
        };
    }
    static get events() {
        return [{
                "method": "pageChanged",
                "name": "pageChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9v\u00E9nement \u00E9mis lorsque la page est chang\u00E9e, renvoie le num\u00E9ro de la nouvelle page"
                },
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "setPage": {
                "complexType": {
                    "signature": "(page: number) => Promise<void>",
                    "parameters": [{
                            "name": "page",
                            "type": "number",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "M\u00E9thode publique pour d\u00E9finir la page courante",
                    "tags": []
                }
            }
        };
    }
    static get watchers() {
        return [{
                "propName": "totalItems",
                "methodName": "calculateTotalPages"
            }, {
                "propName": "itemsPerPage",
                "methodName": "calculateTotalPages"
            }, {
                "propName": "currentPage",
                "methodName": "calculateTotalPages"
            }, {
                "propName": "currentPage",
                "methodName": "onCurrentPageChange"
            }, {
                "propName": "itemsPerPage",
                "methodName": "onItemsPerPageChange"
            }, {
                "propName": "totalItems",
                "methodName": "onTotalItemsChange"
            }];
    }
}
