// Main application JavaScript for Document Manager


// Global variables
let currentPage = 1;
const itemsPerPage = 12;
let currentPreviewDoc = null; // holds { id, name, fileExt }
let currentFilters = {
    category: '',
    type: '',
    search: '',
    tags: '',
    tagsMatchAll: false,
    vendor: '',
    minTotal: '', // string; parsed to float
    maxTotal: '', // string; parsed to float
    startDate: '', // ISO or yyyy-mm-dd
    endDate: ''    // ISO or yyyy-mm-dd
};

// DOM Elements
let documentsList, noDocuments, pagination, searchForm, searchInput, categoryFilter, typeFilter, applyFiltersBtn, resetFiltersBtn;
let tagsFilter, tagsMatchAllEl, vendorFilter, minTotalFilter, maxTotalFilter, startDateFilter, endDateFilter;

// Initialize the application
console.log("app.js script started");

document.addEventListener('DOMContentLoaded', () => {
    console.log("DOMContentLoaded event fired");
    // Assign DOM elements now that the DOM is loaded
    console.log("Assigning DOM elements...");
    documentsList = document.getElementById('documentsList');
    noDocuments = document.getElementById('noDocuments');
    pagination = document.getElementById('pagination');
    searchForm = document.getElementById('searchForm');
    searchInput = document.getElementById('searchInput');
    categoryFilter = document.getElementById('categoryFilter');
    typeFilter = document.getElementById('typeFilter');
    tagsFilter = document.getElementById('tagsFilter');
    tagsMatchAllEl = document.getElementById('tagsMatchAll');
    vendorFilter = document.getElementById('vendorFilter');
    minTotalFilter = document.getElementById('minTotalFilter');
    maxTotalFilter = document.getElementById('maxTotalFilter');
    startDateFilter = document.getElementById('startDateFilter');
    endDateFilter = document.getElementById('endDateFilter');
    applyFiltersBtn = document.getElementById('applyFilters');
    resetFiltersBtn = document.getElementById('resetFilters');

    // Load initial data first to ensure content is displayed
    console.log("Loading initial data...");
    loadCategories();
    loadDocuments();

    // Then, initialize event listeners for interactivity
    initEventListeners();


    
    // Add a small delay before triggering the fade-in animation
    setTimeout(() => {
        document.body.classList.add('loaded');
    }, 100);
    // Print button listener (in preview modal footer)
    const printBtn = document.getElementById('printDocument');
    if (printBtn) {
        printBtn.addEventListener('click', () => {
            try {
                if (!currentPreviewDoc || !currentPreviewDoc.id) {
                    console.warn('No document selected for printing');
                    return;
                }
                const url = `/document/${currentPreviewDoc.id}/preview`;
                const win = window.open('', '_blank');
                if (!win) {
                    alert('Please allow popups to print the document.');
                    return;
                }
                const title = `Print - ${escapeHtml(currentPreviewDoc.name || 'Document')}`;
                win.document.write(`<!doctype html><html><head><title>${title}</title><style>html,body,iframe{margin:0;padding:0;height:100%;width:100%;}</style></head><body>`);
                win.document.write(`<iframe src="${url}" style="border:0;" onload="setTimeout(()=>{this.contentWindow && this.contentWindow.focus && this.contentWindow.focus(); try{this.contentWindow.print();}catch(e){window.print();}}, 300);"></iframe>`);
                win.document.write('</body></html>');
                win.document.close();
            } catch (e) {
                console.error('Print failed:', e);
                alert('Unable to print this document.');
            }
        });
    }
});

// Initialize event listeners
function initEventListeners() {
    // Search form submission
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            currentFilters.search = searchInput.value.trim();
            currentPage = 1;
            loadDocuments();
        });
    }

