#include "imagegallery.h"
#include <QMouseEvent>
#include <QFileInfo>
#include <QProcess>
#include <QDesktopServices>
#include <QUrl>
#include <QPainter>
#include <QApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QTimer>
#include <QScrollBar>



// ImageThumbnail implementation
ImageThumbnail::ImageThumbnail(const QString &filePath, QWidget *parent)
    : QLabel(parent)
    , m_filePath(filePath)
{
    setFixedSize(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
    setAlignment(Qt::AlignCenter);
    setFrameStyle(QFrame::Panel | QFrame::Sunken);
    setLineWidth(2);
    setScaledContents(false);
    setCursor(Qt::PointingHandCursor);
    // We're removing tooltips as requested
    
    // Enable text wrapping and text interaction
    setWordWrap(true);
    setTextInteractionFlags(Qt::TextSelectableByMouse);
    
    // Set a minimum size policy
    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
}

void ImageThumbnail::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        emit thumbnailClicked(m_filePath);
    }
    QLabel::mousePressEvent(event);
}

// ImageGallery implementation
ImageGallery::ImageGallery(QWidget *parent)
    : QWidget(parent)
    , m_dbManager(nullptr)
    , m_currentOffset(0)
    , m_pageSize(DEFAULT_PAGE_SIZE)
    , m_totalCount(0)
    , m_isLoading(false)
    , m_hasMoreImages(false)
    , m_lastScrollPosition(0)
    , m_loadingIndicator(nullptr)
{
    // Create scroll area
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Prevent horizontal scrollbar
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // Create container widget for the grid layout
    m_containerWidget = new QWidget(m_scrollArea);
    
    // Make container expand to fill the available width
    m_containerWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
    
    // Create grid layout with minimal spacing
    m_gridLayout = new QGridLayout(m_containerWidget);
    m_gridLayout->setSpacing(THUMBNAIL_SPACING);
    m_gridLayout->setContentsMargins(THUMBNAIL_SPACING, THUMBNAIL_SPACING, THUMBNAIL_SPACING, THUMBNAIL_SPACING);
    
    // Initialize column count based on container width
    m_columnsCount = 4; // Default value, will be updated in updateGridLayout
    
    m_scrollArea->setWidget(m_containerWidget);
    
    // Create layout for the gallery widget
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_scrollArea);
    setLayout(mainLayout);
    
    // No need to connect to container widget - we'll use resizeEvent instead
    
    // Initial layout update
    QTimer::singleShot(0, this, &ImageGallery::updateGridLayout);
    
    // Install event filter on viewport to catch resize events
    m_scrollArea->viewport()->installEventFilter(this);
    
    // We'll still keep a periodic check as backup
    QTimer *resizeTimer = new QTimer(this);
    connect(resizeTimer, &QTimer::timeout, this, &ImageGallery::handleContainerResized);
    resizeTimer->start(300); // Check every 300ms
    
    // Create scroll timer for detecting end of scroll events
    m_scrollTimer = new QTimer(this);
    m_scrollTimer->setSingleShot(true);
    m_scrollTimer->setInterval(200);
    connect(m_scrollTimer, &QTimer::timeout, this, &ImageGallery::handleScrolledToBottom);
    
    // Create loading indicator
    m_loadingIndicator = new QLabel(tr("Loading more images..."), this);
    m_loadingIndicator->setAlignment(Qt::AlignCenter);
    m_loadingIndicator->setStyleSheet("color: #666; font-size: 14px; padding: 10px;");
    m_loadingIndicator->hide();
    
    // Install event filter on scroll area viewport to catch scroll events
    m_scrollArea->viewport()->installEventFilter(this);
    
    // Create the loading indicator
    m_loadingIndicator = new QLabel(tr("Loading more images..."), this);
    m_loadingIndicator->setAlignment(Qt::AlignCenter);
    m_loadingIndicator->setStyleSheet("color: #666; font-size: 14px; padding: 10px;");
    m_loadingIndicator->hide();
    
    // Create Load More button
    m_loadMoreButton = new QPushButton(tr("Load More Images"), this);
    m_loadMoreButton->setStyleSheet("font-size: 14px; padding: 10px; margin: 10px; background-color: #e0e0e0; border-radius: 5px; border: 1px solid #c0c0c0;");
    m_loadMoreButton->setMinimumHeight(50);
    m_loadMoreButton->setCursor(Qt::PointingHandCursor);
    connect(m_loadMoreButton, &QPushButton::clicked, this, &ImageGallery::handleLoadMoreClicked);
}

