jQuery(document).ready(function($) {
    console.log('PinnerPress: Image Analytics JavaScript loaded');
    
    // Initialize variables
    var currentPostId = null;
    var currentImages = [];
    var currentPostAnalytics = null;
    var currentView = 'table'; // Default to table view
    var currentSortField = 'pin-clicks';
    var currentSortOrder = 'desc';
    
    // Define ajaxurl if not already defined
    if (typeof ajaxurl === 'undefined') {
        var ajaxurl = pinnerpress_ajax.ajax_url;
    }
    
    console.log('Image Analytics: Initializing...');
    console.log('Ajax URL:', ajaxurl);
    console.log('Is Premium:', pinnerpress_ajax.is_premium);
    console.log('Select2 available:', typeof $.fn.select2);
    
    // Always initialize Select2 since this is a premium-only page
    setTimeout(function() {
        initializeSelect2Dropdown();
    }, 100);
    
    // Initialize Select2 dropdown
    function initializeSelect2Dropdown() {
        console.log('Setting up Select2...');
        
        try {
            $('#post-select').select2({
                ajax: {
                    url: ajaxurl,
                    dataType: 'json',
                    delay: 250,
                    cache: false,  // Disable caching to ensure fresh results
                    transport: function(params, success, failure) {
                        console.log('Select2 AJAX transport called with params:', params);
                        var $request = $.ajax(params);
                        $request.then(success);
                        $request.fail(failure);
                        return $request;
                    },
                    data: function(params) {
                        console.log('Select2 data function called with params:', params);
                        return {
                            action: 'pinnerpress_get_posts_for_analytics',
                            search: params.term || '',
                            page: params.page || 1,
                            nonce: pinnerpress_ajax.nonce
                        };
                    },
                    processResults: function(data, params) {
                        console.log('Select2 processResults called with data:', data);
                        
                        // Always log the full response data structure
                        if (data.success && data.data) {
                            console.log('Full response data:', JSON.stringify(data.data, null, 2));
                        }
                        
                        // Log debug info if available
                        if (data.success && data.data && data.data.debug) {
                            console.log('=== PinnerPress Search Debug ===');
                            console.log('Search term:', data.data.debug.search_term);
                            console.log('WHERE clause:', data.data.debug.where_clause);
                            console.log('Query params:', data.data.debug.query_params);
                            console.log('Total found:', data.data.debug.total_found);
                            console.log('Final SQL:', data.data.debug.final_sql);
                            console.log('================================');
                        } else {
                            console.log('No debug info in response. Search term was:', params.term);
                        }
                        
                        params.page = params.page || 1;
                        
                        if (data.success && data.data) {
                            return {
                                results: data.data.posts || [],
                                pagination: {
                                    more: data.data.has_more || false
                                }
                            };
                        }
                        return { results: [] };
                    },
                    error: function(xhr, status, error) {
                        console.error('Select2 AJAX error:', error);
                        console.error('Response:', xhr.responseText);
                    }
                },
                placeholder: 'Search for a post...',
                minimumInputLength: 0,
                width: '100%',
                allowClear: true,
                debug: true
            });
            
            console.log('Select2 initialized successfully');
            
            // Handle post selection
            $('#post-select').on('select2:select', function(e) {
                var postId = null;
                
                // Try to get post ID from event params
                if (e.params && e.params.data && e.params.data.id) {
                    postId = e.params.data.id;
                } else {
                    // Fallback to getting the selected value directly
                    postId = $('#post-select').val();
                }
                
                console.log('Post selected via Select2:', postId);
                if (postId) {
                    currentPostId = postId;
                    
                    // Update URL with post_id parameter
                    updateUrlWithPostId(postId);
                    
                    loadImageAnalytics(postId);
                }
            });
            
            $('#post-select').on('select2:unselect', function() {
                console.log('Post unselected');
                
                // Remove post_id from URL
                removePostIdFromUrl();
                
                resetDisplay();
            });
            
        } catch (error) {
            console.error('Error initializing Select2:', error);
            // Fall back to simple dropdown
            initializeSimpleDropdown();
        }
    }
    
    // Simple dropdown initialization (without Select2)
    function initializeSimpleDropdown() {
        $('#post-select').on('change', function() {
            var postId = $(this).val();
            console.log('Post selected (Simple):', postId);
            if (postId) {
                currentPostId = postId;
                
                // Update URL with post_id parameter
                updateUrlWithPostId(postId);
                
                loadImageAnalytics(postId);
            } else {
                // Remove post_id from URL
                removePostIdFromUrl();
                
                resetDisplay();
            }
        });
    }
    
    // Check for post_id URL parameter and auto-select if present
    function checkForAutoSelect() {
        const urlParams = new URLSearchParams(window.location.search);
        const postId = urlParams.get('post_id');
        
        if (postId) {
            console.log('Auto-selecting post from URL parameter:', postId);
            
            // Check if the post is already in the dropdown
            const existingOption = $('#post-select option[value="' + postId + '"]');
            
            if (existingOption.length > 0) {
                console.log('Post already in dropdown, selecting it');
                // Post is already in dropdown, select it
                $('#post-select').val(postId).trigger('change');
                
                // Directly load analytics to ensure it works
                console.log('Directly loading analytics for existing post:', postId);
                currentPostId = postId;
                loadImageAnalytics(postId);
            } else {
                console.log('Post not in dropdown, loading it first');
                // Post not in dropdown, load it first
                loadSpecificPost(postId);
            }
        } else {
            console.log('No post_id parameter found in URL');
        }
    }
    
    // Load a specific post and add it to the dropdown
    function loadSpecificPost(postId) {
        console.log('Loading specific post:', postId);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pinnerpress_get_post_by_id',
                post_id: postId,
                nonce: pinnerpress_ajax.nonce
            },
            success: function(response) {
                console.log('Load specific post response:', response);
                if (response.success && response.data.post) {
                    const post = response.data.post;
                    console.log('Post loaded successfully:', post);
                    
                    // Add post to dropdown if not already there
                    const existingOption = $('#post-select option[value="' + post.id + '"]');
                    if (existingOption.length === 0) {
                        console.log('Adding post to dropdown');
                        const option = new Option(post.text, post.id, true, true);
                        $('#post-select').append(option);
                    }
                    
                    // Select the post in dropdown
                    console.log('Selecting post in dropdown');
                    $('#post-select').val(post.id).trigger('change');
                    
                    // Directly load analytics
                    console.log('Directly loading analytics for post:', post.id);
                    currentPostId = post.id;
                    loadImageAnalytics(post.id);
                } else {
                    console.error('Failed to load specific post:', response.data || response);
                    showError('Post not found or could not be loaded.');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading specific post:', error);
                console.error('Response:', xhr.responseText);
                showError('Error loading post. Please try selecting manually.');
            }
        });
    }
    
    // Check for auto-select after initialization with a delay to ensure Select2 is ready
    setTimeout(function() {
        checkForAutoSelect();
    }, 500);
    
    // Handle date range update (for legacy compatibility)
    $('#update-date-range').on('click', function() {
        if (currentPostId) {
            loadImageAnalytics(currentPostId);
        }
    });
    
    // Handle new date controls update
    $('#pinnerpress-update-chart').on('click', function() {
        if (currentPostId) {
            loadImageAnalytics(currentPostId);
        }
    });
    
    // Listen for refresh event triggered by date preset buttons
    $(document).on('pinnerpress-refresh-image-analytics', function() {
        console.log('Refresh event received');
        if (currentPostId) {
            loadImageAnalytics(currentPostId);
        }
    });
    
    // Date preset button handlers
    $('.pinnerpress-date-preset').on('click', function() {
        const days = parseInt($(this).data('days'));
        
        // Use the server's date as the source of truth
        const serverDateStr = $('.pinnerpress-image-analytics-page').data('server-date');
        const endDate = new Date(serverDateStr + 'T00:00:00'); // Use server date to avoid timezone issues

        // Check for premium access for 30/90 day presets
        const hasTrulyPremium = pinnerpress_ajax.is_truly_premium;
        if (!hasTrulyPremium && (days === 30 || days === 90)) {
            alert('🚀 Unlock PinnerPress Premium - Upgrade to premium to unlock advanced features including: Call-out Banners, Image Control, Custom CTA Banners, Follow Buttons, Rich Pins, Hidden Pins, Custom Descriptions, Repin Attribution, Post Analytics, and Image Analytics');
            return;
        }

        // Calculate start date based on the server's end date
        const startDate = new Date(endDate.getTime());
        startDate.setDate(startDate.getDate() - (days -1));

        const startDateStr = formatDate(startDate);
        const endDateStr = formatDate(endDate);

        $('#pinnerpress-start-date').val(startDateStr);
        $('#pinnerpress-end-date').val(endDateStr);

        // Update the active state for the preset buttons
        $('.pinnerpress-date-preset').removeClass('active');
        $(this).addClass('active');

        // Trigger the chart and table data to refresh
        loadAnalyticsData();
    });

    // Enforce date range limits for free/trial users
    function enforceDateRangeLimits(start, end) {
        if (typeof hasPremiumAnalytics !== 'undefined' && hasPremiumAnalytics) {
            return { startDate: start, endDate: end };
        }
        
        // For non-premium users, enforce the 7-day limit relative to server date
        const serverDateStr = $('.pinnerpress-image-analytics-page').data('server-date');
        const today = new Date(serverDateStr + 'T00:00:00');
        
        const sevenDaysAgo = new Date(today.getTime());
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 6); // 7 days inclusive
        
        const startDate = new Date(start);
        const endDate = new Date(end);
        
        // If start date is more than 7 days ago, adjust it
        if (startDate < sevenDaysAgo) {
            startDate = formatDate(sevenDaysAgo);
        }
        
        // If end date is in the future (compared to server date), set to server's today
        if (endDate > today) {
            endDate = formatDate(today);
        }

        // Check if the selected range is more than 7 days
        const diffTime = Math.abs(endDate - startDate);
        
        return { startDate: startDate, endDate: endDate };
    }
    
    // Load image analytics for selected post
    function loadImageAnalytics(postId) {
        // Try new date inputs first, fall back to old ones
        var startDate = $('#pinnerpress-start-date').val() || $('#start-date').val();
        var endDate = $('#pinnerpress-end-date').val() || $('#end-date').val();
        
        // Enforce date range limits
        const enforcedDates = enforceDateRangeLimits(startDate, endDate);
        startDate = enforcedDates.startDate;
        endDate = enforcedDates.endDate;
        
        // Update inputs with enforced dates
        if ($('#pinnerpress-start-date').length > 0) {
            $('#pinnerpress-start-date').val(startDate);
            $('#pinnerpress-end-date').val(endDate);
        }
        if ($('#start-date').length > 0) {
            $('#start-date').val(startDate);
            $('#end-date').val(endDate);
        }
        
        console.log('Loading analytics for post:', postId, 'Date range:', startDate, 'to', endDate);
        
        // Show loading state
        showLoading();
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pinnerpress_get_post_images_analytics',
                post_id: postId,
                start_date: startDate,
                end_date: endDate,
                nonce: pinnerpress_ajax.nonce
            },
            success: function(response) {
                console.log('Analytics response:', response);
                if (response.success && response.data) {
                    displayImageAnalytics(response.data);
                } else {
                    console.error('Server returned error:', response.data);
                    showError('Error loading analytics data: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                console.error('Response Text:', xhr.responseText);
                showError('Error loading analytics data. Please try again.');
            }
        });
    }
    
    // Display image analytics in grid
    function displayImageAnalytics(data) {
        currentImages = data.images;
        currentPostAnalytics = data.post_analytics || null;
        
        // Update post info
        $('#selected-post-title').text(data.post_title);
        $('#selected-post-link').attr('href', '/?p=' + data.post_id);
        $('.selected-post-info').show();
        
        // Update summary stats (now includes post analytics)
        updateSummaryStats(data.summary, currentPostAnalytics);
        
        // Display images
        displaySortedImages();
        
        // Show/hide appropriate sections
        hideLoading();
        $('.no-data-message').hide();
        $('.summary-stats, .image-analytics-container, .pinnerpress-table-controls').show();
        $('#export-csv').prop('disabled', false);
    }
    
    // Show loading state
    function showLoading() {
        $('.no-data-message').html('<p><span class="pinnerpress-spinner"></span> Loading image analytics...</p>');
        $('.summary-stats, .image-analytics-grid').hide();
    }
    
    // Hide loading state
    function hideLoading() {
        $('.no-data-message').hide();
    }
    
    // Show error message
    function showError(message) {
        $('.no-data-message').html('<p class="notice notice-error">' + message + '</p>').show();
        $('.summary-stats, .image-analytics-container, .pinnerpress-table-controls').hide();
    }
    
    // Reset display to initial state
    function resetDisplay() {
        currentPostId = null;
        currentImages = [];
        currentPostAnalytics = null;
        $('.no-data-message').html('<p>Select a post to view image analytics</p>').show();
        $('.summary-stats, .image-analytics-container, .selected-post-info, .pinnerpress-table-controls, .post-analytics-summary').hide();
        $('#export-csv').prop('disabled', true);
    }
    
    // Display images with current sorting and filtering
    function displaySortedImages() {
        if (currentImages.length === 0) {
            var emptyMessage = '<p style="text-align: center; padding: 40px; color: #666;">No images found in this post.</p>';
            $('.image-grid-container').html(emptyMessage);
            $('.image-table-container tbody').html('<tr><td colspan="8" style="text-align: center; padding: 40px; color: #666;">No images found in this post.</td></tr>');
            return;
        }
        
        var grid = $('.image-grid-container');
        grid.empty();
        
        // Always show all images (no filtering)
        var imagesToShow = currentImages;
        
        // Sort images - use table sort if in table view
        if (currentView === 'table') {
            imagesToShow = sortImagesForTable(imagesToShow, currentSortField, currentSortOrder);
        } else {
            // For grid view, default to sorting by most clicks
            imagesToShow = sortImages(imagesToShow, 'clicks-desc');
        }
        
        // Render based on current view
        if (currentView === 'table') {
            renderTableView(imagesToShow);
        } else {
            renderGridView(imagesToShow);
        }
    }
    
    // Render table view
    function renderTableView(images) {
        var tbody = $('.image-table-container tbody');
        tbody.empty();
        
        images.forEach(function(image) {
            var row = createTableRow(image);
            tbody.append(row);
        });
        
        // Show count if filtered
                    if (images.length !== currentImages.length) {
                $('.image-table-container').prepend(
                    '<div class="filter-info" style="margin-bottom: 10px; padding: 10px; background: #f0f0f0; border-radius: 4px;">' +
                    '<strong>' + images.length + '</strong> of <strong>' + currentImages.length + '</strong> images shown</div>'
                );
            } else {
                $('.image-table-container .filter-info').remove();
            }
            
            // Update table styling for proper column widths
            $('.image-table-container table').css('table-layout', 'fixed');
            $('.image-table-container .column-preview').css('width', '80px');
            $('.image-table-container .column-impressions').css('width', '100px');
            $('.image-table-container .column-pin-clicks').css('width', '80px');
            $('.image-table-container .column-pin-ctr').css('width', '80px');
            $('.image-table-container .column-banner-clicks').css('width', '80px');
            $('.image-table-container .column-banner-ctr').css('width', '80px');
            $('.image-table-container .column-conversion').css('width', '100px');
            $('.image-table-container .column-actions').css('width', '140px');
    }
    
    // Create table row for an image
    function createTableRow(image) {
        var hasClicks = image.analytics.total_clicks > 0;
        var displayName = image.image_id || image.image_url.split('/').pop();
        
        var row = '<tr data-image-id="' + escapeHtml(image.image_id || '') + '">';
        
        // Image preview
        row += '<td class="column-preview">';
        row += '<img src="' + escapeHtml(image.thumbnail_url || image.image_url) + '" alt="' + escapeHtml(image.alt_text || '') + '">';
        row += '</td>';
        
        // Image ID
        row += '<td class="column-image-id">' + escapeHtml(displayName) + '</td>';
        
        // Get post analytics values
        var postImpressions = (currentPostAnalytics && currentPostAnalytics.totals) ? currentPostAnalytics.totals.impressions || 0 : 0;
        var postPinClicks = (currentPostAnalytics && currentPostAnalytics.totals) ? currentPostAnalytics.totals.pin_clicks || 0 : 0;
        var postBannerClicks = (currentPostAnalytics && currentPostAnalytics.totals) ? currentPostAnalytics.totals.banner_clicks || 0 : 0;
        var postFollowClicks = (currentPostAnalytics && currentPostAnalytics.totals) ? currentPostAnalytics.totals.follow_clicks || 0 : 0;
        
        // DISABLED: Impressions tracking removed
        // var imageImpressions = (image.analytics && image.analytics.impression) ? image.analytics.impression : 0;
        // row += '<td class="column-impressions">' + formatNumber(imageImpressions) + '</td>';

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

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

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

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

        // DISABLED: Conversion rate requires impressions
        // row += '<td class="column-conversion">';
        // var imageConversionRate = imageImpressions > 0 ? (image.analytics.total_clicks / imageImpressions) * 100 : 0;
        // var imageConversionClass = getConversionClass(imageConversionRate);
        // row += '<span class="conversion-rate ' + imageConversionClass + '">' + imageConversionRate.toFixed(2) + '%</span>';
        // row += '</td>';
        
        // Actions
        row += '<td class="column-actions">';
        // View Details button
        row += '<button class="button view-image-details" title="' + escapeHtml('View Details') + '">';
        row += '<span class="dashicons dashicons-visibility"></span>';
        row += '</button>';
        if (currentPostId) {
            // View Analytics button
            var imageAnalyticsUrl = admin_url('admin.php?page=pinnerpress-image-analytics&post_id=' + currentPostId);
            row += '<a href="' + escapeHtml(imageAnalyticsUrl) + '" class="button" title="' + escapeHtml('View in Image Analytics') + '">';
            row += '<span class="dashicons dashicons-chart-line"></span>';
            row += '</a>';
            // View Post button
            var postUrl = '/?p=' + currentPostId;
            row += '<a href="' + escapeHtml(postUrl) + '" target="_blank" class="button" title="' + escapeHtml('View Post') + '">';
            row += '<span class="dashicons dashicons-external"></span>';
            row += '</a>';
        }
        row += '</td>';
        
        row += '</tr>';
        
        return row;
    }
    
    // Get CSS class for conversion rate styling (fixed logic)
    function getConversionClass(rate) {
        if (rate >= 5) return 'excellent';
        if (rate >= 2) return 'good';
        if (rate >= 1) return 'fair';
        return 'poor'; // This covers 0% and other low rates
    }
    
    // Helper function to get admin URL (fallback if not defined)
    function admin_url(path) {
        if (typeof ajaxurl !== 'undefined') {
            return ajaxurl.replace('admin-ajax.php', path);
        }
        return '/wp-admin/' + path;
    }
    
    // Get conversion rate color for modal display
    function getConversionModalColor(rate) {
        if (rate >= 5) return '#4CAF50'; // Green for excellent
        if (rate >= 2) return '#FF9800'; // Orange for good
        if (rate >= 1) return '#FFC107'; // Yellow for fair
        return '#E60023'; // Red for poor (including 0%)
    }
    
    // Get time ago string
    function getTimeAgo(date) {
        var now = new Date();
        var diffMs = now - date;
        var diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        var diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        var diffMinutes = Math.floor(diffMs / (1000 * 60));
        
        if (diffMinutes < 1) {
            return 'Just now';
        } else if (diffMinutes < 60) {
            return diffMinutes + 'm ago';
        } else if (diffHours < 24) {
            return diffHours + 'h ago';
        } else if (diffDays === 0) {
            return 'Today';
        } else if (diffDays === 1) {
            return 'Yesterday';
        } else if (diffDays < 7) {
            return diffDays + ' days ago';
        } else {
            return Math.floor(diffDays / 7) + 'w ago';
        }
    }
    
    // Render grid view
    function renderGridView(images) {
        var grid = $('.image-grid-container');
        grid.empty();
        
        // Remove any filter info from table view
        $('.image-table-container .filter-info').remove();
        
        // Create image cards
        images.forEach(function(image) {
            var card = createImageCard(image);
            grid.append(card);
        });
        
        // Show count
        if (images.length !== currentImages.length) {
            grid.prepend('<div class="filter-info" style="margin-bottom: 20px; padding: 10px; background: #f0f0f0; border-radius: 4px;">' +
                        '<strong>' + images.length + '</strong> of <strong>' + currentImages.length + '</strong> images shown</div>');
        }
    }
    
    // Sort images for table view
    function sortImagesForTable(images, sortField, sortOrder) {
        var sorted = images.slice(); // Make a copy

        sorted.sort(function(a, b) {
            var aVal, bVal;

            // DISABLED: Impressions tracking removed
            // var aImpressions = (a.analytics && a.analytics.impression) ? a.analytics.impression : 0;
            // var bImpressions = (b.analytics && b.analytics.impression) ? b.analytics.impression : 0;

            switch(sortField) {
                case 'id':
                    aVal = a.image_id || '';
                    bVal = b.image_id || '';
                    return sortOrder === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);

                // DISABLED: Impressions tracking removed
                // case 'impressions':
                //     return sortOrder === 'asc' ? aImpressions - bImpressions : bImpressions - aImpressions;

                case 'pin-clicks':
                    aVal = a.analytics.pin_button_click || 0;
                    bVal = b.analytics.pin_button_click || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Pin CTR requires impressions
                // case 'pin-ctr':
                //     aVal = aImpressions > 0 ? ((a.analytics.pin_button_click || 0) / aImpressions) * 100 : 0;
                //     bVal = bImpressions > 0 ? ((b.analytics.pin_button_click || 0) / bImpressions) * 100 : 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'banner-clicks':
                    aVal = a.analytics.image_banner_click || 0;
                    bVal = b.analytics.image_banner_click || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Banner CTR requires impressions
                // case 'banner-ctr':
                //     aVal = aImpressions > 0 ? ((a.analytics.image_banner_click || 0) / aImpressions) * 100 : 0;
                //     bVal = bImpressions > 0 ? ((b.analytics.image_banner_click || 0) / bImpressions) * 100 : 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Conversion rate requires impressions
                // case 'conversion':
                //     aVal = aImpressions > 0 ? ((a.analytics.total_clicks || 0) / aImpressions) * 100 : 0;
                //     bVal = bImpressions > 0 ? ((b.analytics.total_clicks || 0) / bImpressions) * 100 : 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'clicks':
                    aVal = a.analytics.total_clicks || 0;
                    bVal = b.analytics.total_clicks || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'last-click':
                    aVal = a.analytics.last_click ? new Date(a.analytics.last_click).getTime() : 0;
                    bVal = b.analytics.last_click ? new Date(b.analytics.last_click).getTime() : 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                default:
                    return 0;
            }
        });

        return sorted;
    }
    
    // Sort images based on selected criteria (for grid view)
    function sortImages(images, sortBy) {
        var sorted = images.slice(); // Make a copy
        
        switch(sortBy) {
            case 'clicks-desc':
                sorted.sort(function(a, b) {
                    return b.analytics.total_clicks - a.analytics.total_clicks;
                });
                break;
            case 'clicks-asc':
                sorted.sort(function(a, b) {
                    return a.analytics.total_clicks - b.analytics.total_clicks;
                });
                break;
            case 'id-asc':
                sorted.sort(function(a, b) {
                    var aId = a.image_id || '';
                    var bId = b.image_id || '';
                    return aId.localeCompare(bId);
                });
                break;
            case 'id-desc':
                sorted.sort(function(a, b) {
                    var aId = a.image_id || '';
                    var bId = b.image_id || '';
                    return bId.localeCompare(aId);
                });
                break;
            case 'recent-click':
                sorted.sort(function(a, b) {
                    var aTime = a.analytics.last_click ? new Date(a.analytics.last_click).getTime() : 0;
                    var bTime = b.analytics.last_click ? new Date(b.analytics.last_click).getTime() : 0;
                    return bTime - aTime;
                });
                break;
        }
        
        return sorted;
    }
    
    
    // Update summary statistics
    function updateSummaryStats(summary, postAnalytics) {
        // Image analytics summary
        $('#total-images').text(summary.total_images || 0);
        $('#total-clicks').text(summary.total_clicks || 0);

        if (summary.best_performing_image) {
            $('#best-image').text(summary.best_performing_image.clicks + ' clicks');
        } else {
            $('#best-image').text('-');
        }

        // Calculate average
        var avg = summary.total_images > 0 ? (summary.total_clicks / summary.total_images).toFixed(1) : 0;
        $('#avg-clicks').text(avg);

        // Post analytics summary (if available)
        if (postAnalytics && postAnalytics.totals) {
            // DISABLED: Impressions tracking removed
            // var impressions = postAnalytics.totals.impressions || 0;
            // $('#post-impressions').text(formatNumber(impressions)).css('color', '#E60023');

            // Update pin clicks (always red)
            $('#post-pin-clicks').text(formatNumber(postAnalytics.totals.pin_clicks || 0)).css('color', '#E60023');

            // Update banner clicks (always red)
            $('#post-banner-clicks').text(formatNumber(postAnalytics.totals.banner_clicks || 0)).css('color', '#E60023');

            // Update follow clicks (always red)
            $('#post-follow-clicks').text(formatNumber(postAnalytics.totals.follow_clicks || 0)).css('color', '#E60023');

            // Update call-out banner clicks (always red)
            $('#post-callout-clicks').text(formatNumber(postAnalytics.totals.call_out_banner_clicks || 0)).css('color', '#E60023');

            // DISABLED: Conversion rate requires impressions
            // var conversionRate = postAnalytics.conversion_rates.overall || 0;
            // $('#post-conversion-rate').text(conversionRate.toFixed(2) + '%').css('color', '#E60023');

            // Show post analytics section
            $('.post-analytics-summary').show();
        } else {
            // Hide post analytics section if no data
            $('.post-analytics-summary').hide();
        }
    }
    
    // Format number with commas
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    // Create an image card element
    function createImageCard(image) {
        var hasClicks = image.analytics.total_clicks > 0;
        var card = $('<div class="image-card' + (hasClicks ? '' : ' no-clicks') + '" data-image-id="' + (image.image_id || '') + '"></div>');
        
        // Image preview - make it clickable to show modal
        var imgHtml = '<div class="image-preview" title="Click to view full image">' +
                      '<img src="' + escapeHtml(image.thumbnail_url || image.image_url) + '" alt="' + escapeHtml(image.alt_text || '') + '">' +
                      '</div>';
        card.append(imgHtml);
        
        // Card body
        var body = $('<div class="image-card-body"></div>');
        
        // Image ID or filename
        var displayName = image.image_id || image.image_url.split('/').pop();
        body.append('<div class="image-name" title="' + escapeHtml(image.image_url) + '">' + escapeHtml(displayName) + '</div>');
        
        // Stats grid
        var statsGrid = $('<div class="image-stats"></div>');
        
        // Total clicks
        var totalClicks = image.analytics.total_clicks || 0;
        statsGrid.append(createStatItem('Total Clicks', totalClicks));
        
        // Pin button clicks
        var pinClicks = image.analytics.pin_button_click || 0;
        statsGrid.append(createStatItem('Pin Clicks', pinClicks));
        
        // Banner clicks
        var bannerClicks = image.analytics.image_banner_click || 0;
        statsGrid.append(createStatItem('Image Banner Clicks', bannerClicks));
        
        // Last clicked or status
        if (hasClicks && image.analytics.last_click) {
            var lastClick = new Date(image.analytics.last_click);
            var timeAgo = getTimeAgo(lastClick);
            statsGrid.append(createStatItem('Last Click', timeAgo));
        } else {
            statsGrid.append(createStatItem('Status', 'Never clicked'));
        }
        
        body.append(statsGrid);
        card.append(body);
        
        // Click handler for image preview
        card.find('.image-preview').on('click', function(e) {
            e.stopPropagation();
            showImageDetails(image);
        });
        
        // Make entire card clickable
        card.on('click', function() {
            showImageDetails(image);
        });
        
        return card;
    }
    
    // Create a stat item element
    function createStatItem(label, value) {
        return $('<div class="stat-item">' +
                '<div class="stat-label">' + escapeHtml(label) + '</div>' +
                '<div class="stat-number">' + escapeHtml(value.toString()) + '</div>' +
                '</div>');
    }
    
    // Show detailed analytics for an image
    function showImageDetails(image) {
        var modal = $('.image-detail-modal');
        var body = modal.find('.modal-body');
        
        // Find current image index in the displayed images
        var displayedImages = getDisplayedImages();
        var currentIndex = displayedImages.findIndex(function(img) {
            return img.image_id === image.image_id;
        });
        
        // Update modal with navigation
        updateModalContent(image, currentIndex, displayedImages);
        
        // Show modal
        modal.fadeIn();
    }
    
    // Get currently displayed images (respecting sort)
    function getDisplayedImages() {
        var imagesToShow = currentImages;
        
        // Apply sort based on current view
        if (currentView === 'table') {
            return sortImagesForTable(imagesToShow, currentSortField, currentSortOrder);
        } else {
            return sortImages(imagesToShow, 'clicks-desc');
        }
    }
    
    // Update modal content with navigation
    function updateModalContent(image, currentIndex, displayedImages) {
        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 ' + displayedImages.length + '</span>';
        
        // Next button
        if (currentIndex < displayedImages.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 = displayedImages[newIndex];
            updateModalContent(newImage, newIndex, displayedImages);
        });
        
        // 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 with image name and View Post button
        content += '<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;">';
        
        // Image info
        var displayName = image.image_id || image.image_url.split('/').pop();
        content += '<h3 style="margin: 0; word-break: break-all; flex: 1; padding-right: 10px;">' + escapeHtml(displayName) + '</h3>';
        
        // View Post button
        var postUrl = '/?p=' + currentPostId;
        content += '<a href="' + escapeHtml(postUrl) + '" target="_blank" class="button button-secondary" style="white-space: nowrap;">';
        content += '<span class="dashicons dashicons-external" style="vertical-align: middle; margin-right: 3px;"></span>';
        content += 'View Post</a>';
        
        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;">';
        
        // Total clicks
        var totalImageClicks = image.analytics.total_clicks || 0;
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Image Clicks</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">' + totalImageClicks + '</div>';
        content += '</div>';
        
        // Pin clicks
        var imagePinClicks = image.analytics.pin_button_click || 0;
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Pin Clicks</div>';
        content += '<div style="font-size: 32px; font-weight: 600; color: #E60023;">' + imagePinClicks + '</div>';
        content += '</div>';
        
        // Banner clicks
        var imageBannerClicks = 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;">' + imageBannerClicks + '</div>';
        content += '</div>';
        
        // Last click
        content += '<div>';
        content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Last Click</div>';
        content += '<div style="font-size: 20px; font-weight: 600; color: #E60023;">';
        
        var hasClicks = image.analytics.total_clicks > 0;
        if (hasClicks && image.analytics.last_click) {
            var lastClick = new Date(image.analytics.last_click);
            var timeAgo = getTimeAgo(lastClick);
            content += timeAgo;
        } else {
            content += 'Never';
        }
        content += '</div>';
        content += '</div>';
        
        content += '</div>'; // End image analytics grid
        
        // Post analytics grid (if available)
        if (currentPostAnalytics && currentPostAnalytics.totals) {
            content += '<h4 style="margin-bottom: 15px; color: #333;">Post Analytics</h4>';
            content += '<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; background: #f9f9f9; padding: 20px; border-radius: 4px;">';

            // DISABLED: Impressions tracking removed
            // var impressions = currentPostAnalytics.totals.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>';

            // Post pin clicks
            var pinClicks = currentPostAnalytics.totals.pin_clicks || 0;
            var pinClicksColor = pinClicks === 0 ? '#E60023' : '#E60023';
            content += '<div>';
            content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Pin Clicks</div>';
            content += '<div style="font-size: 24px; font-weight: 600; color: ' + pinClicksColor + ';">' + formatNumber(pinClicks) + '</div>';
            content += '</div>';

            // Post banner clicks (always red)
            var bannerClicks = currentPostAnalytics.totals.banner_clicks || 0;
            content += '<div>';
            content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Banner Clicks</div>';
            content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(bannerClicks) + '</div>';
            content += '</div>';

            // Post follow clicks (always red)
            var followClicks = currentPostAnalytics.totals.follow_clicks || 0;
            content += '<div>';
            content += '<div style="text-transform: uppercase; font-size: 11px; color: #666; margin-bottom: 5px;">Follow Clicks</div>';
            content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(followClicks) + '</div>';
            content += '</div>';

            // DISABLED: Conversion rate requires impressions
            // var conversionRate = currentPostAnalytics.conversion_rates.overall || 0;
            // 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: #E60023;">' + conversionRate.toFixed(2) + '%</div>';
            // content += '</div>';

            // Total clicks (always red)
            var totalClicks = currentPostAnalytics.totals.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: 24px; font-weight: 600; color: #E60023;">' + formatNumber(totalClicks) + '</div>';
            content += '</div>';

            content += '</div>'; // End post analytics grid
        }
        
        // Additional details
        if (image.analytics.first_click || image.analytics.last_click) {
            content += '<div style="background: #fff; border: 1px solid #ddd; padding: 15px; border-radius: 4px;">';
            content += '<h4 style="margin-top: 0;">Timeline Details</h4>';
            content += '<ul style="margin: 0; padding-left: 20px;">';
            if (image.analytics.first_click) {
                content += '<li>First clicked: ' + formatDate(image.analytics.first_click) + '</li>';
            }
            if (image.analytics.last_click) {
                content += '<li>Last clicked: ' + formatDate(image.analytics.last_click) + '</li>';
            }
            content += '</ul>';
            content += '</div>';
        }
        
        // 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.alt_text) {
            content += '<br><br><strong>Alt Text:</strong> ' + escapeHtml(image.alt_text);
        }
        content += '</div>';
        
        content += '</div>'; // End right side
        content += '</div>'; // End flex container
        
        // Append the content after navigation
        body.append(content);
    }
    
    // Handle modal close
    $('.close, .image-detail-modal').on('click', function(e) {
        if (e.target === this) {
            $('.image-detail-modal').fadeOut();
        }
    });
    
    // Handle keyboard navigation in modal
    $(document).on('keydown', function(e) {
        if ($('.image-detail-modal').is(':visible')) {
            if (e.key === 'ArrowLeft') {
                $('.prev-image:not(:disabled)').click();
            } else if (e.key === 'ArrowRight') {
                $('.next-image:not(:disabled)').click();
            } else if (e.key === 'Escape') {
                $('.image-detail-modal').fadeOut();
            }
        }
    });
    
    // Handle CSV export
    $('#export-csv').on('click', function() {
        // Check for premium access
        if (typeof pinnerpressImageAnalytics !== 'undefined' && !pinnerpressImageAnalytics.is_premium) {
            alert('🚀 Unlock PinnerPress Premium - Upgrade to premium to unlock advanced features including: Call-out Banners, Image Control, Custom CTA Banners, Follow Buttons, Rich Pins, Hidden Pins, Custom Descriptions, Repin Attribution, Post Analytics, and Image Analytics');
            return;
        }
        
        if (!currentPostId || currentImages.length === 0) {
            return;
        }
        
        // Ask user what to export
        var exportAll = confirm('Export all images? Click OK for all images, Cancel for currently visible images only.');
        
        var imagesToExport;
        if (exportAll) {
            imagesToExport = currentImages;
        } else {
            // Get currently visible images
            imagesToExport = currentImages;
            // Use current sorting based on view
            if (currentView === 'table') {
                imagesToExport = sortImagesForTable(imagesToExport, currentSortField, currentSortOrder);
            } else {
                imagesToExport = sortImages(imagesToExport, 'clicks-desc');
            }
        }
        
        // Prepare CSV data with post analytics if available
        // DISABLED: Removed Image Impressions and Conversion Rate columns
        var csv = 'Image ID,Image URL,Alt Text,Attachment ID,Total Image Clicks,Pin Button Clicks,Image Banner Clicks,First Click,Last Click,Status';

        // Add additional post analytics columns if available
        if (currentPostAnalytics && currentPostAnalytics.totals) {
            csv += ',Post Pin Clicks,Post Banner Clicks,Post Follow Clicks';
        }
        csv += '\n';

        imagesToExport.forEach(function(image) {
            var hasClicks = image.analytics.total_clicks > 0;
            var status = hasClicks ? 'Clicked' : 'Never clicked';

            csv += '"' + (image.image_id || '') + '",';
            csv += '"' + image.image_url + '",';
            csv += '"' + (image.alt_text || '') + '",';
            csv += '"' + (image.attachment_id || '') + '",';

            // DISABLED: Image impressions tracking removed
            // var imageImpressions = (image.analytics && image.analytics.impression) ? image.analytics.impression : 0;
            // csv += imageImpressions + ',';

            csv += image.analytics.total_clicks + ',';
            csv += (image.analytics.pin_button_click || 0) + ',';
            csv += (image.analytics.image_banner_click || 0) + ',';

            // DISABLED: Conversion rate requires impressions
            // var conversionRate = imageImpressions > 0 ? ((image.analytics.total_clicks || 0) / imageImpressions * 100).toFixed(2) : '0.00';
            // csv += conversionRate + '%,';

            csv += '"' + (image.analytics.first_click || '') + '",';
            csv += '"' + (image.analytics.last_click || '') + '",';
            csv += '"' + status + '"';

            // Add additional post analytics data if available
            if (currentPostAnalytics && currentPostAnalytics.totals) {
                csv += ',' + (currentPostAnalytics.totals.pin_clicks || 0);
                csv += ',' + (currentPostAnalytics.totals.banner_clicks || 0);
                csv += ',' + (currentPostAnalytics.totals.follow_clicks || 0);
            }

            csv += '\n';
        });
        
        // Download CSV
        var blob = new Blob([csv], { type: 'text/csv' });
        var url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        var filename = 'pinnerpress-image-analytics-' + currentPostId + 
                      (exportAll ? '-all' : '-filtered') + 
                      '-' + new Date().toISOString().split('T')[0] + '.csv';
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    });
    
    // Update URL with post_id parameter
    function updateUrlWithPostId(postId) {
        var currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('post_id', postId);
        
        // Update the URL without reloading the page
        window.history.pushState({ postId: postId }, '', currentUrl.toString());
        
        console.log('Updated URL to:', currentUrl.toString());
    }
    
    // Remove post_id parameter from URL
    function removePostIdFromUrl() {
        var currentUrl = new URL(window.location.href);
        currentUrl.searchParams.delete('post_id');
        
        // Update the URL without reloading the page
        window.history.pushState({}, '', currentUrl.toString());
        
        console.log('Removed post_id from URL:', currentUrl.toString());
    }
    
    // Utility functions
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    function formatDate(date) {
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}:00`;
    }

    // Initialize view toggle
    $('.view-toggle-btn').on('click', function() {
        var view = $(this).data('view');
        if (view === currentView) return;
        
        // Update button states
        $('.view-toggle-btn').attr('aria-pressed', 'false');
        $(this).attr('aria-pressed', 'true');
        
        // Update current view
        currentView = view;
        
        // Show/hide appropriate containers
        if (view === 'table') {
            $('.image-table-container').show();
            $('.image-grid-container').hide();
        } else {
            $('.image-table-container').hide();
            $('.image-grid-container').show();
        }
        
        // Re-render the current data
        if (currentImages.length > 0) {
            displaySortedImages();
        }
    });
    
    // Handle table header clicks for sorting
    $(document).on('click', '.image-table-container th.sortable a', function(e) {
        e.preventDefault();
        
        var $th = $(this).parent();
        var sortField = $th.data('sort');
        
        // Toggle sort order if clicking the same column
        if (sortField === currentSortField) {
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
        } else {
            currentSortField = sortField;
            // Default to desc for numeric columns (to show highest first), asc for text columns
            var numericColumns = ['impressions', 'pin-clicks', 'pin-ctr', 'banner-clicks', 'banner-ctr', 'conversion'];
            currentSortOrder = numericColumns.includes(sortField) ? 'desc' : 'asc';
        }
        
        // Update visual indicators
        $('.image-table-container th').removeClass('asc desc');
        $th.addClass(currentSortOrder);
        
        // Re-render sorted data
        displaySortedImages();
    });
    
    // Handle table row clicks (but not action button clicks)
    $(document).on('click', '.image-table-container tbody tr', function(e) {
        // Don't trigger row click if clicking on action buttons
        if ($(e.target).closest('.column-actions').length > 0) {
            return;
        }
        
        var imageId = $(this).data('image-id');
        var image = currentImages.find(function(img) {
            return img.image_id === imageId;
        });
        if (image) {
            showImageDetails(image);
        }
    });
    
    // Handle action button clicks
    $(document).on('click', '.view-image-details', function(e) {
        e.stopPropagation();
        var imageId = $(this).closest('tr').data('image-id');
        var image = currentImages.find(function(img) {
            return img.image_id === imageId;
        });
        if (image) {
            showImageDetails(image);
        }
    });
}); 