<?php

/**
 * Provide a admin area view for the plugin analytics
 *
 * This file is used to markup the admin-facing analytics of the plugin.
 *
 * @link       https://pinnerpress.com
 * @since      0.1.0
 *
 * @package    PinnerPress
 * @subpackage PinnerPress/admin/partials
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Check if user has premium access
$is_premium = function_exists('pinnerpress_is_premium') ? pinnerpress_is_premium() : false;

// Add method to get event colors (this would normally be in the admin class)
if (!function_exists('pinnerpress_get_event_color')) {
    function pinnerpress_get_event_color($event_type) {
        $colors = array(
            'pin_button_click' => '#FF6384', // Pink
            'follow_button_click' => '#FFCE56', // Yellow
            'image_banner_click' => '#4BC0C0', // Teal
            'call_out_banner_click' => '#9966FF', // Purple
            'block_editor_button_click' => '#FF9F40'  // Orange
        );
        
        return isset($colors[$event_type]) ? $colors[$event_type] : '#CCCCCC'; // Default to a light gray
    }
}

// Check if analytics is enabled
$analytics_enabled = get_option('pinnerpress_analytics_enabled', '1') === '1';

if (!$analytics_enabled) {
    ?>
    <div class="wrap pinnerpress-admin">
        <h1><?php echo esc_html__('PinnerPress Analytics', 'pinnerpress'); ?></h1>

        <div class="pinnerpress-admin-header">
            <div class="pinnerpress-logo">
                <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedImage -- Plugin logo asset ?>
                <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'images/pinnerpress-logo.png'); ?>" alt="<?php echo esc_attr__('PinnerPress Logo', 'pinnerpress'); ?>">
            </div>
            <div class="pinnerpress-header-content">
                <h2><?php esc_html_e('PinnerPress Analytics', 'pinnerpress'); ?></h2>
                <p><?php esc_html_e('Track and analyze your Pinterest engagement metrics.', 'pinnerpress'); ?></p>
            </div>
        </div>

        <div class="pinnerpress-analytics-disabled-notice" style="background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 60px 40px; text-align: center; margin: 20px auto 0; max-width: 800px;">
            <span class="dashicons dashicons-chart-bar" style="font-size: 48px; width: 48px; height: 48px; color: #c3c4c7; margin-bottom: 20px;"></span>
            <h2 style="font-size: 24px; margin: 0 0 15px 0; color: #1d2327;"><?php esc_html_e('Analytics Disabled', 'pinnerpress'); ?></h2>
            <p style="font-size: 14px; color: #646970; margin: 0 0 25px 0; max-width: 500px; margin-left: auto; margin-right: auto;">
                <?php esc_html_e('Analytics tracking is currently turned off. Enable analytics to start collecting data about your Pinterest engagement.', 'pinnerpress'); ?>
            </p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=pinnerpress-settings&tab=general#analytics-settings')); ?>" class="button button-primary button-hero">
                <?php esc_html_e('Enable Analytics in Settings', 'pinnerpress'); ?>
            </a>
        </div>
    </div>
    <?php
    return;
}

// Check if user has premium analytics access (extended date ranges)
$has_premium_analytics = pinnerpress_is_feature_enabled('analytics_30_days');

// Check if user has basic analytics access (free users get 7-day analytics)
$has_basic_analytics = pinnerpress_is_feature_enabled('analytics_7_days');

// Get analytics instance with error handling
$analytics = null;
$event_types = array();

try {
    require_once plugin_dir_path(dirname(dirname(__FILE__))) . 'includes/class-pinnerpress-analytics.php';
    
    if (class_exists('PinnerPress_Analytics')) {
        $analytics = new PinnerPress_Analytics();
        
        // Check if analytics table exists, create it if it doesn't
        global $wpdb;
        $table_name = $wpdb->prefix . 'pinnerpress_analytics';
        
        // Try to get from cache first
        $cache_key = 'pinnerpress_analytics_table_exists';
        $table_exists = wp_cache_get($cache_key, 'pinnerpress');
        
        if ($table_exists === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe existence check wrapped with caching
            $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
            wp_cache_set($cache_key, $table_exists, 'pinnerpress', 300); // Cache for 5 minutes
        }
        
        if (!$table_exists) {
            $analytics->create_table();
            // Clear cache after creating table
            wp_cache_delete($cache_key, 'pinnerpress');
        }
        
        $event_types = $analytics->get_event_types();
    }
} catch (Exception $e) {
    // Log the error but don't break the page
    $analytics_enabled = false;
}

// Set default date range based on plan
$default_start_date = $has_premium_analytics ? gmdate('Y-m-d', strtotime('-30 days')) : gmdate('Y-m-d', strtotime('-7 days'));
$default_end_date = gmdate('Y-m-d');
?>

<div class="wrap pinnerpress-admin">
    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
    
    <div class="pinnerpress-admin-header">
        <div class="pinnerpress-logo">
            <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedImage -- Plugin logo asset ?>
            <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'images/pinnerpress-logo.png'); ?>" alt="<?php echo esc_attr__('PinnerPress Logo', 'pinnerpress'); ?>">
        </div>
        <div class="pinnerpress-header-content">
            <h2><?php esc_html_e('PinnerPress Analytics', 'pinnerpress'); ?></h2>
            <p><?php esc_html_e('Track and analyze your Pinterest engagement metrics.', 'pinnerpress'); ?></p>
        </div>
    </div>

    <?php if (!$is_premium): ?>
        <div class="pinnerpress-analytics-limitation notice notice-info">
            <h4><?php esc_html_e('🚀 Unlock PinnerPress Premium', 'pinnerpress'); ?></h4>
            <p><?php esc_html_e('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', 'pinnerpress'); ?></p>
            <a href="<?php echo esc_url(pinnerpress_get_upgrade_url()); ?>" class="button button-primary" target="_blank"><?php esc_html_e('Upgrade to Premium', 'pinnerpress'); ?></a>
        </div>
    <?php endif; ?>
    
    <?php if (empty($event_types)): ?>
        <div class="notice notice-error">
            <p>
                <?php esc_html_e('Analytics system is not properly initialized.', 'pinnerpress'); ?>
                <a href="<?php echo esc_url(wp_nonce_url(add_query_arg('pinnerpress_init_analytics', '1'), 'pinnerpress_init_analytics')); ?>" class="button button-secondary">
                    <?php esc_html_e('Initialize Analytics', 'pinnerpress'); ?>
                </a>
            </p>
        </div>
    <?php endif; ?>
    
    <?php
    // Handle manual analytics initialization
    if (isset($_GET['pinnerpress_init_analytics']) && isset($_GET['_wpnonce']) && current_user_can('manage_options') && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'pinnerpress_init_analytics')) {
        try {
            if ($analytics) {
                $analytics->create_table();
                echo '<div class="notice notice-success"><p>' . esc_html__('Analytics system initialized successfully. Please refresh the page.', 'pinnerpress') . '</p></div>';
            }
        } catch (Exception $e) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Failed to initialize analytics system: ', 'pinnerpress') . esc_html($e->getMessage()) . '</p></div>';
        }
    }
    ?>
    
    <div class="pinnerpress-analytics-container">
        <div class="pinnerpress-analytics-controls">
            <div class="pinnerpress-date-controls">
                <?php if ($has_premium_analytics): ?>
                    <label for="pinnerpress-start-date"><?php esc_html_e('Start Date:', 'pinnerpress'); ?></label>
                    <input type="date" id="pinnerpress-start-date" value="<?php echo esc_attr($default_start_date); ?>" />
                    
                    <label for="pinnerpress-end-date"><?php esc_html_e('End Date:', 'pinnerpress'); ?></label>
                    <input type="date" id="pinnerpress-end-date" value="<?php echo esc_attr($default_end_date); ?>" />
                    
                    <button type="button" id="pinnerpress-update-chart" class="button button-primary">
                        <?php esc_html_e('Update Chart', 'pinnerpress'); ?>
                    </button>
                    
                    <div class="pinnerpress-date-presets">
                        <button type="button" class="button pinnerpress-date-preset <?php echo !$has_premium_analytics ? 'active' : ''; ?>" data-days="7">
                            <?php esc_html_e('Last 7 Days', 'pinnerpress'); ?>
                        </button>
                        <button type="button" class="button pinnerpress-date-preset <?php echo $has_premium_analytics ? 'active' : ''; ?>" data-days="30">
                            <?php esc_html_e('Last 30 Days', 'pinnerpress'); ?>
                        </button>
                        <button type="button" class="button pinnerpress-date-preset" data-days="90">
                            <?php esc_html_e('Last 90 Days', 'pinnerpress'); ?>
                        </button>
                    </div>
                <?php else: ?>
                    <!-- Free users see disabled date inputs with locked message -->
                    <div class="pinnerpress-free-date-controls">
                        <label for="pinnerpress-start-date-disabled"><?php esc_html_e('Date Range:', 'pinnerpress'); ?></label>
                        <input type="date" id="pinnerpress-start-date-disabled" value="<?php echo esc_attr($default_start_date); ?>" disabled />
                        <span style="margin: 0 5px;"><?php esc_html_e('to', 'pinnerpress'); ?></span>
                        <input type="date" id="pinnerpress-end-date-disabled" value="<?php echo esc_attr($default_end_date); ?>" disabled />
                        <span class="pinnerpress-locked-icon" title="<?php esc_attr_e('Premium feature - upgrade to unlock custom date ranges', 'pinnerpress'); ?>">🔒</span>
                        
                        <!-- Hidden inputs for JavaScript to use -->
                        <input type="hidden" id="pinnerpress-start-date" value="<?php echo esc_attr($default_start_date); ?>" />
                        <input type="hidden" id="pinnerpress-end-date" value="<?php echo esc_attr($default_end_date); ?>" />
                    </div>
                    
                    <div class="pinnerpress-date-presets">
                        <button type="button" class="button pinnerpress-date-preset active" data-days="7">
                            <?php esc_html_e('Last 7 Days', 'pinnerpress'); ?>
                        </button>
                        <button type="button" class="button pinnerpress-date-preset pinnerpress-premium-disabled" data-days="30" disabled title="<?php esc_attr_e('Premium feature - upgrade to unlock', 'pinnerpress'); ?>">
                            <?php esc_html_e('Last 30 Days', 'pinnerpress'); ?>
                        </button>
                        <button type="button" class="button pinnerpress-date-preset pinnerpress-premium-disabled" data-days="90" disabled title="<?php esc_attr_e('Premium feature - upgrade to unlock', 'pinnerpress'); ?>">
                            <?php esc_html_e('Last 90 Days', 'pinnerpress'); ?>
                        </button>
                    </div>
                <?php endif; ?>
            </div>
            


        </div>
        
        <div class="pinnerpress-analytics-chart-container">
            <canvas id="pinnerpress-analytics-chart" width="800" height="400"></canvas>
            <div id="pinnerpress-chart-loading" class="pinnerpress-loading" style="display: none;">
                <span class="spinner is-active"></span>
                <?php esc_html_e('Loading analytics data...', 'pinnerpress'); ?>
            </div>
        </div>
        
        <div class="pinnerpress-analytics-summary">
            <h3><?php esc_html_e('Summary', 'pinnerpress'); ?></h3>
            <div id="pinnerpress-analytics-totals" class="pinnerpress-totals-grid">
                <!-- Totals will be populated by JavaScript -->
            </div>
        </div>
        
        <div class="pinnerpress-analytics-top-posts pinnerpress-card" style="margin-top: 20px;">
            <div class="pinnerpress-top-posts-controls" style="margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <label for="pinnerpress-top-posts-event-type"><?php esc_html_e('Show top posts for event type:', 'pinnerpress'); ?></label>
                    <select id="pinnerpress-top-posts-event-type">
                        <?php if (!empty($event_types)): ?>
                            <?php foreach ($event_types as $event_type_val => $label): ?>
                                <option value="<?php echo esc_attr($event_type_val); ?>" <?php selected($event_type_val, 'pin_button_click'); // Default to pin_button_click ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                
                <!-- View Toggle -->
                <div class="pinnerpress-view-toggle">
                    <button type="button" class="pinnerpress-view-toggle-btn" data-view="table" aria-pressed="true">
                        <span class="dashicons dashicons-list-view"></span>
                        <?php esc_html_e('Table', 'pinnerpress'); ?>
                    </button>
                    <button type="button" class="pinnerpress-view-toggle-btn" data-view="grid" aria-pressed="false">
                        <span class="dashicons dashicons-grid-view"></span>
                        <?php esc_html_e('Grid', 'pinnerpress'); ?>
                    </button>
                </div>
            </div>
            <div id="pinnerpress-analytics-top-posts-list" class="pinnerpress-top-posts-list">
                <p class="pinnerpress-loading-text"><?php esc_html_e('Loading top posts data...', 'pinnerpress'); ?></p>
                <!-- Top posts grid will be populated by JavaScript -->
            </div>
        </div>
    </div>
    
</div>

<style>
.pinnerpress-analytics-container {
    margin-top: 20px;
}

.pinnerpress-analytics-controls {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.pinnerpress-date-controls {
    /* margin-bottom: 20px; */
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.pinnerpress-date-controls label {
    font-weight: 600;
    white-space: nowrap;
}

