jQuery(document).ready(function($) {
    console.log('PinnerPress: Top Images JavaScript loaded');

    // Initialize variables
    var currentImages = [];
    var currentView = 'table'; // Default to table view
    var currentSortField = 'total-clicks';
    var currentSortOrder = 'desc';
    var currentPage = 1;
    var totalPages = 1;
    var totalImages = 0;

    // Get settings from localized script
    var isPremium = pinnerpressVars.isPremium || false;
    var imageLimit = pinnerpressVars.imageLimit || 50;
    var perPage = pinnerpressVars.perPage || 25;

    // Define ajaxurl if not already defined
    if (typeof ajaxurl === 'undefined') {
        var ajaxurl = pinnerpressVars.ajaxurl;
    }

    console.log('Top Images: Initializing...');
    console.log('Ajax URL:', ajaxurl);
    console.log('Is Premium:', isPremium);
    console.log('Image Limit:', imageLimit);
    console.log('Per Page:', perPage);

    // Load top images on page load
    loadTopImages();

    /**
     * Load top images data from server
     */
    function loadTopImages() {
        console.log('Loading top images, page:', currentPage);

        // Show loading message
        $('.loading-message').show();
        $('.top-images-container').hide();
        $('.no-data-message').hide();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pinnerpress_get_top_images',
                page: currentPage,
                per_page: perPage,
                limit: imageLimit,
                nonce: pinnerpressVars.nonce
            },
            success: function(response) {
                console.log('Top images response:', response);

                if (response.success && response.data) {
                    currentImages = response.data.images || [];
                    totalImages = response.data.total || 0;
                    totalPages = response.data.total_pages || 1;
                    currentPage = response.data.page || 1;

                    if (currentImages.length > 0) {
                        displayImages();
                        updatePagination();
                        $('.loading-message').hide();
                        $('.top-images-container').show();
                    } else {
                        $('.loading-message').hide();
                        $('.no-data-message').show();
                    }
                } else {
                    console.error('Error loading top images:', response);
                    $('.loading-message').hide();
                    $('.no-data-message').show();
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error loading top images:', error);
                console.error('Response:', xhr.responseText);
                $('.loading-message').hide();
                $('.no-data-message').show();
            }
        });
    }

    /**
     * Display images in current view (table or grid)
     */
    function displayImages() {
        if (currentView === 'table') {
            displayTableView();
        } else {
            displayGridView();
        }
    }

    /**
     * Display images in table view
     */
    function displayTableView() {
        var tbody = $('.image-table-container tbody');
        tbody.empty();

        if (currentImages.length === 0) {
            tbody.append('<tr><td colspan="11" style="text-align: center; padding: 40px;">No images to display</td></tr>');
            return;
        }

        currentImages.forEach(function(image, index) {
            var row = '<tr data-image-index="' + index + '">';

            // Rank
            row += '<td class="column-rank"><strong>#' + image.rank + '</strong></td>';

            // Image preview
            row += '<td class="column-preview">';
            row += '<img src="' + escapeHtml(image.image_url) + '" style="width: 60px; height: 60px; object-fit: cover; cursor: pointer; border: 1px solid #ddd; border-radius: 2px;" class="view-image-details" data-image-index="' + index + '">';
            row += '</td>';

            // Post title (show count if multiple posts)
            var posts = image.posts || [];
            var postCount = posts.length;
            row += '<td class="column-post-title">';
            if (postCount > 1) {
                row += '<a href="' + escapeHtml(image.post_url) + '" target="_blank">' + escapeHtml(image.post_title) + '</a>';
                row += '<span style="color: #666; font-size: 11px; margin-left: 5px;">(+' + (postCount - 1) + ' more)</span>';
            } else if (postCount === 1) {
                row += '<a href="' + escapeHtml(image.post_url) + '" target="_blank">' + escapeHtml(image.post_title) + '</a>';
            } else {
                row += '<span style="color: #999;">Unknown</span>';
            }
            row += '</td>';

            // DISABLED: Impressions tracking removed
            // var impressions = image.analytics.impressions || 0;
            // row += '<td class="column-impressions">' + formatNumber(impressions) + '</td>';

            // Pin Clicks
            var pinClicks = image.analytics.pin_button_click || 0;
            row += '<td class="column-pin-clicks">' + formatNumber(pinClicks) + '</td>';

            // DISABLED: Pin CTR (requires impressions)
            // var pinCtr = image.analytics.pin_ctr || 0;
            // var pinCtrClass = getConversionClass(pinCtr);
            // row += '<td class="column-pin-ctr"><span class="conversion-rate ' + pinCtrClass + '">' + pinCtr.toFixed(2) + '%</span></td>';

            // Banner Clicks
            var bannerClicks = image.analytics.image_banner_click || 0;
            row += '<td class="column-banner-clicks">' + formatNumber(bannerClicks) + '</td>';

            // DISABLED: Banner CTR (requires impressions)
            // var bannerCtr = image.analytics.banner_ctr || 0;
            // var bannerCtrClass = getConversionClass(bannerCtr);
            // row += '<td class="column-banner-ctr"><span class="conversion-rate ' + bannerCtrClass + '">' + bannerCtr.toFixed(2) + '%</span></td>';

            // Total Clicks (combined)
            var totalClicks = image.analytics.total_clicks || 0;
            row += '<td class="column-total-clicks"><strong>' + formatNumber(totalClicks) + '</strong></td>';

            // Actions
            row += '<td class="column-actions">';
            // View Details button with icon
            row += '<button type="button" class="button view-image-details" data-image-index="' + index + '" title="View Details">';
            row += '<span class="dashicons dashicons-visibility"></span>';
            row += '</button>';
            // View Post button with icon
            row += '<a href="' + escapeHtml(image.post_url) + '" target="_blank" class="button" title="View Post">';
            row += '<span class="dashicons dashicons-external"></span>';
            row += '</a>';
            row += '</td>';

            row += '</tr>';
            tbody.append(row);
        });

        // Add click handlers for viewing details
        $('.view-image-details').on('click', function() {
            var imageIndex = parseInt($(this).data('image-index'));
            openImageDetailModal(imageIndex);
        });
    }

    /**
     * Display images in grid view
     */
    function displayGridView() {
        var container = $('.image-grid-container');
        container.empty();

        if (currentImages.length === 0) {
            container.append('<p style="text-align: center; padding: 40px;">No images to display</p>');
            return;
        }

        var gridHtml = '';

        currentImages.forEach(function(image, index) {
            var totalClicks = image.analytics.total_clicks || 0;
            var pinClicks = image.analytics.pin_button_click || 0;
            var bannerClicks = image.analytics.image_banner_click || 0;
            var posts = image.posts || [];
            var postCount = posts.length;

            gridHtml += '<div class="image-grid-card" data-image-index="' + index + '">';
            gridHtml += '<div class="rank-badge">#' + image.rank + '</div>';
            gridHtml += '<div class="image-preview"><img src="' + escapeHtml(image.image_url) + '" alt=""></div>';
            gridHtml += '<div class="card-body">';
            gridHtml += '<p class="post-title">' + escapeHtml(image.post_title);
            if (postCount > 1) {
                gridHtml += ' <span style="color: #999;">+' + (postCount - 1) + ' more</span>';
            }
            gridHtml += '</p>';
            gridHtml += '<p class="total-clicks">' + formatNumber(totalClicks) + '</p>';
            gridHtml += '<p class="total-clicks-label">Total Clicks</p>';
            gridHtml += '<div class="click-breakdown">';
            gridHtml += '<span><strong>Pin:</strong> ' + formatNumber(pinClicks) + '</span>';
            gridHtml += '<span><strong>Banner:</strong> ' + formatNumber(bannerClicks) + '</span>';
            gridHtml += '</div>';
            gridHtml += '</div>';
            gridHtml += '</div>';
        });

        container.html(gridHtml);

        // Add click handlers
        $('.image-grid-card').on('click', function() {
            var imageIndex = parseInt($(this).data('image-index'));
            openImageDetailModal(imageIndex);
        });
    }

    /**
     * Update pagination controls
     */
    function updatePagination() {
        $('#displaying-num').text(totalImages + ' items');
        $('#current-page-display').text(currentPage);
        $('#total-pages-display').text(totalPages);

        // Enable/disable pagination buttons
        $('#first-page, #prev-page').prop('disabled', currentPage === 1);
        $('#next-page, #last-page').prop('disabled', currentPage === totalPages);
    }

    /**
     * Open image detail modal
     */
    function openImageDetailModal(imageIndex) {
        var image = currentImages[imageIndex];
        if (!image) {
            console.error('Image not found at index:', imageIndex);
            return;
        }

        updateModalContent(image, imageIndex);
        $('.image-detail-modal').fadeIn();
    }

    /**
     * Update modal content with image details
     */
    function updateModalContent(image, currentIndex) {
        var modal = $('.image-detail-modal');
        var body = modal.find('.modal-body');

        // Clear previous content
        body.empty();

        // Add navigation controls
        var navHtml = '<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid #ddd;">';

        // Previous button
        if (currentIndex > 0) {
            navHtml += '<button class="button prev-image" data-index="' + (currentIndex - 1) + '">';
            navHtml += '<span class="dashicons dashicons-arrow-left-alt2" style="vertical-align: middle; margin-right: 3px;"></span>Previous</button>';
        } else {
            navHtml += '<button class="button" disabled style="opacity: 0.5;">';
            navHtml += '<span class="dashicons dashicons-arrow-left-alt2" style="vertical-align: middle; margin-right: 3px;"></span>Previous</button>';
        }

        // Image counter
        navHtml += '<span style="color: #666;">' + (currentIndex + 1) + ' of ' + currentImages.length + ' (Rank #' + image.rank + ')</span>';

        // Next button
        if (currentIndex < currentImages.length - 1) {
            navHtml += '<button class="button next-image" data-index="' + (currentIndex + 1) + '">';
            navHtml += 'Next<span class="dashicons dashicons-arrow-right-alt2" style="vertical-align: middle; margin-left: 3px;"></span></button>';
        } else {
            navHtml += '<button class="button" disabled style="opacity: 0.5;">';
            navHtml += 'Next<span class="dashicons dashicons-arrow-right-alt2" style="vertical-align: middle; margin-left: 3px;"></span></button>';
        }

        navHtml += '</div>';
        body.append(navHtml);

        // Add navigation event handlers
        body.find('.prev-image, .next-image').on('click', function() {
            var newIndex = parseInt($(this).data('index'));
            var newImage = currentImages[newIndex];
            updateModalContent(newImage, newIndex);
        });

        // Add image preview and details
        var content = '<div style="display: flex; gap: 30px; align-items: flex-start;">';

        // Left side - Image
        content += '<div style="flex: 0 0 400px; max-width: 50%;">';
        content += '<img src="' + escapeHtml(image.image_url) + '" style="width: 100%; height: auto; border: 1px solid #ddd; border-radius: 4px;">';
        content += '</div>';

        // Right side - Stats
        content += '<div style="flex: 1; min-width: 300px;">';

        // Header - show all posts where this image appears
        var posts = image.posts || [];
        var postCount = posts.length;

        content += '<div style="margin-bottom: 20px;">';
        content += '<h4 style="margin: 0 0 10px 0; color: #333;">Appears in ' + postCount + ' post' + (postCount !== 1 ? 's' : '') + ':</h4>';

        if (postCount > 0) {
            content += '<div style="max-height: 150px; overflow-y: auto; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; padding: 10px;">';
            posts.forEach(function(post, idx) {
                content += '<div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0;' + (idx < posts.length - 1 ? ' border-bottom: 1px solid #eee;' : '') + '">';
                content += '<span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-right: 10px;">' + escapeHtml(post.post_title) + '</span>';
                content += '<a href="' + escapeHtml(post.post_url) + '" target="_blank" class="button button-small" style="flex-shrink: 0;">';
                content += '<span class="dashicons dashicons-external" style="vertical-align: middle; font-size: 14px;"></span>';
                content += '</a>';
                content += '</div>';
            });
            content += '</div>';
        } else {
            content += '<p style="color: #666; margin: 0;">No posts found for this image.</p>';
        }

        content += '</div>'; // End header

        // Image analytics grid
        content += '<h4 style="margin-bottom: 15px; color: #333;">Image Analytics</h4>';
        content += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px; background: #f5f5f5; padding: 20px; border-radius: 4px;">';

        // Rank
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Rank</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">#' + image.rank + '</div>';
        content += '</div>';

        // Total clicks
        var totalClicks = image.analytics.total_clicks || 0;
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Total Clicks</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">' + formatNumber(totalClicks) + '</div>';
        content += '</div>';

        // Pin clicks
        var pinClicks = image.analytics.pin_button_click || 0;
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Pin Button Clicks</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">' + formatNumber(pinClicks) + '</div>';
        content += '</div>';

        // Banner clicks
        var bannerClicks = image.analytics.image_banner_click || 0;
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Image Banner Clicks</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">' + formatNumber(bannerClicks) + '</div>';
        content += '</div>';

        // DISABLED: Impressions tracking removed
        // var impressions = image.analytics.impressions || 0;
        // content += '<div>';
        // content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Impressions</div>';
        // content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(impressions) + '</div>';
        // content += '</div>';

        // DISABLED: Conversion Rate (requires impressions)
        // var conversionRate = image.analytics.conversion_rate || 0;
        // var conversionColor = getConversionColor(conversionRate);
        // content += '<div>';
        // content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Conversion Rate</div>';
        // content += '<div style="font-size: 24px; font-weight: 600; color: ' + conversionColor + ';">' + conversionRate.toFixed(2) + '%</div>';
        // content += '</div>';

        content += '</div>'; // End image analytics grid

        // Image details
        content += '<div style="margin-top: 15px; padding: 15px; background: #f9f9f9; border-radius: 4px; font-size: 12px; color: #666;">';
        content += '<strong>Image URL:</strong><br>';
        content += '<a href="' + escapeHtml(image.image_url) + '" target="_blank" style="word-break: break-all; font-family: monospace; font-size: 11px; color: #E60023; text-decoration: none;">' + escapeHtml(image.image_url) + '</a>';
        if (image.attachment_id) {
            content += '<br><br><strong>Attachment ID:</strong> ' + image.attachment_id;
        }
        if (image.image_id) {
            content += '<br><br><strong>Image ID:</strong> ' + escapeHtml(image.image_id);
        }
        content += '</div>';

        content += '</div>'; // End right side
        content += '</div>'; // End flex container

        // Append the content after navigation
        body.append(content);
    }

    /**
     * View toggle handlers
     */
    $('.view-toggle-btn').on('click', function() {
        var newView = $(this).data('view');

        if (newView === currentView) {
            return;
        }

        // Update active state
        $('.view-toggle-btn').attr('aria-pressed', 'false');
        $(this).attr('aria-pressed', 'true');

        // Update current view
        currentView = newView;

        // Toggle visibility
        if (currentView === 'table') {
            $('.image-table-container').show();
            $('.image-grid-container').hide();
        } else {
            $('.image-table-container').hide();
            $('.image-grid-container').show();
        }

        // Re-render the view
        displayImages();
    });

    /**
     * Pagination button handlers
     */
    $('#first-page').on('click', function() {
        if (currentPage !== 1) {
            currentPage = 1;
            loadTopImages();
        }
    });

    $('#prev-page').on('click', function() {
        if (currentPage > 1) {
            currentPage--;
            loadTopImages();
        }
    });

    $('#next-page').on('click', function() {
        if (currentPage < totalPages) {
            currentPage++;
            loadTopImages();
        }
    });

    $('#last-page').on('click', function() {
        if (currentPage !== totalPages) {
            currentPage = totalPages;
            loadTopImages();
        }
    });

    /**
     * Export CSV handler
     */
    $('#export-csv').on('click', function() {
        if (!isPremium) {
            alert('CSV export is a premium feature. Please upgrade to access this functionality.');
            return;
        }

        exportToCSV();
    });

    /**
     * Export current data to CSV
     */
    function exportToCSV() {
        if (currentImages.length === 0) {
            alert('No data to export');
            return;
        }

        // MODIFIED: Removed impressions, CTR, and conversion rate columns
        var csv = 'Rank,Post Count,Post Titles,Post URLs,Image URL,Pin Clicks,Banner Clicks,Total Clicks\n';

        currentImages.forEach(function(image) {
            var posts = image.posts || [];
            var postTitles = posts.map(function(p) { return p.post_title; }).join(' | ');
            var postUrls = posts.map(function(p) { return p.post_url; }).join(' | ');

            csv += image.rank + ',';
            csv += posts.length + ',';
            csv += '"' + postTitles.replace(/"/g, '""') + '",';
            csv += '"' + postUrls.replace(/"/g, '""') + '",';
            csv += '"' + image.image_url.replace(/"/g, '""') + '",';
            csv += (image.analytics.pin_button_click || 0) + ',';
            csv += (image.analytics.image_banner_click || 0) + ',';
            csv += (image.analytics.total_clicks || 0) + '\n';
        });

        // Create download link
        var blob = new Blob([csv], { type: 'text/csv' });
        var url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'pinnerpress-top-images-page-' + currentPage + '.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }

    /**
     * Handle modal close
     */
    $('.close, .image-detail-modal').on('click', function(e) {
        if (e.target === this) {
            $('.image-detail-modal').fadeOut();
        }
    });

    /**
     * Keyboard navigation for modal
     */
    $(document).on('keydown', function(e) {
        if ($('.image-detail-modal').is(':visible')) {
            if (e.key === 'Escape') {
                $('.image-detail-modal').fadeOut();
            }
        }
    });

    /**
     * Sorting handlers
     */
    $('.sortable a').on('click', function(e) {
        e.preventDefault();

        var th = $(this).parent();
        var sortField = th.data('sort');

        // Toggle sort order if clicking the same field
        if (sortField === currentSortField) {
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
        } else {
            currentSortField = sortField;
            currentSortOrder = 'desc';
        }

        // Update sorting indicators
        $('.sortable').removeClass('asc desc');
        th.addClass(currentSortOrder);

        // Sort the images
        sortImages();
        displayImages();
    });

    /**
     * Sort images based on current sort field and order
     */
    function sortImages() {
        currentImages.sort(function(a, b) {
            var aVal, bVal;

            switch(currentSortField) {
                // DISABLED: impressions sorting removed
                // case 'impressions':
                //     aVal = a.analytics.impressions || 0;
                //     bVal = b.analytics.impressions || 0;
                //     break;
                case 'pin-clicks':
                    aVal = a.analytics.pin_button_click || 0;
                    bVal = b.analytics.pin_button_click || 0;
                    break;
                // DISABLED: pin-ctr sorting removed (requires impressions)
                // case 'pin-ctr':
                //     aVal = a.analytics.pin_ctr || 0;
                //     bVal = b.analytics.pin_ctr || 0;
                //     break;
                case 'banner-clicks':
                    aVal = a.analytics.image_banner_click || 0;
                    bVal = b.analytics.image_banner_click || 0;
                    break;
                // DISABLED: banner-ctr sorting removed (requires impressions)
                // case 'banner-ctr':
                //     aVal = a.analytics.banner_ctr || 0;
                //     bVal = b.analytics.banner_ctr || 0;
                //     break;
                case 'total-clicks':
                    aVal = a.analytics.total_clicks || 0;
                    bVal = b.analytics.total_clicks || 0;
                    break;
                // DISABLED: conversion sorting removed (requires impressions)
                // case 'conversion':
                //     aVal = a.analytics.conversion_rate || 0;
                //     bVal = b.analytics.conversion_rate || 0;
                //     break;
                default:
                    aVal = a.analytics.total_clicks || 0;
                    bVal = b.analytics.total_clicks || 0;
            }

            if (currentSortOrder === 'asc') {
                return aVal - bVal;
            } else {
                return bVal - aVal;
            }
        });
    }

    /**
     * Helper Functions
     */

    function formatNumber(num) {
        return num.toLocaleString();
    }

    function escapeHtml(text) {
        if (!text) return '';
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.toString().replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    function getCTRColor(ctr) {
        if (ctr >= 5) return '#28a745';  // Green for high CTR
        if (ctr >= 2) return '#ffc107';  // Yellow for medium CTR
        return '#dc3545';  // Red for low CTR
    }

    function getConversionColor(rate) {
        if (rate >= 5) return '#28a745';  // Green
        if (rate >= 2) return '#ffc107';  // Yellow
        return '#dc3545';  // Red
    }

    function getConversionClass(rate) {
        if (rate >= 5) return 'excellent';
        if (rate >= 2) return 'good';
        if (rate >= 1) return 'fair';
        return 'poor';
    }
});