// Print the currently previewed document
function printCurrentDocument() {
    try {
        if (!currentPreviewDoc || !currentPreviewDoc.id) {
            console.warn('No document selected for printing');
            return;
        }
        const url = `/document/${currentPreviewDoc.id}/preview`;
        const ext = (currentPreviewDoc.fileExt || '').toLowerCase();
        
        // Use an iframe inside a new window to trigger print reliably for images and PDFs
        const win = window.open('', '_blank');
        if (!win) {
            alert('Please allow popups to print the document.');
            return;
        }
        const title = `Print - ${escapeHtml(currentPreviewDoc.name || 'Document')}`;
        win.document.write(`<!doctype html><html><head><title>${title}</title><style>html,body,iframe{margin:0;padding:0;height:100%;width:100%;}</style></head><body>`);
        win.document.write(`<iframe src="${url}" style="border:0;" onload="setTimeout(()=>{this.contentWindow && this.contentWindow.focus && this.contentWindow.focus(); try{this.contentWindow.print();}catch(e){window.print();}}, 300);"></iframe>`);
        win.document.write('</body></html>');
        win.document.close();
    } catch (e) {
        console.error('Print failed:', e);
        alert('Unable to print this document.');
    }
}
    
    // Apply filters button
    if (applyFiltersBtn) {
        applyFiltersBtn.addEventListener('click', function() {
            currentFilters.category = categoryFilter.value;
            currentFilters.type = typeFilter.value;
            currentFilters.tags = tagsFilter ? tagsFilter.value.trim() : '';
            currentFilters.tagsMatchAll = tagsMatchAllEl ? !!tagsMatchAllEl.checked : false;
            currentFilters.vendor = vendorFilter ? vendorFilter.value.trim() : '';
            currentFilters.minTotal = minTotalFilter ? minTotalFilter.value.trim() : '';
            currentFilters.maxTotal = maxTotalFilter ? maxTotalFilter.value.trim() : '';
            currentFilters.startDate = startDateFilter ? startDateFilter.value.trim() : '';
            currentFilters.endDate = endDateFilter ? endDateFilter.value.trim() : '';
            currentPage = 1;
            loadDocuments();
        });
    }
    
    // Reset filters button
    if (resetFiltersBtn) {
        resetFiltersBtn.addEventListener('click', function() {
            // Reset filter UI
            if (categoryFilter) categoryFilter.value = '';
            if (typeFilter) typeFilter.value = '';
            if (searchInput) searchInput.value = '';
            if (tagsFilter) tagsFilter.value = '';
            if (tagsMatchAllEl) tagsMatchAllEl.checked = false;
            if (vendorFilter) vendorFilter.value = '';
            if (minTotalFilter) minTotalFilter.value = '';
            if (maxTotalFilter) maxTotalFilter.value = '';
            if (startDateFilter) startDateFilter.value = '';
            if (endDateFilter) endDateFilter.value = '';
            
            // Reset filters
            currentFilters = {
                category: '',
                type: '',
                search: '',
                tags: '',
                tagsMatchAll: false,
                vendor: '',
                minTotal: '',
                maxTotal: '',
                startDate: '',
                endDate: ''
            };
            
            // Reload documents
            currentPage = 1;
            loadDocuments();
        });
    }
}

// Load categories from the server
async function loadCategories() {
    console.log("loadCategories function called");
    try {
        const response = await fetch('/api/categories');
        const data = await response.json();
        
        if (data.success && data.data) {
            // Update category filter dropdown
            if (categoryFilter) {
                // Save current value
                const currentValue = categoryFilter.value;
                
                // Clear existing options except the first one
                while (categoryFilter.options.length > 1) {
                    categoryFilter.remove(1);
                }
                
                // Add new categories
                data.data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.name;
                    option.textContent = category.name;
                    categoryFilter.appendChild(option);
                });
                
                // Restore previous value if it still exists
                if (currentValue) {
                    const optionExists = Array.from(categoryFilter.options).some(
                        opt => opt.value === currentValue
                    );
                    if (optionExists) {
                        categoryFilter.value = currentValue;
                    }
                }
            }
            
            // Also update the upload form's category dropdown if it exists
            const uploadCategory = document.getElementById('documentCategory');
            if (uploadCategory) {
                // Clear existing options except the first one
                while (uploadCategory.options.length > 1) {
                    uploadCategory.remove(1);
                }
                
                // Add new categories
                data.data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.name;
                    option.textContent = category.name;
                    uploadCategory.appendChild(option);
                });
            }
        }
    } catch (error) {
        console.error('Error loading categories:', error);
    }
}