.pinnerpress-date-controls input[type="date"] {
    margin-right: 5px;
}

.pinnerpress-free-date-controls {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.pinnerpress-free-date-controls input[type="date"]:disabled {
    background-color: #f1f1f1;
    color: #666;
    cursor: not-allowed;
}

.pinnerpress-locked-icon {
    font-size: 16px;
    cursor: help;
    color: #d63638;
}

.pinnerpress-date-presets {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
    margin-left: auto;
}

.pinnerpress-date-preset {
    /* Removed margin-left since flexbox gap handles spacing */
    height: auto;
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 6px 12px;
    line-height: 1.4;
    background-color: #fff !important;
    color: #E60023 !important;
    border: 1px solid #E60023 !important;
    transition: all 0.3s ease;
    text-decoration: none !important;
    box-shadow: none !important;
}

.pinnerpress-date-preset:hover:not(.pinnerpress-premium-disabled) {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

.pinnerpress-date-preset.active {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

/* Additional specificity for WordPress button overrides */
.pinnerpress-analytics-controls .pinnerpress-date-preset.button {
    background-color: #fff !important;
    color: #E60023 !important;
    border: 1px solid #E60023 !important;
}

.pinnerpress-analytics-controls .pinnerpress-date-preset.button:hover:not(.pinnerpress-premium-disabled) {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

.pinnerpress-analytics-controls .pinnerpress-date-preset.button.active {
    background-color: #E60023 !important;
    color: white !important;
    border-color: #E60023 !important;
}

.pinnerpress-date-preset.pinnerpress-premium-disabled {
    background-color: #f1f1f1;
    color: #666;
    cursor: not-allowed;
    border-color: #ddd;
    opacity: 0.6;
}

.pinnerpress-analytics-limitation {
    border-left: 4px solid #E60023;
    padding: 12px;
    background-color: #fef4f4;
    margin: 20px 0;
}

.pinnerpress-analytics-limitation h4 {
    margin-top: 0;
    color: #E60023;
}

.pinnerpress-analytics-limitation p {
    margin-bottom: 10px;
}

.pinnerpress-analytics-chart-container {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    position: relative;
}

.pinnerpress-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}

.pinnerpress-analytics-summary {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
}

.pinnerpress-totals-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.pinnerpress-total-item {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    text-align: center;
}

.pinnerpress-total-number {
    font-size: 24px;
    font-weight: 600;
    color: #E60023;
    display: block;
}

.pinnerpress-total-label {
    font-size: 14px;
    color: #646970;
    margin-top: 5px;
}

/* Highlighted Total Clicks card */
.pinnerpress-total-clicks-highlight {
    background: linear-gradient(135deg, #E60023 0%, #bd0d1e 100%);
    border: none;
    color: #fff;
}

.pinnerpress-total-clicks-highlight .pinnerpress-total-number {
    color: #fff;
    font-size: 28px;
}

.pinnerpress-total-clicks-highlight .pinnerpress-total-label {
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
}

.pinnerpress-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

/* Top Posts Grid Styles */
.pinnerpress-top-posts-header {
    margin-bottom: 20px;
}

.pinnerpress-top-posts-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #d63638;
}

.pinnerpress-trophy-icon {
    font-size: 20px;
}

.pinnerpress-top-posts-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.pinnerpress-top-post-card {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
    position: relative;
}

.pinnerpress-top-post-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-color: #E60023;
}

.pinnerpress-post-link {
    display: block;
    text-decoration: none;
    color: inherit;
}

.pinnerpress-post-link:hover {
    text-decoration: none;
    color: inherit;
}

.pinnerpress-post-image-container {
    position: relative;
    height: 200px;
    background: #f5f5f5;
    overflow: hidden;
}

/* Ensure high-quality image rendering on retina displays */
@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
    .pinnerpress-post-image {
        -ms-interpolation-mode: bicubic;
        image-rendering: -webkit-optimize-contrast;
        image-rendering: optimize-contrast;
    }
}

.pinnerpress-post-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
    image-rendering: auto;
    image-rendering: -webkit-optimize-contrast;
    image-rendering: crisp-edges;
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
}