ImageGallery::~ImageGallery()
{
    clearGallery();
}

void ImageGallery::setDatabaseManager(DatabaseManager *dbManager)
{
    m_dbManager = dbManager;
    
    // Connect to the DatabaseManager signals
    if (m_dbManager) {
        connect(m_dbManager, &DatabaseManager::searchResultsReady, 
                this, &ImageGallery::handleSearchResults);
        connect(m_dbManager, &DatabaseManager::searchStarted,
                this, &ImageGallery::handleSearchStarted);
    }
    
    // Initialize the last search query
    m_lastSearchQuery = QString();
}

void ImageGallery::displayImages(const QList<DatabaseManager::ImageItem> &images, bool clearExisting)
{
    // Clear existing thumbnails if requested
    if (clearExisting) {
        clearGallery();
        m_currentOffset = 0;
        // Don't reset m_hasMoreImages here - we need to know if there are more to show the button
        // It will be set correctly in handleSearchResults
    }
    
    // Update grid layout to ensure correct column count before adding images
    updateGridLayout();
    
    // Remove any previous instances of the Load More button and loading indicator from the layout
    if (m_loadMoreButton->parent()) {
        m_gridLayout->removeWidget(m_loadMoreButton);
    }
    if (m_loadingIndicator->parent()) {
        m_gridLayout->removeWidget(m_loadingIndicator);
    }
    m_loadMoreButton->hide();
    m_loadingIndicator->hide();
    
    const int numImages = images.size();
    int row = 0, col = 0;
    
    // If we have existing thumbnails, start from the last position
    if (!clearExisting && !m_thumbnails.isEmpty()) {
        // Remove any "no images" or loading indicators first
        for (int i = m_thumbnails.size() - 1; i >= 0; i--) {
            if (m_thumbnails[i]->text().contains("No images found") ||
                m_thumbnails[i]->text().contains("Loading")) {
                m_gridLayout->removeWidget(m_thumbnails[i]);
                delete m_thumbnails[i];
                m_thumbnails.removeAt(i);
            }
        }
        
        if (!m_thumbnails.isEmpty()) {
            int lastIndex = m_thumbnails.size() - 1;
            row = lastIndex / m_columnsCount;
            col = lastIndex % m_columnsCount;
            
            // Move to the next position
            col++;
            if (col >= m_columnsCount) {
                col = 0;
                row++;
            }
        }
    }
    
    for (int i = 0; i < numImages; ++i) {
        const auto &item = images[i];
        
        // Check if file exists before creating thumbnail
        QFileInfo fileInfo(item.filePath);
        if (!fileInfo.exists() || !fileInfo.isReadable()) {
            qDebug() << "Image file does not exist or is not readable:" << item.filePath;
            continue;  // Skip this image
        }
        
        // Create and add thumbnail
        QPixmap thumbnail = createThumbnail(item.filePath, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
        ImageThumbnail *thumbnailLabel = new ImageThumbnail(item.filePath, this);
        thumbnailLabel->setPixmap(thumbnail);
        
        // Add filename overlay at the bottom of the thumbnail
        QFileInfo fileNameInfo(item.filePath);
        QString fileName = fileNameInfo.fileName();
        
        // Create overlay container with dark background - store it as a property of the thumbnail
        QFrame* overlay = new QFrame(thumbnailLabel);
        overlay->setObjectName("filenameOverlay"); // Set object name for finding it later
        overlay->setStyleSheet("background-color: rgba(0, 0, 0, 0.7);");
        overlay->setFixedHeight(20);
        
        // Create label for the filename
        QLabel* fileNameLabel = new QLabel(fileName, overlay);
        fileNameLabel->setStyleSheet("color: white; background: transparent;");
        fileNameLabel->setAlignment(Qt::AlignCenter);
        // Truncate filename if too long (more than 30 chars)
        if (fileName.length() > 30) {
            fileNameLabel->setText(fileName.left(13) + "..." + fileName.right(13));
        }
        
        // Layout for the overlay
        QHBoxLayout* overlayLayout = new QHBoxLayout(overlay);
        overlayLayout->setContentsMargins(5, 0, 5, 0);
        overlayLayout->addWidget(fileNameLabel);
        
        // Position the overlay at the bottom of the thumbnail
        // Width and position will be adjusted in updateGridLayout()
        overlay->setFixedWidth(thumbnailLabel->width());
        overlay->move(0, THUMBNAIL_HEIGHT - overlay->height());
        
        // Connect the thumbnail click signal
        connect(thumbnailLabel, &ImageThumbnail::thumbnailClicked, 
                this, &ImageGallery::handleThumbnailClicked);
        
        // Add to grid
        m_gridLayout->addWidget(thumbnailLabel, row, col);
        m_thumbnails.append(thumbnailLabel);
        
        // Update row and column
        col++;
        if (col >= m_columnsCount) {
            col = 0;
            row++;
        }
    }
    
    // Display a message when no images are found
    if (m_thumbnails.isEmpty()) {
        // Create a special ImageThumbnail for the "no images" message
        ImageThumbnail *noImagesLabel = new ImageThumbnail("", this);
        noImagesLabel->setText("No images found matching your search criteria");
        noImagesLabel->setAlignment(Qt::AlignCenter);
        m_gridLayout->addWidget(noImagesLabel, 0, 0, 1, m_columnsCount);
        m_thumbnails.append(noImagesLabel);
    } else if (images.size() > 0) {
        // This final row + 1 position is where we'll add the Load More button 
        // or nothing if we don't have more images
        
        if (m_hasMoreImages) {
            // Update Load More button text with current count info
            m_loadMoreButton->setText(tr("Load More Images (%1 of %2)")
                                  .arg(m_currentOffset)
                                  .arg(m_totalCount));
            
            // Add to layout and show
            m_gridLayout->addWidget(m_loadMoreButton, row + 1, 0, 1, m_columnsCount, Qt::AlignCenter);
            m_loadMoreButton->setVisible(true);
            m_loadMoreButton->raise(); // Ensure it's on top
            
            qDebug() << "Added Load More button at row" << row + 1 << "showing" 
                    << m_currentOffset << "of" << m_totalCount;
        } else {
            m_loadMoreButton->setVisible(false);
        }
        
        m_loadingIndicator->setVisible(false);
    }
    
    // Add stretch to the bottom of the grid, but after the Load More button
    m_gridLayout->setRowStretch(row + 3, 1);
}

void ImageGallery::clearGallery()
{
    // Remove all thumbnails
    for (auto thumbnail : m_thumbnails) {
        m_gridLayout->removeWidget(thumbnail);
        disconnect(thumbnail, nullptr, this, nullptr);
        delete thumbnail;
    }
    
    m_thumbnails.clear();
}

void ImageGallery::handleSearchTextChanged(const QString &searchText)
{
    if (m_dbManager) {
        // Clear existing search results
        clearGallery();
        
        // Store the search text for tracking
        m_lastSearchQuery = searchText;
        
        // Reset pagination for new search
        m_currentOffset = 0;
        m_totalCount = 0;
        m_hasMoreImages = false;
        m_isLoading = true;
        
        // Show loading indicator
        m_loadingIndicator->setText(tr("Searching..."));
        m_loadingIndicator->show();
        m_gridLayout->addWidget(m_loadingIndicator, 0, 0, 1, m_columnsCount);
        
        // Initiate the threaded search with pagination
        m_dbManager->searchImages(searchText, m_currentOffset, m_pageSize);
    }
}

void ImageGallery::handleSearchResults(const QList<DatabaseManager::ImageItem> &results, 
                                      const QString &searchText, int offset, int limit, 
                                      int totalCount)
{
    // Only update display if this is the result for the most recent search
    if (searchText == m_lastSearchQuery) {
        m_isLoading = false;
        m_totalCount = totalCount;
        
        // If this is the first page or a different search
        bool isFirstPage = (offset == 0);
        
        // Display images, clearing existing ones only if this is first page
        displayImages(results, isFirstPage);
        
        // Update pagination state
        m_currentOffset = offset + results.size();
        m_totalCount = totalCount;
        m_hasMoreImages = m_currentOffset < totalCount;
        
        // Always hide the loading indicator when search completes
        m_loadingIndicator->hide();
        
        // Update Load More button if we have more images
        // Update Load More button state based on whether there are more images
        if (m_hasMoreImages) {
            // Update button text with current counts
            m_loadMoreButton->setText(tr("Load More Images (%1 of %2)")
                                   .arg(m_currentOffset)
                                   .arg(totalCount));
            
            // Add to layout at bottom of grid and ensure it's visible
            int row = (m_thumbnails.size() / m_columnsCount);
            m_gridLayout->removeWidget(m_loadMoreButton); // Remove from any previous location
            m_gridLayout->addWidget(m_loadMoreButton, row + 1, 0, 1, m_columnsCount, Qt::AlignCenter);
            m_loadMoreButton->setVisible(true);
            m_loadMoreButton->raise(); // Ensure it's on top
            
            qDebug() << "Search results - Added Load More button at row" << row + 1 
                    << "showing" << m_currentOffset << "of" << totalCount;
        } else {
            // Hide both indicators if no more images
            m_loadingIndicator->setVisible(false);
            m_loadMoreButton->setVisible(false);
        }
    }
}

// Method to append more images to the gallery
void ImageGallery::appendImages(const QList<DatabaseManager::ImageItem> &images)
{
    // Call displayImages with clearExisting=false
    displayImages(images, false);
}

// Handle search start event
void ImageGallery::handleSearchStarted(const QString &searchText)
{
    // Show loading indicator or status message
    // This is called when a search operation begins
    
    // Set loading state
    m_isLoading = true;
    
    // Only show "Searching" indicator when search actually begins (not during typing)
    if (!m_thumbnails.isEmpty() && !m_lastSearchQuery.isEmpty() && searchText != m_lastSearchQuery) {
        // New search, keep thumbnails but show loading overlay
        m_loadingIndicator->setText(tr("Searching..."));
        m_loadingIndicator->show();
        
        // Move loading indicator to be visible
        m_scrollArea->verticalScrollBar()->setValue(0);
    }
}

// Load more images when scrolled to bottom
void ImageGallery::loadMoreImages()
{
    if (!m_dbManager || m_isLoading || !m_hasMoreImages) {
        return;
    }
    
    m_isLoading = true;
    
    // Hide the Load More button while loading
    m_loadMoreButton->hide();
    
    // Show loading indicator
    m_loadingIndicator->setText(tr("Loading more images (%1 of %2)...")
                               .arg(m_currentOffset)
                               .arg(m_totalCount));
    m_loadingIndicator->show();
    
    // Position loading indicator at bottom of grid
    int row = (m_thumbnails.size() / m_columnsCount);
    m_gridLayout->addWidget(m_loadingIndicator, row + 1, 0, 1, m_columnsCount);
    
    // Request next page from database
    m_dbManager->searchImages(m_lastSearchQuery, m_currentOffset, m_pageSize);
}

// Handle scroll to bottom event
void ImageGallery::handleScrolledToBottom()
{
    if (!m_isLoading && m_hasMoreImages) {
        qDebug() << "Loading more images from handleScrolledToBottom";
        loadMoreImages();
    }
}

// Handle Load More button click
void ImageGallery::handleLoadMoreClicked()
{
    if (!m_isLoading && m_hasMoreImages) {
        qDebug() << "Loading more images from Load More button";
        
        // Hide the button and show loading indicator during loading
        m_loadMoreButton->hide();
        m_loadingIndicator->setText(tr("Loading images..."));
        m_loadingIndicator->show();
        int row = (m_thumbnails.size() / m_columnsCount);
        m_gridLayout->addWidget(m_loadingIndicator, row + 1, 0, 1, m_columnsCount);
        
        // Request more images
        loadMoreImages();
        
        // Debug output
        qDebug() << "Total thumbnails:" << m_thumbnails.size() 
                 << "Grid size:" << m_gridLayout->rowCount() << "x" << m_gridLayout->columnCount()
                 << "Has more:" << m_hasMoreImages;
    }
}

// Set page size for lazy loading
void ImageGallery::setPageSize(int pageSize)
{
    if (pageSize > 0) {
        m_pageSize = pageSize;
    }
}

// Reset pagination state to initial values
void ImageGallery::resetPagination()
{
    // Reset pagination state variables
    m_currentOffset = 0;
    m_isLoading = false;
    m_hasMoreImages = false;
    m_totalCount = 0;
    
    // Hide loading indicators
    if (m_loadingIndicator) {
        m_loadingIndicator->hide();
    }
    
    // Hide "Load More" button until we know there are more images
    if (m_loadMoreButton) {
        m_loadMoreButton->hide();
    }
}

// Override wheel event to detect end of scrolling
void ImageGallery::wheelEvent(QWheelEvent *event)
{
    QWidget::wheelEvent(event);
    
    // Don't check scroll position during the wheel event
    // This will be handled by the eventFilter
}

void ImageGallery::updateSearchTextDisplay(const QString &searchText)
{
    // Update the UI to reflect the current search text without performing a search
    // This gives immediate feedback while typing, before the actual search happens
    
    // Store the search text for tracking
    m_lastSearchQuery = searchText;
    
    // Keep existing thumbnails visible without distracting visual changes
    
    // If we have a "no results" message showing, update it quietly
    for (auto thumbnail : m_thumbnails) {
        if (thumbnail->text().contains("No images found")) {
            thumbnail->setText(tr("Search in progress..."));
        }
    }
    
    // No typing indicator or popups while typing
    // Just wait for the actual search to complete
}

void ImageGallery::handleThumbnailClicked(const QString &filePath)
{
    // Show a wait cursor while attempting to open the file
    QApplication::setOverrideCursor(Qt::WaitCursor);
    
    // Check if file exists
    QFileInfo fileInfo(filePath);
    if (fileInfo.exists() && fileInfo.isFile()) {
        try {
            // Use QDesktopServices to open the file with the default application
            bool success = QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
            if (!success) {
                qDebug() << "Failed to open file with default application:" << filePath;
            }
        } catch (const std::exception &e) {
            qDebug() << "Exception occurred while opening file:" << e.what();
        }
    } else {
        qDebug() << "File does not exist:" << filePath;
    }
    
    // Restore cursor
    QApplication::restoreOverrideCursor();
}

QPixmap ImageGallery::createThumbnail(const QString &filePath, int width, int height)
{
    // Verify file exists before attempting to load
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists() || !fileInfo.isReadable()) {
        qDebug() << "Image file does not exist or is not readable:" << filePath;
        return createPlaceholderThumbnail(width, height, "File not found");
    }
    
    // Try to load the image
    QPixmap pixmap(filePath);
    
    // If loading failed, create a placeholder
    if (pixmap.isNull()) {
        qDebug() << "Failed to load image:" << filePath;
        return createPlaceholderThumbnail(width, height, "Failed to load");
    }
    
    // Scale pixmap while maintaining aspect ratio
    return pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}