// Load documents from the server
async function loadDocuments() {
    console.log("loadDocuments function called");
    try {
        console.log('Loading documents, page:', currentPage);
        
        // Show loading state
        documentsList.innerHTML = '<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';
        
        // Build query parameters
        const params = new URLSearchParams();
        if (currentFilters.category) params.append('category', currentFilters.category);
        if (currentFilters.type) params.append('type', currentFilters.type);
        if (currentFilters.search) params.append('q', currentFilters.search);
        if (currentFilters.tags) params.append('tags', currentFilters.tags);
        if (currentFilters.tags && currentFilters.tagsMatchAll) params.append('matchAllTags', '1');
        if (currentFilters.vendor) params.append('vendor', currentFilters.vendor);
        if (currentFilters.minTotal) params.append('minTotal', currentFilters.minTotal);
        if (currentFilters.maxTotal) params.append('maxTotal', currentFilters.maxTotal);
        if (currentFilters.startDate) params.append('startDate', currentFilters.startDate);
        if (currentFilters.endDate) params.append('endDate', currentFilters.endDate);
        // Ensure page is at least 1
        const page = Math.max(1, parseInt(currentPage) || 1);
        params.append('page', page);
        params.append('limit', itemsPerPage);
        
        const apiUrl = `/api/documents?${params.toString()}`;
        console.log('Fetching documents from:', apiUrl);
        
        // Fetch documents
        const response = await fetch(apiUrl);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('Received data:', data);
        
        // Clear the documents list
        documentsList.innerHTML = '';
        
        let documents = data.data || [];
        const paginationData = data.pagination || {};

        // If the server does not handle new filters, apply client-side as a fallback
        if (data.success) {
            if (!paginationData || Object.keys(paginationData).length === 0) {
                documents = filterDocumentsClientSide(documents, currentFilters);
            }
        }

        if (data.success && documents.length > 0) {
            console.log(`Rendering ${documents.length} documents`);
            
            // Hide "no documents" message
            if (noDocuments) noDocuments.style.display = 'none';
            
            // Render documents
            const startIndex = (currentPage - 1) * itemsPerPage;
            const pageDocs = documents.slice(startIndex, startIndex + itemsPerPage);
            pageDocs.forEach(doc => {
                renderDocumentCard(doc);
            });
            
            // Update pagination with the server's pagination data
            if (paginationData) {
                console.log('Updating pagination with server data:', paginationData);
                updatePagination(paginationData);
            } else {
                console.log('No pagination data from server, creating basic pagination');
                // If no pagination data from server, create a basic one (based on filtered list)
                const totalItems = documents.length;
                updatePagination({
                    currentPage: currentPage,
                    totalPages: Math.ceil(totalItems / itemsPerPage) || 1,
                    totalItems,
                    itemsPerPage: itemsPerPage,
                    hasNextPage: currentPage < Math.ceil(totalItems / itemsPerPage),
                    hasPreviousPage: currentPage > 1
                });
            }
        } else {
            console.log('No documents found or empty data');
            // Show "no documents" message
            if (noDocuments) noDocuments.style.display = 'block';
            const paginationEl = document.querySelector('#pagination .pagination');
            if (paginationEl) {
                paginationEl.innerHTML = '';
            }
        }
    } catch (error) {
        console.error('Error loading documents:', error);
        documentsList.innerHTML = `
            <div class="col-12">
                <div class="alert alert-danger">
                    Failed to load documents. Please try again later.
                </div>
            </div>
        `;
    }
}