.pinnerpress-top-post-card:hover .pinnerpress-post-image {
    transform: scale(1.05);
}

.pinnerpress-post-image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
    color: #999;
}

.pinnerpress-placeholder-icon {
    font-size: 48px;
    opacity: 0.6;
}

.pinnerpress-post-stats {
    padding: 20px;
    text-align: center;
}

.pinnerpress-post-clicks {
    font-size: 24px;
    font-weight: 700;
    color: #d63638;
    margin-bottom: 8px;
    line-height: 1;
}

.pinnerpress-post-title {
    font-size: 14px;
    font-weight: 500;
    color: #646970;
    line-height: 1.4;
    margin: 0;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.pinnerpress-pro-tip {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 16px;
    margin-top: 20px;
    font-size: 14px;
    line-height: 1.5;
    color: #495057;
}

.pinnerpress-tip-icon {
    margin-right: 8px;
    font-size: 16px;
}

.pinnerpress-pro-tip strong {
    color: #E60023;
}

/* PinnerPress Button Styling */
#pinnerpress-update-chart {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
    transition: all 0.3s ease;
}

#pinnerpress-update-chart:hover {
    background-color: #c7001e !important;
    border-color: #c7001e !important;
}

.pinnerpress-analytics-limitation .button-primary {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
    transition: all 0.3s ease;
}

