const thumbnailContainer = document.getElementById("thumbnailContainer");
const prevBtn = document.getElementById("prevBtn");
const nextBtn = document.getElementById("nextBtn");

// Add new elements for pagination display
const paginationDisplay = document.getElementById("paginationDisplay");

let currentPage = 0;
const imagesPerPage = 4;
let thumbnailsData = [];  // Store the fetched data locally

// Function to fetch data from the server and populate thumbnails
async function fetchDataAndPopulateThumbnails() {
    try {
        thumbnailContainer.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
            </div>
        `;
        
        const response = await fetch('/thumbnails');
        const data = await response.json();

        thumbnailsData = data.thumbnails;

        // Update the pagination display with the initial total number of pages
        updatePaginationDisplay();
        populateThumbnails();
    } catch (error) {
        console.error('Error fetching data:', error);
        thumbnailContainer.innerHTML = "<p>Error loading data. Please try again.</p>";
    }
}

function imageClicked(boothUrl, companyId) {
    window.location.href = `/booth.html?image=${encodeURIComponent(boothUrl)}&companyId=${companyId}`;
}

function populateThumbnails() {
    thumbnailContainer.innerHTML = "";

    const startIndex = currentPage * imagesPerPage;
    const endIndex = Math.min(startIndex + imagesPerPage, thumbnailsData.length);

    for (let i = startIndex; i < endIndex; i++) {
        const { imageUrl, boothUrl, companyName, companyId } = thumbnailsData[i];
        
        const thumbnail = document.createElement("div");
        thumbnail.className = "carousel-item";

        const img = document.createElement("img");
        img.src = imageUrl;
        img.alt = "Thumbnail";

        img.addEventListener("click", function() {
            imageClicked(boothUrl, companyId);
        });

        const thumbnailWrapper = document.createElement("div");
        thumbnailWrapper.className = "thumbnail-wrapper";
        
        const companyNameSpan = document.createElement("span");
        companyNameSpan.className = "company-name";
        companyNameSpan.textContent = companyName;
        thumbnailWrapper.appendChild(companyNameSpan);
        thumbnailWrapper.appendChild(img);

        thumbnail.appendChild(thumbnailWrapper);
        thumbnailContainer.appendChild(thumbnail);
    }

    prevBtn.disabled = currentPage === 0;
    nextBtn.disabled = endIndex >= thumbnailsData.length;

    // Update pagination after the thumbnails have been populated
    updatePaginationDisplay();
}

// Function to navigate to the previous page of thumbnails
function prevSlide() {
    if (currentPage > 0) {
        currentPage--;
        populateThumbnails();
    }
}

// Function to navigate to the next page of thumbnails
function nextSlide() {
    if ((currentPage + 1) * imagesPerPage < thumbnailsData.length) {
        currentPage++;
        populateThumbnails();
    }
}

// Update the pagination display
function updatePaginationDisplay() {
    const totalPages = Math.ceil(thumbnailsData.length / imagesPerPage);
    paginationDisplay.textContent = `Page ${currentPage + 1} of ${totalPages}`;
}

// Initialize the thumbnails carousel
fetchDataAndPopulateThumbnails();