// Render a single document card
function renderDocumentCard(doc) {
    try {
    // Format date
    const docDate = doc.date ? new Date(doc.date).toLocaleDateString() : 'N/A';
    
    // Determine icon based on file type
    let iconClass = 'bi-file-earmark-text';
    let bgClass = 'bg-light';
    
    if (doc.document_type) {
        switch(doc.document_type.toLowerCase()) {
            case 'image':
                iconClass = 'bi-file-earmark-image';
                bgClass = 'bg-invoice';
                break;
            case 'pdf':
                iconClass = 'bi-file-earmark-pdf';
                bgClass = 'bg-receipt';
                break;
            case 'word':
                iconClass = 'bi-file-earmark-word';
                bgClass = 'bg-contract';
                break;
            default:
                iconClass = 'bi-file-earmark-text';
                bgClass = 'bg-other';
        }
    }
    
    // Create the card HTML
    const card = document.createElement('div');
    card.className = 'col-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-4 fade-in';
    card.innerHTML = `
        <div class="card document-card h-100">
            <div class="card-body d-flex flex-column">
                <div class="text-center mb-3">
                    <div class="document-icon ${bgClass} p-3 rounded-circle d-inline-flex align-items-center justify-content-center">
                        <i class="bi ${iconClass}"></i>
                    </div>
                </div>
                <h5 class="card-title" title="${escapeHtml(doc.name)}">${truncateText(doc.name, 30)}</h5>
                ${doc.summary ? `<p class="card-text text-muted" title="${escapeHtml(doc.summary)}">${truncateText(doc.summary, 60)}</p>` : ''}
                <div class="document-meta mt-auto">
                    <div><i class="bi bi-tag"></i> ${doc.category || 'Uncategorized'}</div>
                    <div><i class="bi bi-calendar"></i> ${docDate}</div>
                    <div><i class="bi bi-currency-dollar"></i> ${doc.total_amount ? escapeHtml(doc.total_amount) : '0.00'}</div>
                    ${doc.vendor ? `<div><i class="bi bi-building"></i> ${escapeHtml(doc.vendor)}</div>` : ''}
                    ${doc.tags ? `<div class="mt-1">${doc.tags.split(',').map(t => `<span class='badge bg-secondary me-1'>${escapeHtml(t.trim())}</span>`).join('')}</div>` : ''}
                </div>
                <div class="mt-3 d-flex gap-2">
                    <button class="btn btn-sm btn-outline-primary flex-grow-1 view-document" data-id="${doc.id}">
                        <i class="bi bi-eye"></i> View
                    </button>
                    <a href="/download/${doc.id}" class="btn btn-sm btn-outline-secondary" download="${escapeHtml(doc.name)}">
                        <i class="bi bi-download"></i>
                    </a>
                </div>
            </div>
        </div>
    `;
    
    // Add event listener for view button
    card.querySelector('.view-document').addEventListener('click', () => showDocumentPreview(doc.id));

    // Add to the documents list
    documentsList.appendChild(card);
    } catch (error) {
        console.error('Error rendering document card:', error, 'for document:', doc);
    }
}