void ImageGallery::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    
    // Trigger grid layout update when gallery is resized
    QTimer::singleShot(0, this, &ImageGallery::updateGridLayout);
    
    // Ensure the container widget fills the viewport width
    if (m_scrollArea && m_containerWidget) {
        int viewportWidth = m_scrollArea->viewport()->width();
        m_containerWidget->setMinimumWidth(viewportWidth);
        
        // Immediately update layout to avoid visual glitches during resize
        m_gridLayout->activate();
        m_containerWidget->updateGeometry();
    }
}

// Event filter to catch viewport resize events and scroll events
bool ImageGallery::eventFilter(QObject *watched, QEvent *event)
{
    // Check if this is a resize event on the viewport
    if (watched == m_scrollArea->viewport() && event->type() == QEvent::Resize) {
        // Update the grid layout
        updateGridLayout();
        return false; // Allow event to propagate
    }
    
    // Check for various scroll-related events
    if (watched == m_scrollArea->viewport() &&
        (event->type() == QEvent::Wheel || 
         event->type() == QEvent::MouseMove ||
         event->type() == QEvent::MouseButtonRelease)) {
         
        QScrollBar* vScrollBar = m_scrollArea->verticalScrollBar();
        if (vScrollBar) {
            int max = vScrollBar->maximum();
            int current = vScrollBar->value();
            int viewportHeight = m_scrollArea->viewport()->height();
            
            // If we're near the bottom and not already loading, prepare to load more
            // Use a percentage of viewport height as threshold for very tall viewports
            int dynamicThreshold = qMin(LOAD_THRESHOLD_PX, viewportHeight / 4);
            
            if ((max - current) <= dynamicThreshold && max > 0 && !m_isLoading && m_hasMoreImages) {
                // Cancel any pending timer and start a new one for debouncing
                m_scrollTimer->stop();
                m_scrollTimer->start();
                
                // We'll rely on the Load More button for explicit user action
                // rather than showing a loading indicator during scroll
            }
        }
    }
    
    // Pass unhandled events to parent
    return QWidget::eventFilter(watched, event);
}