.pinnerpress-analytics-limitation .button-primary:hover {
    background-color: #c7001e !important;
    border-color: #c7001e !important;
}

/* Initialize Analytics Button */
.notice .button-secondary {
    color: #E60023;
    border-color: #E60023;
    background-color: #fff;
    transition: all 0.3s ease;
}

.notice .button-secondary:hover {
    background-color: #E60023;
    color: white;
}

/* View Toggle Styles */
.pinnerpress-view-toggle {
    display: inline-flex;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    overflow: hidden;
}

.pinnerpress-view-toggle-btn {
    background: #fff;
    border: none;
    padding: 6px 12px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    color: #646970;
    transition: all 0.2s;
}

.pinnerpress-view-toggle-btn:not(:last-child) {
    border-right: 1px solid #ccd0d4;
}

.pinnerpress-view-toggle-btn[aria-pressed="true"] {
    background: #E60023;
    color: #fff;
}

.pinnerpress-view-toggle-btn[aria-pressed="true"] .dashicons {
    color: #fff;
}

.pinnerpress-view-toggle-btn:hover:not([aria-pressed="true"]) {
    background: #f0f0f1;
}

/* Table View Styles */
.pinnerpress-top-posts-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

.pinnerpress-top-posts-table th {
    background: #f6f7f7;
    padding: 12px;
    text-align: left;
    font-weight: 600;
    border-bottom: 1px solid #ccd0d4;
}