// Show document preview in modal
async function showDocumentPreview(docId) {
    console.log(`Showing preview for docId: ${docId}`);
    const previewContent = document.getElementById('documentPreviewContent');
    if (!previewContent) {
        console.error('Preview content element not found');
        return;
    }

    const previewModal = new bootstrap.Modal(document.getElementById('documentPreviewModal'));
    
    try {
        if (!docId) {
            throw new Error('No document ID provided');
        }

        // Show loading state
        previewContent.innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary mb-3" role="status"></div>
                <p>Loading document ${docId}...</p>
            </div>
        `;
        
        // Show the modal
        previewModal.show();
        
        console.log(`Fetching document details for ID: ${docId}`);
        const response = await fetch(`/api/document/${docId}`);
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error('Raw error response:', errorText);
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // Log raw response text before parsing
        const responseText = await response.text();
        console.log('Raw response text:', responseText);
        
        // Parse the JSON manually to catch any parsing errors
        let data;
        try {
            data = JSON.parse(responseText);
            console.log('Parsed document details:', data);
        } catch (parseError) {
            console.error('Error parsing JSON:', parseError);
            throw new Error('Invalid JSON response from server');
        }
        
        if (!data) {
            throw new Error('No data received from server');
        }
        
        if (!data.success) {
            throw new Error(data.error || 'Failed to load document details');
        }
        
        if (!data.data) {
            throw new Error('No document data found in response');
        }
        
        const doc = data.data;
        
        // Set the document title
        const titleElement = document.getElementById('documentPreviewTitle');
        if (titleElement) {
            titleElement.textContent = doc.name || 'Document Preview';
        }
        
        // Set the download link
        const downloadBtn = document.getElementById('downloadDocument');
        if (downloadBtn) {
            downloadBtn.href = `/download/${doc.id}`;
            downloadBtn.download = doc.name || 'document';
        }
        
        // Determine how to display the document based on its type
        const fileExt = doc.file_path ? doc.file_path.split('.').pop().toLowerCase() : '';
        currentPreviewDoc = { id: doc.id, name: doc.name || 'Document', fileExt };
        
        // Build a right-side details panel to keep summary and fields visible
        const detailsPanel = `
            <div class="mt-3">
                ${doc.summary ? `<div class="mb-3"><h6>Summary</h6><div class="small text-muted" style="max-height: 25vh; overflow:auto; white-space:pre-wrap;">${escapeHtml(doc.summary)}</div></div>` : ''}
                <div class="row g-2">
                    <div class="col-6"><strong>Category:</strong> ${escapeHtml(doc.category || 'Uncategorized')}</div>
                    <div class="col-6"><strong>Date:</strong> ${doc.date ? new Date(doc.date).toLocaleDateString() : 'N/A'}</div>
                    <div class="col-6"><strong>Total:</strong> ${doc.total_amount ? escapeHtml(doc.total_amount) : '0.00'}</div>
                    <div class="col-6"><strong>Vendor:</strong> ${doc.vendor ? escapeHtml(doc.vendor) : ''}</div>
                    ${doc.tags ? `<div class="col-12"><strong>Tags:</strong> ${doc.tags.split(',').map(t => `<span class='badge bg-secondary me-1'>${escapeHtml(t.trim())}</span>`).join('')}</div>` : ''}
                </div>
            </div>
        `;

        if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExt)) {
            // Image preview with details
            previewContent.innerHTML = `
                <div class="row">
                    <div class="col-12 text-center">
                        <img src="/document/${doc.id}/preview" alt="${escapeHtml(doc.name || '')}" class="img-fluid" style="max-height: 70vh;">
                    </div>
                    <div class="col-12">${detailsPanel}</div>
                </div>
            `;
        } else if (fileExt === 'pdf') {
            // PDF preview using PDF.js
            previewContent.innerHTML = `
                <div class="row">
                    <div class="col-12 col-lg-8">
                        <canvas id="pdfViewer" class="w-100"></canvas>
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <button class="btn btn-sm btn-outline-primary" id="prevPage">Previous</button>
                            <span id="pageInfo">Page 1 of 1</span>
                            <button class="btn btn-sm btn-outline-primary" id="nextPage">Next</button>
                        </div>
                    </div>
                    <div class="col-12 col-lg-4">
                        ${detailsPanel}
                    </div>
                </div>
            `;
            
            // Initialize PDF.js
            try {

                let pdfDoc = null;
                let pageNum = 1;
                let pageRendering = false;
                let pageNumPending = null;
                const scale = 1.5;
                const canvas = document.getElementById('pdfViewer');
                const ctx = canvas.getContext('2d');

                async function renderPage(num) {
                    pageRendering = true;
                    const page = await pdfDoc.getPage(num);
                    const viewport = page.getViewport({ scale: scale });
                    canvas.height = viewport.height;
                    canvas.width = viewport.width;

                    const renderContext = {
                        canvasContext: ctx,
                        viewport: viewport
                    };
                    await page.render(renderContext).promise;
                    pageRendering = false;
                    if (pageNumPending !== null) {
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                }

                function queueRenderPage(num) {
                    if (pageRendering) {
                        pageNumPending = num;
                    } else {
                        renderPage(num);
                    }
                }

                function updateButtons() {
                    document.getElementById('pageInfo').textContent = `Page ${pageNum} of ${pdfDoc.numPages}`;
                    document.getElementById('prevPage').disabled = pageNum <= 1;
                    document.getElementById('nextPage').disabled = pageNum >= pdfDoc.numPages;
                }

                const loadingTask = pdfjsLib.getDocument(`/document/${doc.id}/preview`);
                pdfDoc = await loadingTask.promise;
                updateButtons();
                renderPage(pageNum);

                // Button event listeners
                document.getElementById('prevPage').addEventListener('click', () => {
                    if (pageNum <= 1) return;
                    pageNum--;
                    queueRenderPage(pageNum);
                    updateButtons();
                });

                document.getElementById('nextPage').addEventListener('click', () => {
                    if (pageNum >= pdfDoc.numPages) return;
                    pageNum++;
                    queueRenderPage(pageNum);
                    updateButtons();
                });

            } catch (pdfError) {
                console.error('Error initializing PDF viewer:', pdfError);
                previewContent.innerHTML = `<div class="alert alert-danger">Failed to load PDF: ${pdfError.message}</div>`;
            }
            
        } else if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(fileExt)) {
            // Office documents - show a message with download option
            previewContent.innerHTML = `
                <div class="text-center py-5">
                    <i class="bi bi-file-earmark-word display-1 text-primary mb-3"></i>
                    <h4>${escapeHtml(doc.name || 'Document')}</h4>
                    <p class="text-muted mb-4">Preview not available for this file type.</p>
                    <a href="/download/${doc.id}" class="btn btn-primary" download>
                        <i class="bi bi-download me-2"></i>Download Document
                    </a>
                    ${detailsPanel}
                </div>
            `;
        } else {
            // Unsupported file type
            previewContent.innerHTML = `
                <div class="text-center py-5">
                    <i class="bi bi-file-earmark-text display-1 text-muted mb-3"></i>
                    <h4>${escapeHtml(doc.name || 'File')}</h4>
                    <p class="text-muted mb-4">Preview not available for this file type.</p>
                    <a href="/download/${doc.id}" class="btn btn-outline-primary" download>
                        <i class="bi bi-download me-2"></i>Download File
                    </a>
                    ${detailsPanel}
                </div>
            `;
        }
        
    } catch (error) {
        console.error('Error loading document preview:', error);
        
        previewContent.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle-fill"></i> 
                Failed to load document preview. Please try again later.
                <div class="mt-2 small">${escapeHtml(error.message)}</div>
            </div>
        `;
    }
}

