jQuery(document).ready(function($) {
    // Gated debug helper
    function pinnerpressAdminDebugLog() {
        var debugParam = new URLSearchParams(window.location.search).get('pinnerpress_debug');
        if (debugParam === '1') {
            console.log.apply(console, arguments);
        }
    }
    function pinnerpressAdminDebugError() {
        var debugParam = new URLSearchParams(window.location.search).get('pinnerpress_debug');
        if (debugParam === '1') {
            console.error.apply(console, arguments);
        }
    }

    pinnerpressAdminDebugLog('PinnerPress: Post Analytics JavaScript loaded');
    
    // Initialize variables
    var currentPosts = [];
    // MODIFIED: Changed default sort from impressions to pin-clicks
    var currentSortField = 'pin-clicks';
    var currentSortOrder = 'desc';
    var currentPage = 1;
    var postsPerPage = 25;
    var isDataLimited = false; // Track if data is limited for free users
    
    // Define ajaxurl if not already defined
    if (typeof ajaxurl === 'undefined') {
        var ajaxurl = pinnerpress_ajax.ajax_url;
    }
    
    pinnerpressAdminDebugLog('Post Analytics: Initializing...');
    pinnerpressAdminDebugLog('Ajax URL:', ajaxurl);
    pinnerpressAdminDebugLog('Is Premium:', pinnerpress_ajax.is_premium);
    
    // Initialize by loading data
    loadPostAnalytics();
    
    // Handle posts per page change
    $('#posts-per-page').on('change', function() {
        var value = $(this).val();
        postsPerPage = value === 'all' ? 'all' : parseInt(value);
        currentPage = 1; // Reset to first page
        if (currentPosts.length > 0) {
            displaySortedPosts();
        }
    });
    
    // Handle pagination controls
    $(document).on('click', '.first-page:not(:disabled)', function() {
        currentPage = 1;
        displaySortedPosts();
    });
    
    $(document).on('click', '.prev-page:not(:disabled)', function() {
        currentPage--;
        displaySortedPosts();
    });
    
    $(document).on('click', '.next-page:not(:disabled)', function() {
        currentPage++;
        displaySortedPosts();
    });
    
    $(document).on('click', '.last-page:not(:disabled)', function() {
        var totalPages = postsPerPage === 'all' ? 1 : Math.ceil(currentPosts.length / postsPerPage);
        currentPage = totalPages;
        displaySortedPosts();
    });
    
    $(document).on('change', '.current-page', function() {
        var page = parseInt($(this).val());
        var totalPages = postsPerPage === 'all' ? 1 : Math.ceil(currentPosts.length / postsPerPage);
        
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
            displaySortedPosts();
        } else {
            $(this).val(currentPage); // Reset to current page if invalid
        }
    });
    
    // Handle date range update
    $('#pinnerpress-update-chart').on('click', function() {
        validateAndLoadAnalytics();
    });
    
    // Add validation for manual date changes
    $('#pinnerpress-start-date, #pinnerpress-end-date').on('change', function() {
        const hasTrulyPremium = pinnerpress_ajax.is_truly_premium;
        if (!hasTrulyPremium) {
            // For non-premium users, enforce 7-day limit
            const endDate = new Date();
            const maxStartDate = new Date(endDate.getTime() - (7 * 24 * 60 * 60 * 1000));
            
            const startDateInput = $('#pinnerpress-start-date');
            const endDateInput = $('#pinnerpress-end-date');
            
            const startDate = new Date(startDateInput.val());
            const currentEndDate = new Date(endDateInput.val());
            
            // Check if dates exceed 7-day limit
            if (startDate < maxStartDate || currentEndDate > endDate) {
                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');
                
                // Reset to last 7 days
                startDateInput.val(formatDate(maxStartDate));
                endDateInput.val(formatDate(endDate));
            }
        }
    });
    
    // Validate and load analytics
    function validateAndLoadAnalytics() {
        const hasTrulyPremium = pinnerpress_ajax.is_truly_premium;
        if (!hasTrulyPremium) {
            // For non-premium users, enforce 7-day limit before loading
            const endDate = new Date();
            const maxStartDate = new Date(endDate.getTime() - (7 * 24 * 60 * 60 * 1000));
            
            $('#pinnerpress-start-date').val(formatDate(maxStartDate));
            $('#pinnerpress-end-date').val(formatDate(endDate));
        }
        loadPostAnalytics();
    }
    
    // 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-post-analytics-page').data('server-date');
        const endDate = new Date(serverDateStr + 'T00:00:00'); // Use server date to avoid timezone issues

        // Check if this is a premium feature and user doesn't have truly premium
        const hasTrulyPremium = pinnerpress_ajax.is_truly_premium;
        if (!hasTrulyPremium && (days === 30 || days === 90)) {
            // Show upgrade message for disabled buttons
            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);
        
        // For free users, also update disabled inputs
        if (!hasTrulyPremium) {
            $('#pinnerpress-start-date-disabled').val(startDateStr);
            $('#pinnerpress-end-date-disabled').val(endDateStr);
        }
        
        // Update the active state for the preset buttons
        $('.pinnerpress-date-preset').removeClass('active');
        $(this).addClass('active');

        // Trigger data refresh
        loadPostAnalytics();
    });
    
    // Load post analytics data
    function loadPostAnalytics() {
        var startDate = $('#pinnerpress-start-date').val();
        var endDate = $('#pinnerpress-end-date').val();
        
        pinnerpressAdminDebugLog('Loading post analytics for date range:', startDate, 'to', endDate);
        
        // Show loading state
        showLoading();
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pinnerpress_get_post_analytics_data',
                start_date: startDate,
                end_date: endDate,
                nonce: pinnerpress_ajax.nonce
            },
            success: function(response) {
                pinnerpressAdminDebugLog('Post analytics response:', response);
                if (response.success && response.data) {
                    displayPostAnalytics(response.data);
                } else {
                    pinnerpressAdminDebugError('Server returned error:', response.data);
                    showError('Error loading analytics data: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                pinnerpressAdminDebugError('AJAX Error:', status, error);
                pinnerpressAdminDebugError('Response Text:', xhr.responseText);
                showError('Error loading analytics data. Please try again.');
            }
        });
    }
    
    // Display posts data
    function displayPostAnalytics(data) {
        currentPosts = data.posts || [];
        currentPage = 1; // Reset to first page when loading new data
        
        // Check if data is limited for free users
        isDataLimited = data.is_limited || false;
        
        // Update summary stats
        updateSummaryStats();
        
        // Display posts in table
        displaySortedPosts();
        
        // Set initial sort indicator
        $('#post-analytics-table th').removeClass('asc desc');
        $('#post-analytics-table th[data-sort="' + currentSortField + '"]').addClass(currentSortOrder);
        
        // Show/hide appropriate sections
        hideLoading();
        
        if (currentPosts.length === 0) {
            $('.no-data-message').show();
            $('.post-table-container').hide();
            $('.summary-stats').hide();
        } else {
            $('.no-data-message').hide();
            $('.post-table-container').show();
            $('.summary-stats').show();
            // Only show pagination for premium users with more than 25 posts
            if (isDataLimited || postsPerPage === 'all') {
                $('.pinnerpress-pagination').hide();
            } else {
                $('.pinnerpress-pagination').show();
            }
        }
    }
    
    // Update summary statistics
    function updateSummaryStats() {
        var totalPosts = currentPosts.length;
        // DISABLED: Impressions tracking removed
        // var totalImpressions = 0;
        var totalClicks = 0;
        var totalPinClicks = 0;
        var totalBannerClicks = 0;
        var totalFollowClicks = 0;
        var totalCalloutClicks = 0;

        currentPosts.forEach(function(post) {
            // DISABLED: Impressions tracking removed
            // totalImpressions += parseInt(post.total_impressions) || 0;
            totalClicks += parseInt(post.total_clicks) || 0;
            totalPinClicks += parseInt(post.total_pin_clicks) || 0;
            totalBannerClicks += parseInt(post.total_banner_clicks) || 0;
            totalFollowClicks += parseInt(post.total_follow_clicks) || 0;
            totalCalloutClicks += parseInt(post.total_call_out_banner_clicks) || 0;
        });

        // DISABLED: Conversion rate requires impressions
        // var avgConversion = totalImpressions > 0 ? ((totalClicks / totalImpressions) * 100).toFixed(2) : 0;

        $('#total-posts').text(totalPosts);
        // DISABLED: Impressions tracking removed
        // $('#total-impressions').text(formatNumber(totalImpressions));

        // Update total clicks
        $('#total-clicks').text(formatNumber(totalClicks));

        // DISABLED: Conversion rate requires impressions
        // $('#avg-conversion').text(avgConversion + '%');
    }
    
    // Display sorted posts in table with pagination
    function displaySortedPosts() {
        var posts = sortPosts(currentPosts, currentSortField, currentSortOrder);
        var tbody = $('#post-analytics-table tbody');
        tbody.empty();
        
        // Calculate pagination
        var totalPosts = posts.length;
        var totalPages = postsPerPage === 'all' ? 1 : Math.ceil(totalPosts / postsPerPage);
        
        // Ensure current page is valid
        if (currentPage > totalPages) {
            currentPage = totalPages || 1;
        }
        
        // Get posts for current page
        var startIndex = postsPerPage === 'all' ? 0 : (currentPage - 1) * postsPerPage;
        var endIndex = postsPerPage === 'all' ? totalPosts : Math.min(startIndex + postsPerPage, totalPosts);
        var pagePosts = posts.slice(startIndex, endIndex);
        
        // Display posts
        pagePosts.forEach(function(post) {
            var row = createTableRow(post);
            tbody.append(row);
        });
        
        // Update pagination controls
        updatePaginationControls(totalPosts, totalPages, startIndex + 1, endIndex);
    }
    
    // Create table row for a post
    function createTableRow(post) {
        var row = '<tr data-post-id="' + escapeHtml(post.post_id) + '">';
        
        // Image
        row += '<td class="column-preview">';
        if (post.featured_image && post.featured_image.url) {
            row += '<img src="' + escapeHtml(post.featured_image.url) + '" alt="">';
        } else {
            row += '<div class="default-placeholder">';
            row += '<span class="dashicons dashicons-format-image"></span>';
            row += '</div>';
        }
        row += '</td>';
        
        // Post Title
        row += '<td class="column-title">' + escapeHtml(post.post_title) + '</td>';

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

        // Pin Clicks
        row += '<td class="column-pin-clicks">' + formatNumber(post.total_pin_clicks || 0) + '</td>';

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

        // Banner Clicks
        row += '<td class="column-banner-clicks">' + formatNumber(post.total_banner_clicks || 0) + '</td>';

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

        // Follow Clicks
        row += '<td class="column-follow-clicks">' + formatNumber(post.total_follow_clicks || 0) + '</td>';

        // DISABLED: Follow CTR requires impressions
        // var followCtr = parseFloat(post.follow_conversion_rate) || 0;
        // var followCtrClass = getConversionClass(followCtr);
        // row += '<td class="column-follow-ctr"><span class="conversion-rate ' + followCtrClass + '">' +
        //        followCtr.toFixed(2) + '%</span></td>';

        // Callout Banner Clicks
        row += '<td class="column-callout-clicks">' + formatNumber(post.total_call_out_banner_clicks || 0) + '</td>';

        // DISABLED: Callout CTR requires impressions
        // var calloutCtr = parseFloat(post.call_out_banner_conversion_rate) || 0;
        // var calloutCtrClass = getConversionClass(calloutCtr);
        // row += '<td class="column-callout-ctr"><span class="conversion-rate ' + calloutCtrClass + '">' +
        //        calloutCtr.toFixed(2) + '%</span></td>';

        // Post Block Follow Clicks
        row += '<td class="column-block-clicks">' + formatNumber(post.total_block_editor_button_clicks || 0) + '</td>';

        // DISABLED: Block CTR requires impressions
        // var blockCtr = parseFloat(post.block_editor_button_conversion_rate) || 0;
        // var blockCtrClass = getConversionClass(blockCtr);
        // row += '<td class="column-block-ctr"><span class="conversion-rate ' + blockCtrClass + '">' +
        //        blockCtr.toFixed(2) + '%</span></td>';

        // DISABLED: Overall conversion rate requires impressions
        // var conversionRate = parseFloat(post.overall_conversion_rate) || 0;
        // var conversionClass = getConversionClass(conversionRate);
        // row += '<td class="column-conversion"><span class="conversion-rate ' + conversionClass + '">' +
        //        conversionRate.toFixed(2) + '%</span></td>';
        
        // Actions
        row += '<td class="column-actions">';
        row += '<a href="' + escapeHtml(post.post_url) + '" target="_blank" class="button button-small view-post-btn" title="View Post">';
        row += '<span class="dashicons dashicons-external" style="vertical-align: middle;"></span>';
        row += '</a>';
        row += ' <a href="' + escapeHtml(pinnerpress_ajax.admin_url) + 'admin.php?page=pinnerpress-image-analytics&post_id=' + post.post_id + '" class="button button-small view-images-btn" title="View Image Analytics">';
        row += '<span class="dashicons dashicons-format-image" style="vertical-align: middle;"></span>';
        row += '</a>';
        row += '</td>';
        
        row += '</tr>';
        
        return row;
    }
    
    // Get conversion rate class for styling
    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
    }
    
    // Sort posts
    function sortPosts(posts, sortField, sortOrder) {
        var sorted = posts.slice(); // Make a copy
        
        sorted.sort(function(a, b) {
            var aVal, bVal;
            
            switch(sortField) {
                case 'title':
                    aVal = a.post_title || '';
                    bVal = b.post_title || '';
                    return sortOrder === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);

                // DISABLED: Impressions sorting removed
                // case 'impressions':
                //     aVal = parseInt(a.total_impressions) || 0;
                //     bVal = parseInt(b.total_impressions) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'pin-clicks':
                    aVal = parseInt(a.total_pin_clicks) || 0;
                    bVal = parseInt(b.total_pin_clicks) || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Pin CTR sorting removed (requires impressions)
                // case 'pin-ctr':
                //     aVal = parseFloat(a.pin_conversion_rate) || 0;
                //     bVal = parseFloat(b.pin_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'banner-clicks':
                    aVal = parseInt(a.total_banner_clicks) || 0;
                    bVal = parseInt(b.total_banner_clicks) || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Banner CTR sorting removed (requires impressions)
                // case 'banner-ctr':
                //     aVal = parseFloat(a.banner_conversion_rate) || 0;
                //     bVal = parseFloat(b.banner_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'follow-clicks':
                    aVal = parseInt(a.total_follow_clicks) || 0;
                    bVal = parseInt(b.total_follow_clicks) || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Follow CTR sorting removed (requires impressions)
                // case 'follow-ctr':
                //     aVal = parseFloat(a.follow_conversion_rate) || 0;
                //     bVal = parseFloat(b.follow_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'callout-clicks':
                    aVal = parseInt(a.total_call_out_banner_clicks) || 0;
                    bVal = parseInt(b.total_call_out_banner_clicks) || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Callout CTR sorting removed (requires impressions)
                // case 'callout-ctr':
                //     aVal = parseFloat(a.call_out_banner_conversion_rate) || 0;
                //     bVal = parseFloat(b.call_out_banner_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                case 'block-clicks':
                    aVal = parseInt(a.total_block_editor_button_clicks) || 0;
                    bVal = parseInt(b.total_block_editor_button_clicks) || 0;
                    return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Block CTR sorting removed (requires impressions)
                // case 'block-ctr':
                //     aVal = parseFloat(a.block_editor_button_conversion_rate) || 0;
                //     bVal = parseFloat(b.block_editor_button_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                // DISABLED: Conversion sorting removed (requires impressions)
                // case 'conversion':
                //     aVal = parseFloat(a.overall_conversion_rate) || 0;
                //     bVal = parseFloat(b.overall_conversion_rate) || 0;
                //     return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;

                default:
                    return 0;
            }
        });
        
        return sorted;
    }
    
    // Handle table header clicks for sorting
    $(document).on('click', '#post-analytics-table 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;
            currentSortOrder = 'desc'; // Default to desc for new column
        }
        
        // Reset to first page when sorting changes
        currentPage = 1;
        
        // Update visual indicators
        $('#post-analytics-table th').removeClass('asc desc');
        $th.addClass(currentSortOrder);
        
        // Re-render sorted data
        displaySortedPosts();
    });
    
    // Handle table row clicks to show modal
    $(document).on('click', '#post-analytics-table tbody tr', function(e) {
        // Don't trigger if clicking on a button or link
        if ($(e.target).closest('a, button').length > 0) {
            return;
        }
        
        var postId = $(this).data('post-id');
        var post = currentPosts.find(function(p) {
            return p.post_id == postId;
        });
        
        if (post) {
            showPostDetails(post);
        }
    });
    
    // Show post details in modal
    function showPostDetails(post) {
        pinnerpressAdminDebugLog('Showing details for post:', post);
        
        // Get detailed analytics for this post
        var startDate = $('#pinnerpress-start-date').val();
        var endDate = $('#pinnerpress-end-date').val();
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pinnerpress_get_single_post_analytics',
                post_id: post.post_id,
                start_date: startDate,
                end_date: endDate,
                nonce: pinnerpress_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    displayPostModal(response.data);
                } else {
                    pinnerpressAdminDebugError('Failed to load post details:', response);
                }
            },
            error: function(xhr, status, error) {
                pinnerpressAdminDebugError('Error loading post details:', error);
            }
        });
    }
    
    // Display post modal with detailed analytics
    function displayPostModal(data) {
        var modal = $('.pinnerpress-post-detail-modal');
        var body = modal.find('.modal-body');
        
        // Clear previous content
        body.empty();
        
        // Build modal content
        var content = '<div style="display: flex; gap: 30px; align-items: flex-start;">';
        
        // Left side - Post info and image
        content += '<div style="flex: 0 0 400px; max-width: 50%;">';
        
        // Post image
        if (data.post.featured_image && data.post.featured_image.url) {
            content += '<img src="' + escapeHtml(data.post.featured_image.url) + '" style="width: 100%; height: auto; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 20px;">';
        }
        
        // Post title and link
        content += '<h2 style="margin: 0 0 10px 0;">' + escapeHtml(data.post.title) + '</h2>';
        content += '<a href="' + escapeHtml(data.post.url) + '" target="_blank" class="button button-secondary">';
        content += '<span class="dashicons dashicons-external" style="vertical-align: middle; margin-right: 3px;"></span>';
        content += 'View Post</a>';
        content += '</div>';
        
        // Right side - Analytics data
        content += '<div style="flex: 1; min-width: 400px;">';
        
        // Summary stats - Click breakdown
        content += '<h3 style="margin-top: 0;">Click Summary</h3>';
        content += '<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 30px;">';

        // DISABLED: Impressions tracking removed
        // content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        // content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Total Impressions</div>';
        // content += '<div style="font-size: 24px; font-weight: 600; color: #333;">' + formatNumber(data.totals.impressions) + '</div>';
        // content += '</div>';

        // Total Clicks
        content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Total Clicks</div>';
        content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(data.totals.total_clicks) + '</div>';
        content += '</div>';

        // Pin Clicks
        content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Pin Clicks</div>';
        content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(data.totals.pin_clicks) + '</div>';
        content += '</div>';

        // Banner Clicks
        content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Banner Clicks</div>';
        content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(data.totals.banner_clicks) + '</div>';
        content += '</div>';

        // Follow Clicks
        content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Follow Clicks</div>';
        content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(data.totals.follow_clicks) + '</div>';
        content += '</div>';

        // Callout Banner Clicks
        content += '<div style="background: #f5f5f5; padding: 15px; border-radius: 4px;">';
        content += '<div style="font-size: 12px; color: #666; margin-bottom: 5px;">Callout Banner Clicks</div>';
        content += '<div style="font-size: 24px; font-weight: 600; color: #E60023;">' + formatNumber(data.totals.call_out_banner_clicks) + '</div>';
        content += '</div>';

        content += '</div>'; // End summary grid

        // DISABLED: Conversion rates require impressions
        /*
        content += '<h3>Conversion Rates</h3>';
        content += '<div style="background: #fff; border: 1px solid #ddd; padding: 20px; border-radius: 4px; margin-bottom: 30px;">';
        content += '<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">';
        // Pin Conversion
        content += '<div>';
        content += '<div style="display: flex; justify-content: space-between; align-items: center;">';
        content += '<span style="font-weight: 500;">Pin Button</span>';
        content += '<span style="font-weight: 600; color: ' + getConversionColor(data.conversion_rates.pin) + ';">' + data.conversion_rates.pin + '%</span>';
        content += '</div>';
        content += '<div style="font-size: 12px; color: #666; margin-top: 5px;">' + formatNumber(data.totals.pin_clicks) + ' clicks</div>';
        content += '</div>';
        // Banner Conversion
        content += '<div>';
        content += '<div style="display: flex; justify-content: space-between; align-items: center;">';
        content += '<span style="font-weight: 500;">Image Banner</span>';
        content += '<span style="font-weight: 600; color: ' + getConversionColor(data.conversion_rates.banner) + ';">' + data.conversion_rates.banner + '%</span>';
        content += '</div>';
        content += '<div style="font-size: 12px; color: #666; margin-top: 5px;">' + formatNumber(data.totals.banner_clicks) + ' clicks</div>';
        content += '</div>';
        // Follow Conversion
        content += '<div>';
        content += '<div style="display: flex; justify-content: space-between; align-items: center;">';
        content += '<span style="font-weight: 500;">Follow Button</span>';
        content += '<span style="font-weight: 600; color: ' + getConversionColor(data.conversion_rates.follow) + ';">' + data.conversion_rates.follow + '%</span>';
        content += '</div>';
        content += '<div style="font-size: 12px; color: #666; margin-top: 5px;">' + formatNumber(data.totals.follow_clicks) + ' clicks</div>';
        content += '</div>';
        // Callout Banner Conversion
        content += '<div>';
        content += '<div style="display: flex; justify-content: space-between; align-items: center;">';
        content += '<span style="font-weight: 500;">Callout Banner</span>';
        content += '<span style="font-weight: 600; color: ' + getConversionColor(data.conversion_rates.call_out_banner) + ';">' + data.conversion_rates.call_out_banner + '%</span>';
        content += '</div>';
        content += '<div style="font-size: 12px; color: #666; margin-top: 5px;">' + formatNumber(data.totals.call_out_banner_clicks) + ' clicks</div>';
        content += '</div>';
        // Overall Conversion
        content += '<div>';
        content += '<div style="display: flex; justify-content: space-between; align-items: center;">';
        content += '<span style="font-weight: 500;">Overall</span>';
        content += '<span style="font-weight: 600; color: ' + getConversionColor(data.conversion_rates.overall) + ';">' + data.conversion_rates.overall + '%</span>';
        content += '</div>';
        content += '<div style="font-size: 12px; color: #666; margin-top: 5px;">' + formatNumber(data.totals.total_clicks) + ' total clicks</div>';
        content += '</div>';
        content += '</div>'; // End conversion grid
        content += '</div>'; // End conversion container
        */
        
        // Daily chart if we have data
        if (data.daily_data && data.daily_data.length > 0) {
            content += '<h3>Daily Performance</h3>';
            content += '<div style="background: #fff; border: 1px solid #ddd; padding: 20px; border-radius: 4px;">';
            content += '<canvas id="post-daily-chart" width="400" height="200"></canvas>';
            content += '</div>';
        }
        
        content += '</div>'; // End right side
        content += '</div>'; // End flex container
        
        // Set modal content
        body.html(content);
        
        // Show modal
        modal.fadeIn();
        
        // Create chart if we have daily data
        if (data.daily_data && data.daily_data.length > 0) {
            createDailyChart(data.daily_data);
        }
    }
    
    // Create daily performance chart
    function createDailyChart(dailyData) {
        var ctx = document.getElementById('post-daily-chart').getContext('2d');

        var labels = dailyData.map(function(day) {
            return formatChartDate(day.date);
        });

        // DISABLED: Impressions tracking removed
        // var impressionsData = dailyData.map(function(day) {
        //     return parseInt(day.impressions) || 0;
        // });

        var clicksData = dailyData.map(function(day) {
            return parseInt(day.total_clicks) || 0;
        });

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                // DISABLED: Impressions tracking removed
                // {
                //     label: 'Impressions',
                //     data: impressionsData,
                //     borderColor: '#4BC0C0',
                //     backgroundColor: 'rgba(75, 192, 192, 0.1)',
                //     tension: 0.4,
                //     yAxisID: 'y'
                // },
                {
                    label: 'Total Clicks',
                    data: clicksData,
                    borderColor: '#E60023',
                    backgroundColor: 'rgba(230, 0, 35, 0.1)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Clicks'
                        }
                    }
                }
            }
        });
    }
    
    // Get color for conversion rate
    function getConversionColor(rate) {
        if (rate >= 5) return '#4CAF50';
        if (rate >= 2) return '#FF9800';
        return '#E60023';
    }
    
    // Handle modal close
    $('.close, .pinnerpress-post-detail-modal').on('click', function(e) {
        if (e.target === this) {
            $('.pinnerpress-post-detail-modal').fadeOut();
        }
    });
    
    // Handle CSV export
    $('#export-csv').on('click', function() {
        // Check for premium access
        if (!pinnerpress_ajax.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 (currentPosts.length === 0) {
            alert('No data to export');
            return;
        }
        
        // Prepare CSV data - MODIFIED: Removed impressions and conversion rates
        var csv = 'Post Title,Post URL,Pin Clicks,Banner Clicks,Follow Clicks,Call Out Banner Clicks,Total Clicks\n';

        currentPosts.forEach(function(post) {
            csv += '"' + post.post_title + '",';
            csv += '"' + post.post_url + '",';
            csv += post.total_pin_clicks + ',';
            csv += post.total_banner_clicks + ',';
            csv += post.total_follow_clicks + ',';
            csv += (post.total_call_out_banner_clicks || 0) + ',';
            csv += post.total_clicks + '\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-post-analytics-' + $('#pinnerpress-start-date').val() + '-to-' + 
                      $('#pinnerpress-end-date').val() + '.csv';
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    });
    
    // Utility functions
    function showLoading() {
        $('.pinnerpress-loading').show();
        $('.post-table-container').hide();
        $('.no-data-message').hide();
        $('.summary-stats').hide();
    }
    
    function hideLoading() {
        $('.pinnerpress-loading').hide();
    }
    
    function showError(message) {
        $('.no-data-message').html('<p class="notice notice-error">' + message + '</p>').show();
        $('.post-table-container').hide();
        $('.summary-stats').hide();
    }
    
    function formatDate(date) {
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    }
    
    function formatChartDate(dateString) {
        var date = new Date(dateString);
        return (date.getMonth() + 1) + '/' + date.getDate();
    }
    
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // Update pagination controls
    function updatePaginationControls(totalPosts, totalPages, startIndex, endIndex) {
        var $pagination = $('.pinnerpress-pagination');
        
        // Update displaying text
        var displayingText = totalPosts === 0 ? 
            'No posts found' : 
            'Showing ' + startIndex + ' to ' + endIndex + ' of ' + totalPosts + ' posts';
        $('.displaying-num').text(displayingText);
        
        // Update page input
        $('.current-page').val(currentPage).attr('max', totalPages);
        $('.total-pages').text(totalPages);
        
        // Disable page input for free users
        if (isDataLimited) {
            $('.current-page').prop('disabled', true);
        }
        
        // Enable/disable navigation buttons
        $('.first-page, .prev-page').prop('disabled', currentPage <= 1 || isDataLimited);
        $('.next-page, .last-page').prop('disabled', currentPage >= totalPages || isDataLimited);
        
        // Show/hide pagination based on posts
        if (totalPosts === 0 || postsPerPage === 'all' || isDataLimited) {
            $pagination.hide();
        } else {
            $pagination.show();
        }
    }
    
}); 