const PaginationManager = {
    currentPage: 1,
    itemsPerPage: 12,
    totalItems: 0,
    onPageChange: null,

    init(itemsPerPage = 12, onPageChange = null) {
        this.itemsPerPage = itemsPerPage;
        this.onPageChange = onPageChange;
        this.currentPage = 1;
    },

    setTotalItems(total) {
        this.totalItems = total;
    },

    getTotalPages() {
        return Math.ceil(this.totalItems / this.itemsPerPage);
    },

    getCurrentPageItems(items) {
        const start = (this.currentPage - 1) * this.itemsPerPage;
        const end = start + this.itemsPerPage;
        return items.slice(start, end);
    },

    getPageRange() {
        const start = (this.currentPage - 1) * this.itemsPerPage;
        const end = Math.min(start + this.itemsPerPage, this.totalItems);
        return { start, end };
    },

    nextPage() {
        if (this.currentPage < this.getTotalPages()) {
            this.currentPage++;
            if (this.onPageChange) this.onPageChange();
            return true;
        }
        return false;
    },

    prevPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            if (this.onPageChange) this.onPageChange();
            return true;
        }
        return false;
    },

    goToPage(page) {
        const totalPages = this.getTotalPages();
        if (page >= 1 && page <= totalPages) {
            this.currentPage = page;
            if (this.onPageChange) this.onPageChange();
            return true;
        }
        return false;
    },

    reset() {
        this.currentPage = 1;
    },

    renderControls(containerId, pageInfoId, prevBtnId, nextBtnId) {
        const container = document.getElementById(containerId);
        const pageInfo = document.getElementById(pageInfoId);
        const prevBtn = document.getElementById(prevBtnId);
        const nextBtn = document.getElementById(nextBtnId);

        if (!container || !pageInfo || !prevBtn || !nextBtn) return;

        const totalPages = this.getTotalPages();

        if (totalPages <= 1) {
            container.style.display = 'none';
            return;
        }

        container.style.display = 'flex';
        pageInfo.innerText = `Page ${this.currentPage} of ${totalPages}`;

        prevBtn.disabled = this.currentPage === 1;
        nextBtn.disabled = this.currentPage >= totalPages;

        prevBtn.onclick = () => this.prevPage();
        nextBtn.onclick = () => this.nextPage();
    }
};

window.PaginationManager = PaginationManager;