// Update pagination controls
function updatePagination(pagination) {
    console.log('Updating pagination with data:', pagination);
    
    // Get the pagination container
    const paginationContainer = document.querySelector('#pagination .pagination');
    if (!paginationContainer) {
        console.error('Pagination container not found in the DOM');
        return;
    }
    
    // Check if we have valid pagination data
    if (!pagination || typeof pagination !== 'object') {
        console.error('Invalid pagination data:', pagination);
        paginationContainer.innerHTML = '';
        return;
    }
    
    // Ensure we have the required pagination properties
    if (typeof pagination.currentPage === 'undefined' || typeof pagination.totalPages === 'undefined') {
        console.error('Missing required pagination properties:', pagination);
        paginationContainer.innerHTML = '';
        return;
    }
    
    // If only one page or no pages, clear pagination
    if (pagination.totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    // Ensure currentPage is within valid range
    const localCurrentPage = Math.max(1, Math.min(pagination.currentPage, pagination.totalPages));
    
    let paginationHTML = '';
    const totalPages = pagination.totalPages;
    
    // Previous button
    paginationHTML += `
        <li class="page-item ${localCurrentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${localCurrentPage - 1}" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
    `;
    
    // Page numbers
    const maxVisiblePages = 5;
    let startPage = Math.max(1, localCurrentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    // First page
    if (startPage > 1) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" data-page="1">1</a>
            </li>
        `;
        
        if (startPage > 2) {
            paginationHTML += `
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>
            `;
        }
    }
    
    // Page range
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <li class="page-item ${i === localCurrentPage ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>
        `;
    }
    
    // Last page
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHTML += `
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>
            `;
        }
        
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a>
            </li>
        `;
    }
    
    // Next button
    paginationHTML += `
        <li class="page-item ${localCurrentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${localCurrentPage + 1}" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    `;
    
    // Update the pagination element
    paginationContainer.innerHTML = paginationHTML;
    
    // Add event listeners to pagination links
    paginationContainer.querySelectorAll('.page-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const page = parseInt(this.getAttribute('data-page'));
            if (!isNaN(page) && page !== localCurrentPage) {
                console.log('Page changed to:', page);
                currentPage = page;
                loadDocuments();
                
                // Scroll to top
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // Log the final pagination HTML for debugging
    console.log('Pagination HTML generated:', paginationHTML);
}

// Utility function to escape HTML
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .toString()
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// Utility function to truncate text
function truncateText(text, maxLength) {
    if (!text) return '';
    if (text.length <= maxLength) return escapeHtml(text);
    return escapeHtml(text.substring(0, maxLength)) + '...';
}

function filterDocumentsClientSide(docs, filters) {
    return docs.filter(doc => {
        // Vendor
        if (filters.vendor) {
            const v = (doc.vendor || '').toLowerCase();
            if (!v.includes(filters.vendor.toLowerCase())) return false;
        }
        // Totals
        const toNumber = v => {
            if (v == null) return NaN;
            const s = String(v).replace(/[,$€£\s]/g, '').replace(/[()]/g, '');
            const n = parseFloat(s);
            return isNaN(n) ? NaN : n;
        };
        const total = toNumber(doc.total_amount);
        if (filters.minTotal && !isNaN(parseFloat(filters.minTotal))) {
            if (isNaN(total) || total < parseFloat(filters.minTotal)) return false;
        }
        if (filters.maxTotal && !isNaN(parseFloat(filters.maxTotal))) {
            if (isNaN(total) || total > parseFloat(filters.maxTotal)) return false;
        }
        // Date range
        const docDate = doc.date ? new Date(doc.date) : null;
        if (filters.startDate) {
            const sd = new Date(filters.startDate);
            if (!docDate || docDate < sd) return false;
        }
        if (filters.endDate) {
            const ed = new Date(filters.endDate);
            if (!docDate || docDate > ed) return false;
        }
        return true;
    });
}