/**
 * Reusable Table Pagination Module for KUB Katedral
 * Usage: initPagination({ tableId, tbodyId, containerId, perPage })
 */
function initPagination(config) {
    const {
        tableId,
        tbodyId,
        containerId,
        perPage: defaultPerPage = 10,
        onPageChange = null
    } = config;

    let currentPage = 1;
    let perPage = defaultPerPage;

    const container = document.getElementById(containerId);
    if (!container) return null;

    // Build pagination HTML
    container.innerHTML = `
        <div class="pagination-info" id="${containerId}_info"></div>
        <div class="pagination-controls" id="${containerId}_controls"></div>
    `;

    function getVisibleRows() {
        const tbody = document.getElementById(tbodyId);
        if (!tbody) return [];
        return Array.from(tbody.querySelectorAll('tr')).filter(row => {
            // Respect search filtering: only include rows not hidden by search
            return row.getAttribute('data-pagination-hidden') !== 'true';
        });
    }

    function getAllRows() {
        const tbody = document.getElementById(tbodyId);
        if (!tbody) return [];
        return Array.from(tbody.querySelectorAll('tr'));
    }

    function render() {
        const visibleRows = getVisibleRows();
        const totalRows = visibleRows.length;
        const totalPages = Math.max(1, Math.ceil(totalRows / perPage));

        if (currentPage > totalPages) currentPage = totalPages;

        const start = (currentPage - 1) * perPage;
        const end = start + perPage;

        // Hide all rows first
        getAllRows().forEach(row => row.style.display = 'none');

        // Show only rows for current page (from visible/filtered set)
        visibleRows.forEach((row, index) => {
            if (index >= start && index < end) {
                row.style.display = '';
            }
        });

        // Update row numbers
        visibleRows.forEach((row, index) => {
            const firstTd = row.querySelector('td:first-child');
            if (firstTd && !isNaN(parseInt(firstTd.textContent))) {
                firstTd.textContent = index + 1;
            }
        });

        // Update info
        const infoEl = document.getElementById(`${containerId}_info`);
        if (infoEl) {
            const showStart = totalRows === 0 ? 0 : start + 1;
            const showEnd = Math.min(end, totalRows);
            infoEl.textContent = `Menampilkan ${showStart}–${showEnd} dari ${totalRows} data`;
        }

        // Build controls
        const controlsEl = document.getElementById(`${containerId}_controls`);
        if (!controlsEl) return;

        let html = '';

        // Prev button
        html += `<button onclick="${containerId}Paginator.goTo(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>‹</button>`;

        // Page buttons with ellipsis
        const maxVisible = 5;
        let pages = [];

        if (totalPages <= maxVisible + 2) {
            for (let i = 1; i <= totalPages; i++) pages.push(i);
        } else {
            pages.push(1);
            let rangeStart = Math.max(2, currentPage - 1);
            let rangeEnd = Math.min(totalPages - 1, currentPage + 1);

            if (currentPage <= 3) {
                rangeStart = 2;
                rangeEnd = Math.min(maxVisible, totalPages - 1);
            } else if (currentPage >= totalPages - 2) {
                rangeStart = Math.max(2, totalPages - maxVisible + 1);
                rangeEnd = totalPages - 1;
            }

            if (rangeStart > 2) pages.push('...');
            for (let i = rangeStart; i <= rangeEnd; i++) pages.push(i);
            if (rangeEnd < totalPages - 1) pages.push('...');
            pages.push(totalPages);
        }

        pages.forEach(p => {
            if (p === '...') {
                html += `<span class="page-ellipsis">…</span>`;
            } else {
                html += `<button onclick="${containerId}Paginator.goTo(${p})" class="${p === currentPage ? 'active' : ''}">${p}</button>`;
            }
        });

        // Next button
        html += `<button onclick="${containerId}Paginator.goTo(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>›</button>`;

        controlsEl.innerHTML = html;

        if (onPageChange) onPageChange();
    }

    // Public API
    const api = {
        goTo(page) {
            const visibleRows = getVisibleRows();
            const totalPages = Math.max(1, Math.ceil(visibleRows.length / perPage));
            if (page < 1 || page > totalPages) return;
            currentPage = page;
            render();
        },
        refresh() {
            render();
        },
        reset() {
            currentPage = 1;
            render();
        },
        markSearchFiltered(searchFn) {
            // Mark rows based on search, then re-render pagination
            const allRows = getAllRows();
            allRows.forEach(row => {
                const hidden = !searchFn(row);
                row.setAttribute('data-pagination-hidden', hidden ? 'true' : 'false');
            });
            currentPage = 1;
            render();
        }
    };

    // Expose globally
    window[`${containerId}Paginator`] = api;

    // Initial render
    render();

    return api;
}