.pinnerpress-top-posts-table td {
    padding: 12px;
    border-bottom: 1px solid #e2e4e7;
}

.pinnerpress-top-posts-table tbody tr {
    cursor: pointer;
    transition: background 0.2s;
}

.pinnerpress-top-posts-table tbody tr:hover {
    background: #f6f7f7;
}

.pinnerpress-post-thumbnail {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
}

.pinnerpress-post-thumbnail-placeholder {
    width: 60px;
    height: 60px;
    background: #f0f0f1;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
}

.pinnerpress-post-rank {
    font-weight: 600;
    color: #E60023;
}

.pinnerpress-post-clicks-cell {
    font-weight: 600;
    color: #E60023;
}

/* Responsive adjustments */
@media (max-width: 1200px) {
    .pinnerpress-top-posts-grid {
        grid-template-columns: repeat(4, 1fr);
    }
}

@media (max-width: 1024px) {
    .pinnerpress-top-posts-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 768px) {
    .pinnerpress-top-posts-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
    }
    
    .pinnerpress-post-image-container {
        height: 160px;
    }
    
    .pinnerpress-post-stats {
        padding: 15px;
    }
    
    .pinnerpress-post-clicks {
        font-size: 20px;
    }
}

@media (max-width: 480px) {
    .pinnerpress-top-posts-grid {
        grid-template-columns: 1fr;
    }
}

/* Legacy list styles for fallback */
.pinnerpress-top-posts-list ol.pinnerpress-ordered-list {
    list-style-type: decimal;
    margin-left: 20px;
    padding-left: 5px;
}

.pinnerpress-top-posts-list ol.pinnerpress-ordered-list li {
    margin-bottom: 8px;
    font-size: 14px;
}

.pinnerpress-top-posts-list .pinnerpress-count {
    color: #646970;
    font-size: 0.9em;
}

/* View Analytics Button Styling */
.pinnerpress-view-analytics-btn {
    background-color: #E60023 !important;
    border-color: #E60023 !important;
    color: white !important;
    transition: all 0.3s ease;
    text-decoration: none !important;
    box-shadow: none !important;
}

.pinnerpress-view-analytics-btn:hover,
.pinnerpress-view-analytics-btn:focus {
    background-color: #C5001E !important;
    border-color: #C5001E !important;
    color: white !important;
    box-shadow: 0 2px 4px rgba(230, 0, 35, 0.3) !important;
}

.pinnerpress-view-analytics-btn:active {
    background-color: #A50019 !important;
    border-color: #A50019 !important;
    transform: translateY(1px);
}
</style>