void ImageGallery::handleContainerResized()
{
    // This will be called periodically to check if container size changed
    static int lastWidth = -1;
    int currentWidth = m_containerWidget->width();
    
    if (currentWidth > 0 && currentWidth != lastWidth) {
        lastWidth = currentWidth;
        updateGridLayout();
    }
}

void ImageGallery::updateGridLayout()
{
    // Get the viewport width to determine available space
    int viewportWidth = m_scrollArea->viewport()->width();
    if (viewportWidth <= 0) {
        return; // Can't determine width yet
    }
    
    // Force container width to match the viewport
    m_containerWidget->setMinimumWidth(viewportWidth);
    
    // Account for left and right margins in the grid layout
    int availableWidth = viewportWidth - (m_gridLayout->contentsMargins().left() + m_gridLayout->contentsMargins().right());
    
    // Calculate how many thumbnails can fit, accounting for spacing between them
    int effectiveThumbnailWidth = THUMBNAIL_WIDTH + THUMBNAIL_SPACING;
    
    // Calculate column count, allowing even very narrow views to show at least 1 column
    int newColumnCount = std::max(1, availableWidth / (THUMBNAIL_WIDTH + 2 * THUMBNAIL_SPACING));
    
    // Only update if column count changes
    if (newColumnCount != m_columnsCount) {
        m_columnsCount = newColumnCount;
        
        // If we have thumbnails, rearrange them in the grid
        if (!m_thumbnails.isEmpty()) {
            // We need to readjust all the thumbnails to the new grid layout
            // First remove all widgets from the grid
            for (auto thumbnail : m_thumbnails) {
                m_gridLayout->removeWidget(thumbnail);
            }
            
            // Then add them back in the new arrangement
            int row = 0, col = 0;
            for (auto thumbnail : m_thumbnails) {
                m_gridLayout->addWidget(thumbnail, row, col);
                col++;
                if (col >= m_columnsCount) {
                    col = 0;
                    row++;
                }
            }
    
            // Force layout update
            m_gridLayout->invalidate();
            m_containerWidget->adjustSize();
            m_containerWidget->updateGeometry();
            
            // Handle single column mode specially
            if (m_columnsCount == 1) {
                // Center the thumbnails in the viewport
                int centeringMargin = (viewportWidth - THUMBNAIL_WIDTH) / 2;
                centeringMargin = std::max(THUMBNAIL_SPACING, centeringMargin);
                m_gridLayout->setContentsMargins(centeringMargin, THUMBNAIL_SPACING, centeringMargin, THUMBNAIL_SPACING);
                
                // Let all thumbnails expand to fill available width in single column mode
                for (auto thumbnail : m_thumbnails) {
                    thumbnail->setMaximumWidth(THUMBNAIL_WIDTH);
                    thumbnail->setAlignment(Qt::AlignCenter);
                    
                    // Update the overlay to match thumbnail width
                    QFrame* overlay = thumbnail->findChild<QFrame*>("filenameOverlay");
                    if (overlay) {
                        overlay->setFixedWidth(THUMBNAIL_WIDTH);
                        overlay->move(0, THUMBNAIL_HEIGHT - overlay->height());
                    }
                }
            } else {
                // For multi-column, use minimal margins
                m_gridLayout->setContentsMargins(THUMBNAIL_SPACING, THUMBNAIL_SPACING, THUMBNAIL_SPACING, THUMBNAIL_SPACING);
                
                // Reset thumbnail constraints
                for (auto thumbnail : m_thumbnails) {
                    thumbnail->setMaximumWidth(QWIDGETSIZE_MAX);
                    
                    // Update the overlay to match thumbnail width in multi-column mode
                    QFrame* overlay = thumbnail->findChild<QFrame*>("filenameOverlay");
                    if (overlay) {
                        overlay->setFixedWidth(thumbnail->width());
                        overlay->move(0, THUMBNAIL_HEIGHT - overlay->height());
                    }
                }
                
                // For multi-column, let the container fill the viewport
                m_containerWidget->setMinimumWidth(viewportWidth);
            }
            
            // Force update of overlay position and size after a short delay
            // This ensures the overlays are sized correctly after all layout changes
            QTimer::singleShot(50, this, [this]() {
                for (auto thumbnail : m_thumbnails) {
                    QFrame* overlay = thumbnail->findChild<QFrame*>("filenameOverlay");
                    if (overlay) {
                        overlay->setFixedWidth(thumbnail->width());
                        overlay->move(0, THUMBNAIL_HEIGHT - overlay->height());
                    }
                }
            });
            
            // Update the layout again after a short delay to handle edge cases
            QTimer::singleShot(10, this, [this](){
                m_gridLayout->update();
                m_containerWidget->update();
            });
        }
    }
}

QPixmap ImageGallery::createPlaceholderThumbnail(int width, int height, const QString &message)
{
    // Create a placeholder image with text
    QPixmap placeholder(width, height);
    placeholder.fill(Qt::lightGray);
    
    // Draw some text on the placeholder
    QPainter painter(&placeholder);
    painter.setPen(Qt::darkGray);
    
    // Use a nice font
    QFont font = painter.font();
    font.setPointSize(12);
    font.setBold(true);
    painter.setFont(font);
    
    // Draw the text centered in the pixmap
    painter.drawText(placeholder.rect(), Qt::AlignCenter, message);
    
    // Add a border
    painter.setPen(QPen(Qt::darkGray, 2));
    painter.drawRect(1, 1, width-2, height-2);
    
    return placeholder;
}