<script>
jQuery(document).ready(function($) {
    // Gate console logging behind URL param pinnerpress_debug=1
    function pinnerpressAdminDebugLog(){var p=new URLSearchParams(window.location.search).get('pinnerpress_debug');if(p==='1'){console.log.apply(console,arguments);}}
    function pinnerpressAdminDebugError(){var p=new URLSearchParams(window.location.search).get('pinnerpress_debug');if(p==='1'){console.error.apply(console,arguments);}}
    pinnerpressAdminDebugLog('PinnerPress Analytics: Page loaded');
    
    let chart = null;
    
    // Analytics feature checks
    const hasPremiumAnalytics = <?php echo wp_json_encode($has_premium_analytics); ?>;
    const hasBasicAnalytics = <?php echo wp_json_encode($has_basic_analytics); ?>;
    
    // Event colors mapping
    const eventColors = {
        'pin_button_click': '#FF6384', // Pink
        'follow_button_click': '#FFCE56', // Yellow
        'image_banner_click': '#4BC0C0', // Teal
        'call_out_banner_click': '#9966FF', // Purple
        'block_editor_button_click': '#FF9F40'  // Orange
    };
    
    // Initialize chart
    function initChart() {
        const ctx = document.getElementById('pinnerpress-analytics-chart').getContext('2d');
        chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        display: true,
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    title: {
                        display: true,
                        text: '<?php echo esc_js(__('PinnerPress Analytics', 'pinnerpress')); ?>' + 
                              (hasPremiumAnalytics ? '' : ' - <?php echo esc_js(__('Last 7 Days (Free Version)', 'pinnerpress')); ?>'),
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    }
    
    // Enforce date range limits for free users
    function enforceDateRangeLimits(startDate, endDate) {
        if (hasPremiumAnalytics) {
            return { startDate: startDate, endDate: endDate };
        }
        
        // For free users, enforce 7-day limit
        const today = new Date();
        const maxStartDate = new Date(today.getTime() - (7 * 24 * 60 * 60 * 1000));
        
        const start = new Date(startDate);
        const end = new Date(endDate);
        
        // If start date is more than 7 days ago, adjust it
        if (start < maxStartDate) {
            startDate = maxStartDate.toISOString().split('T')[0];
        }
        
        // If end date is in the future, set to today
        // Allow today's date by comparing only the date part, not time
        const todayDateOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate());
        const endDateOnly = new Date(end.getFullYear(), end.getMonth(), end.getDate());
        
        if (endDateOnly > todayDateOnly) {
            endDate = today.toISOString().split('T')[0];
        }
        
        return { startDate: startDate, endDate: endDate };
    }
    
    // Load analytics data
    function loadAnalyticsData() {
        let startDate = $('#pinnerpress-start-date').val();
        let endDate = $('#pinnerpress-end-date').val();
        
        // Enforce date range limits
        const enforcedDates = enforceDateRangeLimits(startDate, endDate);
        startDate = enforcedDates.startDate;
        endDate = enforcedDates.endDate;
        
        // Update hidden inputs for free users
        if (!hasPremiumAnalytics) {
            $('#pinnerpress-start-date').val(startDate);
            $('#pinnerpress-end-date').val(endDate);
        }
        
        const selectedEvents = [];
        
        // Show all event types since there are no checkboxes
        const eventTypes = <?php echo wp_json_encode($event_types); ?>;
        for (const eventType in eventTypes) {
            selectedEvents.push(eventType);
        }
        
        $('#pinnerpress-chart-loading').show();
        
        $.post(ajaxurl, {
            action: 'pinnerpress_get_analytics_data',
            nonce: '<?php echo esc_js(wp_create_nonce('pinnerpress_analytics_nonce')); ?>',
            start_date: startDate,
            end_date: endDate,
            event_types: selectedEvents
        }, function(response) {
            $('#pinnerpress-chart-loading').hide();
            
            if (response.success) {
                updateChart(response.data);
                updateTotals(response.data.totals);
            } else {
                pinnerpressAdminDebugError('Failed to load analytics data:', response.data);
            }
        });
    }
    
    // Update chart with new data
    function updateChart(data) {
        if (!chart) return;
        
        // Process data for Chart.js
        const dates = [];
        const datasets = {};
        
        // Get all unique dates
        data.daily_data.forEach(item => {
            if (!dates.includes(item.date)) {
                dates.push(item.date);
            }
        });
        
        // Sort dates
        dates.sort();
        
        // Initialize datasets for all event types
        const eventTypes = <?php echo wp_json_encode($event_types); ?>;
        
        for (const eventType in eventTypes) {
            const label = eventTypes[eventType];
            const color = eventColors[eventType] || '#CCCCCC';
            
            pinnerpressAdminDebugLog('Event Type:', eventType, 'Label:', label, 'Color:', color);
            
            datasets[eventType] = {
                label: label,
                data: new Array(dates.length).fill(0),
                borderColor: color,
                backgroundColor: color + '20',
                tension: 0.1
            };
        }
        
        // Fill in the data
        data.daily_data.forEach(item => {
            const dateIndex = dates.indexOf(item.date);
            if (dateIndex !== -1 && datasets[item.event_type]) {
                datasets[item.event_type].data[dateIndex] = parseInt(item.count);
            }
        });
        
        // Update chart
        chart.data.labels = dates;
        chart.data.datasets = Object.values(datasets);
        chart.update();
    }
    
    // Update totals display
    function updateTotals(totals) {
        let html = '';

        // Calculate total clicks (sum of all click event types)
        const clickEventTypes = ['pin_button_click', 'image_banner_click', 'follow_button_click', 'call_out_banner_click', 'block_editor_button_click'];
        let totalClicks = 0;
        totals.forEach(item => {
            if (clickEventTypes.includes(item.event_type)) {
                totalClicks += parseInt(item.total, 10) || 0;
            }
        });

        // Add Total Clicks card first (highlighted)
        html += '<div class="pinnerpress-total-item pinnerpress-total-clicks-highlight">';
        html += '<span class="pinnerpress-total-number">' + totalClicks.toLocaleString() + '</span>';
        html += '<div class="pinnerpress-total-label"><?php echo esc_js(__('Total Clicks', 'pinnerpress')); ?></div>';
        html += '</div>';

        // Add individual event type totals
        totals.forEach(item => {
            const eventTypes = <?php echo wp_json_encode($event_types); ?>;
            const label = eventTypes[item.event_type] || item.event_type;

            html += '<div class="pinnerpress-total-item">';
            html += '<span class="pinnerpress-total-number">' + parseInt(item.total, 10).toLocaleString() + '</span>';
            html += '<div class="pinnerpress-total-label">' + label + '</div>';
            html += '</div>';
        });

        $('#pinnerpress-analytics-totals').html(html);
    }
    
    function loadTopPostsData() {
        let startDate = $('#pinnerpress-start-date').val();
        let endDate = $('#pinnerpress-end-date').val();
        
        // Enforce date range limits
        const enforcedDates = enforceDateRangeLimits(startDate, endDate);
        startDate = enforcedDates.startDate;
        endDate = enforcedDates.endDate;
        
        const eventType = $('#pinnerpress-top-posts-event-type').val();

        $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').show();

        $.post(ajaxurl, {
            action: 'pinnerpress_get_top_posts',
            nonce: '<?php echo esc_js(wp_create_nonce("pinnerpress_analytics_nonce")); ?>',
            start_date: startDate,
            end_date: endDate,
            event_type: eventType,
            limit: 10
        }, function(response) {
            $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').hide();
            if (response.success && response.data) {
                updateTopPostsList(response.data);
            } else {
                $('#pinnerpress-analytics-top-posts-list').html('<p><?php esc_html_e("Could not load top posts data.", 'pinnerpress'); ?></p>');
                console.error('Failed to load top posts data:', response.data);
            }
        }).fail(function() {
            $('#pinnerpress-analytics-top-posts-list .pinnerpress-loading-text').hide();
            $('#pinnerpress-analytics-top-posts-list').html('<p><?php esc_html_e("Error loading top posts data.", 'pinnerpress'); ?></p>');
        });
    }

    function updateTopPostsList(posts) {
        // Store posts data for re-rendering on view change
        $('#pinnerpress-analytics-top-posts-list').data('posts', posts);
        
        if (posts.length === 0) {
            $('#pinnerpress-analytics-top-posts-list').html('<p><?php esc_html_e("No data for the selected event type and date range.", 'pinnerpress'); ?></p>');
            return;
        }

        // Get the current event type for the header
        const currentEventType = $('#pinnerpress-top-posts-event-type option:selected').text();
        
        let html = `
            <div class="pinnerpress-top-posts-header">
                <h3 class="pinnerpress-top-posts-title">
                    <span class="pinnerpress-trophy-icon">🏆</span>
                    <?php esc_html_e('Top Performing Posts by', 'pinnerpress'); ?> ${currentEventType}
                </h3>
            </div>
        `;
        
        if (currentView === 'table') {
            // Table view
            html += '<table class="pinnerpress-top-posts-table wp-list-table widefat fixed striped">';
            html += '<thead><tr>';
            html += '<th style="width: 50px;"><?php esc_html_e('Rank', 'pinnerpress'); ?></th>';
            html += '<th style="width: 80px;"><?php esc_html_e('Preview', 'pinnerpress'); ?></th>';
            html += '<th><?php esc_html_e('Post Title', 'pinnerpress'); ?></th>';
            html += '<th style="width: 120px;"><?php esc_html_e('Clicks', 'pinnerpress'); ?></th>';
            html += '<th style="width: 100px;"><?php esc_html_e('Actions', 'pinnerpress'); ?></th>';
            html += '</tr></thead><tbody>';
            
            posts.forEach((post, index) => {
                const postTitle = post.post_title || '<?php esc_html_e("Untitled Post", 'pinnerpress'); ?>';
                const count = post.event_count || 0;
                const imageUrl = post.featured_image && post.featured_image.has_image ? post.featured_image.url : '';
                const imageAnalyticsUrl = '<?php echo esc_js(admin_url('admin.php?page=pinnerpress-image-analytics')); ?>&post_id=' + post.post_id;
                
                html += `<tr data-post-id="${post.post_id}" style="cursor: pointer;">`;
                html += `<td class="pinnerpress-post-rank">#${index + 1}</td>`;
                html += `<td>`;
                if (imageUrl) {
                    html += `<img src="${imageUrl}" alt="${postTitle}" class="pinnerpress-post-thumbnail" />`;
                } else {
                    html += `<div class="pinnerpress-post-thumbnail-placeholder">📝</div>`;
                }
                html += `</td>`;
                html += `<td><strong>${postTitle}</strong></td>`;
                html += `<td class="pinnerpress-post-clicks-cell">${count}</td>`;
                html += `<td><a href="${imageAnalyticsUrl}" class="button button-small pinnerpress-view-analytics-btn"><?php esc_html_e('View Analytics', 'pinnerpress'); ?></a></td>`;
                html += `</tr>`;
            });
            
            html += '</tbody></table>';
        } else {
            // Grid view
            html += '<div class="pinnerpress-top-posts-grid">';
            
            posts.forEach((post, index) => {
                const postTitle = post.post_title || '<?php esc_html_e("Untitled Post", 'pinnerpress'); ?>';
                const count = post.event_count || 0;
                const imageUrl = post.featured_image && post.featured_image.has_image ? post.featured_image.url : '';
                
                // Link to image analytics page with post ID parameter
                const imageAnalyticsUrl = '<?php echo esc_js(admin_url('admin.php?page=pinnerpress-image-analytics')); ?>&post_id=' + post.post_id;
                
                // Create a placeholder if no image
                const imageHtml = imageUrl ? 
                    `<img src="${imageUrl}" alt="${postTitle}" class="pinnerpress-post-image" />` :
                    `<div class="pinnerpress-post-image-placeholder">
                        <div class="pinnerpress-placeholder-icon">📝</div>
                    </div>`;
                
                html += `
                    <div class="pinnerpress-top-post-card" data-rank="${index + 1}">
                        <a href="${imageAnalyticsUrl}" class="pinnerpress-post-link">
                            <div class="pinnerpress-post-image-container">
                                ${imageHtml}
                            </div>
                            <div class="pinnerpress-post-stats">
                                <div class="pinnerpress-post-clicks">${count} clicks</div>
                                <div class="pinnerpress-post-title">${postTitle}</div>
                            </div>
                        </a>
                    </div>
                `;
            });
            
            html += '</div>';
        }
        
        // Add pro tip
        html += `
            <div class="pinnerpress-pro-tip">
                <span class="pinnerpress-tip-icon">💡</span>
                <strong><?php esc_html_e('Pro Tip:', 'pinnerpress'); ?></strong>
                <?php esc_html_e('Use this data to place your best performing images at the top of your posts, and consider replacing your lowest performing images.', 'pinnerpress'); ?>
            </div>
        `;
        
        $('#pinnerpress-analytics-top-posts-list').html(html);
        
        // Add click handlers for table rows
        if (currentView === 'table') {
            $('.pinnerpress-top-posts-table tbody tr').on('click', function(e) {
                // Don't navigate if clicking the button
                if ($(e.target).closest('.button').length) return;
                
                const postId = $(this).data('post-id');
                const imageAnalyticsUrl = '<?php echo esc_js(admin_url('admin.php?page=pinnerpress-image-analytics')); ?>&post_id=' + postId;
                window.location.href = imageAnalyticsUrl;
            });
        }
    }
    
    // Date preset button handlers
    $('.pinnerpress-date-preset').on('click', function() {
        const days = parseInt($(this).data('days'));
        
        // Check if this is a premium feature and user doesn't have premium
        if (!hasPremiumAnalytics && (days === 30 || days === 90)) {
            // Show upgrade message for disabled buttons
            alert('<?php echo esc_js(__('This feature requires PinnerPress Premium. Upgrade to unlock extended analytics periods.', 'pinnerpress')); ?>');
            return;
        }
        
        // Remove active class from all buttons
        $('.pinnerpress-date-preset').removeClass('active');
        // Add active class to clicked button
        $(this).addClass('active');
        
        const endDate = new Date();
        const startDate = new Date(endDate.getTime() - (days * 24 * 60 * 60 * 1000));
        
        const startDateStr = startDate.toISOString().split('T')[0];
        const endDateStr = endDate.toISOString().split('T')[0];
        
        $('#pinnerpress-start-date').val(startDateStr);
        $('#pinnerpress-end-date').val(endDateStr);
        
        // For free users, also update disabled inputs
        if (!hasPremiumAnalytics) {
            $('#pinnerpress-start-date-disabled').val(startDateStr);
            $('#pinnerpress-end-date-disabled').val(endDateStr);
        }
        
        loadAnalyticsData();
        loadTopPostsData();
    });
    
    // Update chart button (only for premium users)
    $('#pinnerpress-update-chart').on('click', function() {
        loadAnalyticsData();
        loadTopPostsData();
    });
    
    // Top posts event type change handler
    $('#pinnerpress-top-posts-event-type').on('change', function() {
        loadTopPostsData();
    });
    
    // Initialize
    if (typeof Chart !== 'undefined') {
        initChart();
        
        // Load initial data and set active button based on premium status
        if (!hasPremiumAnalytics) {
            // Free users: ensure 7-day button is active
            $('.pinnerpress-date-preset').removeClass('active');
            $('.pinnerpress-date-preset[data-days="7"]').addClass('active');
        } else {
            // Premium users: ensure 30-day button is active
            $('.pinnerpress-date-preset').removeClass('active');
            $('.pinnerpress-date-preset[data-days="30"]').addClass('active');
        }
        
        // Load analytics data for users with basic or premium analytics access
        if (hasBasicAnalytics || hasPremiumAnalytics) {
            loadAnalyticsData();
            loadTopPostsData();
        }
    } else {
        pinnerpressAdminDebugError('Chart.js is not loaded');
    }

    // Add after chart initialization:
    let currentView = 'table'; // Default to table view
    
    // Handle view toggle
    $('.pinnerpress-view-toggle-btn').on('click', function() {
        const view = $(this).data('view');
        if (view === currentView) return;
        
        // Update button states
        $('.pinnerpress-view-toggle-btn').attr('aria-pressed', 'false');
        $(this).attr('aria-pressed', 'true');
        
        // Update current view
        currentView = view;
        
        // Re-render the top posts if data exists
        const currentData = $('#pinnerpress-analytics-top-posts-list').data('posts');
        if (currentData) {
            updateTopPostsList(currentData);
        }
    });
});
</script>