<?php
// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

// Check if user has required capabilities
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'text-to-speech-tts'));
}

// Check if API key is set
$has_api_key = !empty(get_option('mementor_tts_api_key'));

// Make sure plugin functions are available
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// Check if user has a paid plan via SaaS
$is_pro_active = ttswp_has_paid_plan();

// Check if statistics are enabled
$statistics_enabled = get_option('mementor_tts_enable_statistics', 'no') === 'yes';

// Get player statistics instance
if ($statistics_enabled) {
    $player_stats = Mementor_TTS_Player_Statistics::get_instance();

    // Get overall statistics for the last 30 days
    $date_from = date('Y-m-d', strtotime('-30 days'));
    $date_to = date('Y-m-d');
    $overall_stats = $player_stats->get_overall_statistics($date_from, $date_to);

    // Get detailed statistics
    $page = isset($_GET['paged']) && is_numeric($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $per_page = 10;
    $offset = ((int)$page - 1) * (int)$per_page;

    $detailed_stats = $player_stats->get_detailed_statistics($per_page, $offset, $date_from, $date_to);
    $total_posts = $player_stats->get_detailed_statistics_count($date_from, $date_to);
    $total_pages = ceil($total_posts / $per_page);

    // Daily chart data
    $daily_chart_raw = $player_stats->get_daily_chart_data($date_from, $date_to);

    // Build full 30-day array with zero-fill
    $chart_labels = array();
    $chart_initiated = array();
    $chart_plays = array();
    $chart_completions = array();
    for ($i = 30; $i >= 0; $i--) {
        $d = date('Y-m-d', strtotime("-{$i} days"));
        $chart_labels[] = date('M j', strtotime($d));
        $row = isset($daily_chart_raw[$d]) ? $daily_chart_raw[$d] : null;
        $chart_initiated[] = $row ? intval($row->player_initiated) : 0;
        $chart_plays[] = $row ? intval($row->play_clicks) : 0;
        $chart_completions[] = $row ? intval($row->completion_count) : 0;
    }

    // Previous period (30 days before current 30 days) for delta comparison
    $prev_from = date('Y-m-d', strtotime('-60 days'));
    $prev_to = date('Y-m-d', strtotime('-31 days'));
    $prev_stats = $player_stats->get_overall_statistics($prev_from, $prev_to);
}

?>

<?php
$tts_page_title = __('Audio Statistics', 'text-to-speech-tts');
$tts_topbar_actions = '';
if ($statistics_enabled) {
    $tts_topbar_actions = '<span class="tts-topbar-hint">' . esc_html__('Updated every 24 hours', 'text-to-speech-tts') . '</span>'
        . '<button type="button" class="tts-btn" id="mementor-tts-manual-stats-update">' . esc_html__('Refresh Now', 'text-to-speech-tts') . '</button>'
        . '<button type="button" class="tts-btn tts-btn-danger" id="mementor-tts-reset-stats">' . esc_html__('Reset', 'text-to-speech-tts') . '</button>';
}
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'); ?>

            <!-- Analytics Overview -->
            <div class="tts-card">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Analytics Overview', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Monitor your audio player performance and user engagement metrics', 'text-to-speech-tts'); ?></p>
                </div>

                <?php if (!$statistics_enabled): ?>
                <div class="tts-stats-empty-state">
                    <span class="dashicons dashicons-warning"></span>
                    <p><?php esc_html_e('Statistics tracking is currently disabled. Enable it in the', 'text-to-speech-tts'); ?> <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=text-to-speech-tts-settings'), 'mementor_tts_nav_page')); ?>"><?php esc_html_e('Settings', 'text-to-speech-tts'); ?></a> <?php esc_html_e('to start collecting player usage data.', 'text-to-speech-tts'); ?></p>
                </div>
                <?php elseif (empty($overall_stats) || !$overall_stats->total_play_clicks): ?>
                <div class="tts-stats-empty-state tts-stats-empty-state-compact">
                    <span class="dashicons dashicons-info"></span>
                    <p><?php esc_html_e('No statistics data available yet. Data will appear here once visitors start using the audio players.', 'text-to-speech-tts'); ?></p>
                </div>
                <?php endif; ?>

                <?php
                // Set default values
                $player_initiated = $statistics_enabled && $overall_stats && isset($overall_stats->total_player_initiated) ? intval($overall_stats->total_player_initiated) : 0;
                $play_clicks = $statistics_enabled && $overall_stats && isset($overall_stats->total_play_clicks) ? intval($overall_stats->total_play_clicks) : 0;
                $pause_clicks = $statistics_enabled && $overall_stats && isset($overall_stats->total_pause_clicks) ? intval($overall_stats->total_pause_clicks) : 0;
                $completion_count = $statistics_enabled && $overall_stats && isset($overall_stats->total_completion_count) ? intval($overall_stats->total_completion_count) : 0;
                $downloads = $statistics_enabled && $overall_stats && isset($overall_stats->total_downloads) ? intval($overall_stats->total_downloads) : 0;
                $total_play_time = $statistics_enabled && $overall_stats && isset($overall_stats->total_play_time) ? floatval($overall_stats->total_play_time) : 0;
                $play_rate = $statistics_enabled && $overall_stats && isset($overall_stats->play_rate) ? floatval($overall_stats->play_rate) : 0;
                $completion_rate = $statistics_enabled && $overall_stats && isset($overall_stats->completion_rate) ? floatval($overall_stats->completion_rate) : 0;
                $average_listening_time = $statistics_enabled && $overall_stats && isset($overall_stats->average_listening_time) ? floatval($overall_stats->average_listening_time) : 0;

                // Format play time
                $hours = intval(floor($total_play_time / 3600));
                $remaining_seconds = intval($total_play_time) % 3600;
                $minutes = intval(floor($remaining_seconds / 60));
                $seconds = intval($remaining_seconds % 60);
                $formatted_play_time = sprintf('%d:%02d:%02d', $hours, $minutes, $seconds);

                // Format average listening time
                $avg_minutes = intval(floor($average_listening_time / 60));
                $avg_seconds = intval($average_listening_time) % 60;
                $formatted_avg_time = sprintf('%d:%02d', $avg_minutes, $avg_seconds);

                // Delta calculations vs previous 30 days
                $prev_play_clicks = $prev_stats && isset($prev_stats->total_play_clicks) ? intval($prev_stats->total_play_clicks) : 0;
                $prev_player_initiated = $prev_stats && isset($prev_stats->total_player_initiated) ? intval($prev_stats->total_player_initiated) : 0;
                $prev_play_rate = $prev_stats && isset($prev_stats->play_rate) ? floatval($prev_stats->play_rate) : 0;
                $prev_completion_rate = $prev_stats && isset($prev_stats->completion_rate) ? floatval($prev_stats->completion_rate) : 0;
                $prev_avg_listen = $prev_stats && isset($prev_stats->average_listening_time) ? floatval($prev_stats->average_listening_time) : 0;
                $prev_completion_count = $prev_stats && isset($prev_stats->total_completion_count) ? intval($prev_stats->total_completion_count) : 0;
                $prev_downloads = $prev_stats && isset($prev_stats->total_downloads) ? intval($prev_stats->total_downloads) : 0;
                $prev_pause_clicks = $prev_stats && isset($prev_stats->total_pause_clicks) ? intval($prev_stats->total_pause_clicks) : 0;
                $prev_play_time = $prev_stats && isset($prev_stats->total_play_time) ? floatval($prev_stats->total_play_time) : 0;

                // Helper to compute delta
                function tts_delta($current, $previous, $is_pct = false) {
                    if ($is_pct) {
                        $d = round($current - $previous, 1);
                        return array('val' => $d, 'text' => ($d > 0 ? '+' : '') . $d . 'pp');
                    }
                    if ($previous > 0) {
                        $d = round((($current - $previous) / $previous) * 100);
                    } else {
                        $d = $current > 0 ? 100 : 0;
                    }
                    return array('val' => $d, 'text' => ($d > 0 ? '+' : '') . $d . '%');
                }
                function tts_delta_class($val) {
                    return $val > 0 ? 'tts-delta-up' : ($val < 0 ? 'tts-delta-down' : 'tts-delta-flat');
                }
                ?>

                <!-- All 8 metrics in one unified grid -->
                <div class="tts-chart-summary tts-chart-summary-8">
                    <?php
                    $all_metrics = array(
                        array('icon' => 'controls-play', 'label' => __('Play Clicks', 'text-to-speech-tts'), 'value' => number_format($play_clicks), 'delta' => tts_delta($play_clicks, $prev_play_clicks)),
                        array('icon' => 'chart-line', 'label' => __('Play Rate', 'text-to-speech-tts'), 'value' => number_format($play_rate, 1) . '%', 'delta' => tts_delta($play_rate, $prev_play_rate, true)),
                        array('icon' => 'chart-pie', 'label' => __('Completion Rate', 'text-to-speech-tts'), 'value' => number_format($completion_rate, 1) . '%', 'delta' => tts_delta($completion_rate, $prev_completion_rate, true)),
                        array('icon' => 'clock', 'label' => __('Avg. Listen Time', 'text-to-speech-tts'), 'value' => $formatted_avg_time, 'delta' => tts_delta($average_listening_time, $prev_avg_listen)),
                        array('icon' => 'visibility', 'label' => __('Player Initiated', 'text-to-speech-tts'), 'value' => number_format($player_initiated), 'delta' => tts_delta($player_initiated, $prev_player_initiated)),
                        array('icon' => 'controls-pause', 'label' => __('Pause Clicks', 'text-to-speech-tts'), 'value' => number_format($pause_clicks), 'delta' => tts_delta($pause_clicks, $prev_pause_clicks)),
                        array('icon' => 'backup', 'label' => __('Total Play Time', 'text-to-speech-tts'), 'value' => $formatted_play_time, 'delta' => tts_delta($total_play_time, $prev_play_time)),
                        array('icon' => 'groups', 'label' => __('Sessions', 'text-to-speech-tts'), 'value' => number_format($statistics_enabled && $overall_stats && isset($overall_stats->total_unique_sessions) ? intval($overall_stats->total_unique_sessions) : 0), 'delta' => array('val' => 0, 'text' => 'no_prev')),
                    );
                    foreach ($all_metrics as $km) :
                        $dc = tts_delta_class($km['delta']['val']);
                        if ($km['delta']['text'] === 'no_prev') {
                            $dt = __('No prev. data', 'text-to-speech-tts');
                            $dc = 'tts-delta-flat';
                        } else {
                            $dt = $km['delta']['val'] != 0 ? $km['delta']['text'] : '—';
                        }
                    ?>
                    <div class="tts-chart-mini-card">
                        <div class="tts-chart-mini-icon"><span class="dashicons dashicons-<?php echo esc_attr($km['icon']); ?>"></span></div>
                        <div class="tts-chart-mini-label"><?php echo esc_html($km['label']); ?></div>
                        <div class="tts-chart-mini-value"><?php echo esc_html($km['value']); ?></div>
                        <div class="tts-chart-mini-delta <?php echo esc_attr($dc); ?>"><?php echo esc_html($dt); ?> <span class="tts-delta-hint"><?php esc_html_e('vs prev 30d', 'text-to-speech-tts'); ?></span></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Listening Trend — chart only -->
            <?php if ($statistics_enabled) : ?>
            <div class="tts-card" style="margin-top: 20px;">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Listening Trend — Last 30 Days', 'text-to-speech-tts'); ?></h3>
                    <div class="tts-chart-legend">
                        <span class="tts-chart-legend-item"><span class="tts-chart-legend-swatch" style="background: #B5D4F4;"></span><?php esc_html_e('Initiated', 'text-to-speech-tts'); ?></span>
                        <span class="tts-chart-legend-item"><span class="tts-chart-legend-swatch" style="background: #6B45D4;"></span><?php esc_html_e('Play clicks', 'text-to-speech-tts'); ?></span>
                        <span class="tts-chart-legend-item"><span class="tts-chart-legend-swatch" style="background: #1D9E75;"></span><?php esc_html_e('Completions', 'text-to-speech-tts'); ?></span>
                    </div>
                </div>

                <div class="tts-chart-controls">
                    <div class="tts-chart-toggles">
                        <button type="button" class="tts-chart-toggle active" data-show="all"><?php esc_html_e('All metrics', 'text-to-speech-tts'); ?></button>
                        <button type="button" class="tts-chart-toggle" data-show="plays"><?php esc_html_e('Play clicks', 'text-to-speech-tts'); ?></button>
                        <button type="button" class="tts-chart-toggle" data-show="completions"><?php esc_html_e('Completions', 'text-to-speech-tts'); ?></button>
                        <button type="button" class="tts-chart-toggle" data-show="initiated"><?php esc_html_e('Player initiated', 'text-to-speech-tts'); ?></button>
                    </div>
                </div>

                <div style="position: relative; height: 260px; padding: 0 4px;">
                    <canvas id="tts-trend-chart"></canvas>
                </div>
            </div>
            <?php endif; ?>

            <!-- Detailed Analytics -->
            <div class="tts-card" style="margin-top: 20px;">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Detailed Analytics', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Performance metrics per post', 'text-to-speech-tts'); ?></p>
                    <?php if (!$is_pro_active): ?>
                    <span class="tts-pill tts-pill-pro"><span class="dashicons dashicons-star-filled"></span> <?php esc_html_e('PRO Feature', 'text-to-speech-tts'); ?></span>
                    <?php endif; ?>
                </div>

                <?php if (!$is_pro_active): ?>
                <div class="tts-stats-empty-state">
                    <span class="dashicons dashicons-star-filled" style="color: #f0b849;"></span>
                    <h4><?php esc_html_e('Detailed Analytics is a PRO Feature', 'text-to-speech-tts'); ?></h4>
                    <p><?php esc_html_e('Upgrade to PRO to access detailed statistics for individual posts and pages, including play rates, listening time, and user engagement metrics for each piece of content.', 'text-to-speech-tts'); ?></p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-upgrade')); ?>" class="tts-btn tts-btn-primary">
                        <?php esc_html_e('Upgrade to PRO', 'text-to-speech-tts'); ?>
                    </a>
                </div>
                <?php elseif (!$statistics_enabled): ?>
                <div class="tts-stats-empty-state tts-stats-empty-state-compact">
                    <span class="dashicons dashicons-warning"></span>
                    <p><?php esc_html_e('Statistics tracking is currently disabled. Enable it in the', 'text-to-speech-tts'); ?> <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=text-to-speech-tts-settings'), 'mementor_tts_nav_page')); ?>"><?php esc_html_e('Settings', 'text-to-speech-tts'); ?></a> <?php esc_html_e('to start collecting player usage data.', 'text-to-speech-tts'); ?></p>
                </div>
                <?php elseif (empty($detailed_stats)): ?>
                <div class="tts-stats-empty-state tts-stats-empty-state-compact">
                    <span class="dashicons dashicons-info"></span>
                    <p><?php esc_html_e('No detailed statistics data available yet. Data will appear here once visitors start using the audio players.', 'text-to-speech-tts'); ?></p>
                </div>
                <?php endif; ?>

                <?php if ($is_pro_active && $statistics_enabled && !empty($detailed_stats)):
                    // Pre-compute upload dir and language code once
                    $upload_dir = wp_upload_dir();
                    $audio_dir = $upload_dir['basedir'] . '/text-to-speech-tts/';
                    $language_code = get_option('mementor_tts_language', 'en');

                    // Find max plays for mini bar
                    $max_plays = 1;
                    foreach ($detailed_stats as $s) {
                        if ($s->total_play_clicks > $max_plays) $max_plays = $s->total_play_clicks;
                    }
                ?>
                <div class="tts-detailed-table-wrap">
                    <table class="tts-da-table">
                        <thead>
                            <tr>
                                <th style="width: 30%;"><?php esc_html_e('Page', 'text-to-speech-tts'); ?></th>
                                <th style="width: 6%;"><?php esc_html_e('Audio', 'text-to-speech-tts'); ?></th>
                                <th style="width: 10%;"><?php esc_html_e('Views', 'text-to-speech-tts'); ?></th>
                                <th style="width: 18%;"><?php esc_html_e('Plays', 'text-to-speech-tts'); ?></th>
                                <th style="width: 10%;"><?php esc_html_e('Play %', 'text-to-speech-tts'); ?></th>
                                <th style="width: 13%;"><?php esc_html_e('Total Time', 'text-to-speech-tts'); ?></th>
                                <th style="width: 13%;"><?php esc_html_e('Avg. Time', 'text-to-speech-tts'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($detailed_stats as $stat):
                                $play_pct = $stat->total_player_initiated > 0
                                    ? round(($stat->total_play_clicks / $stat->total_player_initiated) * 100, 1) : 0;
                                $plays_bar_pct = round(($stat->total_play_clicks / $max_plays) * 100);

                                // Resolve audio URL
                                $audio_file = null;
                                $audio_url = null;
                                $meta_url = get_post_meta($stat->post_id, '_mementor_tts_audio_url_' . $language_code, true);
                                if (empty($meta_url)) {
                                    $meta_url = get_post_meta($stat->post_id, '_mementor_tts_audio_url', true);
                                }
                                if (!empty($meta_url)) {
                                    // CDN/external URLs are always available; only check local files
                                    if (preg_match('#^https?://#i', $meta_url) && strpos($meta_url, $upload_dir['baseurl']) === false) {
                                        $audio_url = $meta_url;
                                    } else {
                                        $meta_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $meta_url);
                                        if (file_exists($meta_path)) {
                                            $audio_url = $meta_url;
                                        }
                                    }
                                }
                                if (!$audio_url) {
                                    $possible_files = array(
                                        'mementor-' . $stat->post_id . '-' . $language_code . '.mp3',
                                        'mementor-' . $stat->post_id . '-en.mp3',
                                        'post-' . $stat->post_id . '-' . $language_code . '.mp3',
                                        'post-' . $stat->post_id . '.mp3'
                                    );
                                    foreach ($possible_files as $filename) {
                                        if (file_exists($audio_dir . $filename)) {
                                            $audio_url = $upload_dir['baseurl'] . '/text-to-speech-tts/' . $filename;
                                            break;
                                        }
                                    }
                                }
                                if (!$audio_url && $stat->has_audio) {
                                    global $wpdb;
                                    $speeches_table = $wpdb->prefix . 'mementor_tts_speeches';
                                    $audio_file = $wpdb->get_var($wpdb->prepare(
                                        "SELECT file_name FROM {$speeches_table} WHERE post_id = %d ORDER BY created_at DESC LIMIT 1",
                                        $stat->post_id
                                    ));
                                    if ($audio_file && file_exists($audio_dir . $audio_file)) {
                                        $audio_url = $upload_dir['baseurl'] . '/text-to-speech-tts/' . $audio_file;
                                    }
                                }
                            ?>
                            <tr>
                                <td>
                                    <?php if ($stat->post_title): ?>
                                        <a href="<?php echo esc_url(get_permalink($stat->post_id)); ?>" target="_blank" class="tts-da-post-link"><?php echo esc_html($stat->post_title); ?></a>
                                        <span class="tts-da-post-id">#<?php echo esc_html($stat->post_id); ?></span>
                                    <?php else: ?>
                                        <span class="tts-da-deleted"><?php echo esc_html__('Post', 'text-to-speech-tts') . ' #' . esc_html($stat->post_id); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($audio_url): ?>
                                        <button class="tts-play-stats-audio" data-audio-url="<?php echo esc_attr($audio_url); ?>" data-post-id="<?php echo esc_attr($stat->post_id); ?>" title="<?php esc_attr_e('Play/Pause', 'text-to-speech-tts'); ?>">
                                            <span class="dashicons dashicons-controls-play"></span>
                                        </button>
                                        <audio class="tts-stats-audio-element" data-post-id="<?php echo esc_attr($stat->post_id); ?>" style="display: none;"></audio>
                                    <?php else: ?>
                                        <span class="tts-audio-na"><span class="dashicons dashicons-minus"></span></span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo number_format($stat->total_player_initiated); ?></td>
                                <td>
                                    <div class="tts-da-plays-cell">
                                        <span><?php echo number_format($stat->total_play_clicks); ?></span>
                                        <div class="tts-da-minibar"><div class="tts-da-minibar-fill" style="width: <?php echo esc_attr($plays_bar_pct); ?>%;"></div></div>
                                    </div>
                                </td>
                                <td><span class="tts-da-pct-pill"><?php echo number_format($play_pct, 1); ?>%</span></td>
                                <td><?php echo esc_html($stat->total_play_time_formatted); ?></td>
                                <td><?php echo esc_html($stat->average_listening_time); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <?php if ($total_pages > 1): ?>
                    <div class="tts-stats-pagination">
                        <span class="tts-stats-pagination-count">
                            <?php
                            $start = ((int)$page - 1) * (int)$per_page + 1;
                            $end = min((int)$page * (int)$per_page, (int)$total_posts);
                            /* translators: 1: First item number shown on this page. 2: Last item number shown on this page. 3: Total item count. */
                            printf(esc_html__('Showing %1$d-%2$d of %3$d items', 'text-to-speech-tts'), $start, $end, $total_posts);
                            ?>
                        </span>
                        <div class="tts-stats-pagination-controls">
                            <?php if ((int)$page > 1): ?>
                                <a href="<?php echo esc_url(add_query_arg('paged', (int)$page - 1)); ?>">&laquo;</a>
                            <?php else: ?>
                                <a href="#" class="disabled">&laquo;</a>
                            <?php endif; ?>
                            <?php
                            $start_page = max(1, (int)$page - 2);
                            $end_page = min($total_pages, (int)$page + 2);
                            for ($i = $start_page; $i <= $end_page; $i++):
                            ?>
                                <a href="<?php echo $i == (int)$page ? '#' : esc_url(add_query_arg('paged', $i)); ?>" class="<?php echo $i == (int)$page ? 'active' : ''; ?>"><?php echo esc_html($i); ?></a>
                            <?php endfor; ?>
                            <?php if ((int)$page < $total_pages): ?>
                                <a href="<?php echo esc_url(add_query_arg('paged', (int)$page + 1)); ?>">&raquo;</a>
                            <?php else: ?>
                                <a href="#" class="disabled">&raquo;</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <style>
            /* ── Card system (shared with My Stats) ── */
            .tts-uo-grid { gap: 12px; }
            .tts-uo-grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); }
            .tts-uo-card {
                position: relative;
                padding: 18px 16px 16px;
                background: #fff;
                border: 1px solid var(--tts-border-color, #e2e4e7);
                border-top: 3px solid transparent;
                border-radius: var(--tts-radius-md, 8px);
            }
            .tts-uo-border-purple { border-top-color: var(--tts-purple, #7c3aed); }
            .tts-uo-border-blue { border-top-color: #3b82f6; }
            .tts-uo-border-green { border-top-color: #22c55e; }
            .tts-uo-card-icon { margin-bottom: 8px; }
            .tts-uo-card-icon .dashicons { font-size: 20px; width: 20px; height: 20px; }
            .tts-uo-border-purple .tts-uo-card-icon .dashicons { color: var(--tts-purple, #7c3aed); }
            .tts-uo-border-blue .tts-uo-card-icon .dashicons { color: #3b82f6; }
            .tts-uo-border-green .tts-uo-card-icon .dashicons { color: #22c55e; }
            .tts-uo-value {
                font-size: 22px;
                font-weight: 600;
                color: var(--tts-text-primary, #1d2327);
                line-height: 1.2;
                margin-top: 4px;
            }
            .tts-metric-hint {
                font-size: 11px;
                color: var(--tts-text-secondary, #757575);
                margin-top: 6px;
                line-height: 1.4;
            }
            .tts-metric-unit {
                font-size: 14px;
                font-weight: 400;
                color: var(--tts-text-secondary, #757575);
                margin-left: 2px;
            }

            .tts-pill-pro {
                background: #fef3cd;
                color: #856404;
                font-size: 12px;
                padding: 4px 10px;
                border-radius: 10px;
                display: inline-flex;
                align-items: center;
                gap: 4px;
                white-space: nowrap;
            }

            .tts-pill-pro::before { display: none; }

            .tts-pill-pro .dashicons {
                font-size: 14px;
                width: 14px;
                height: 14px;
                color: #f0b849;
            }

            .tts-stats-empty-state {
                padding: 30px 20px;
                text-align: center;
                color: var(--tts-text-secondary, #646970);
            }

            .tts-stats-empty-state .dashicons {
                font-size: 32px;
                width: 32px;
                height: 32px;
                color: var(--tts-text-secondary, #646970);
                margin-bottom: 8px;
            }

            .tts-stats-empty-state h4 {
                margin: 8px 0;
                font-size: 15px;
                color: var(--tts-text-primary, #1d2327);
            }

            .tts-stats-empty-state p {
                margin: 4px auto;
                max-width: 500px;
            }

            .tts-stats-empty-state .tts-btn { margin-top: 12px; }

            .tts-stats-empty-state-compact { padding: 20px; }

            .tts-stats-empty-state-compact .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
                vertical-align: middle;
                margin-right: 6px;
                margin-bottom: 0;
            }

            .tts-detailed-table-wrap { overflow-x: auto; }

            /* ── Detailed Analytics table ── */
            .tts-da-table { width: 100%; border-collapse: collapse; font-size: 13px; }
            .tts-da-table thead th {
                text-align: left;
                font-size: 11px;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                color: var(--tts-text-secondary, #757575);
                padding: 10px 12px;
                border-bottom: 2px solid var(--tts-border-color, #e2e4e7);
                background: none;
            }
            .tts-da-table tbody tr {
                border-bottom: 1px solid var(--tts-border-color, #e2e4e7);
                transition: background 0.15s;
            }
            .tts-da-table tbody tr:nth-child(even) { background: var(--tts-bg-secondary, #fafafa); }
            .tts-da-table tbody tr:hover { background: #f0edff; }
            .tts-da-table tbody td {
                padding: 10px 12px;
                vertical-align: middle;
                color: var(--tts-text-primary, #1d2327);
            }

            .tts-da-post-link {
                font-weight: 500;
                color: var(--tts-text-primary, #1d2327);
                text-decoration: none;
            }
            .tts-da-post-link:hover { color: var(--tts-purple, #7c3aed); }
            .tts-da-post-id {
                font-size: 12px;
                color: #555555;
                margin-left: 4px;
            }
            .tts-da-deleted { color: #a00; font-style: italic; }

            /* Plays mini bar */
            .tts-da-plays-cell { display: flex; flex-direction: column; gap: 4px; }
            .tts-da-minibar { height: 4px; background: var(--tts-bg-tertiary, #f0f0f0); border-radius: 2px; overflow: hidden; }
            .tts-da-minibar-fill { height: 100%; background: var(--tts-purple, #7c3aed); border-radius: 2px; opacity: 0.6; }

            /* Play % pill */
            .tts-da-pct-pill {
                display: inline-block;
                padding: 2px 8px;
                background: #f0edff;
                color: var(--tts-purple, #7c3aed);
                border-radius: 4px;
                font-size: 11px;
                font-weight: 600;
            }

            .tts-play-stats-audio {
                background: none;
                border: none;
                cursor: pointer;
                padding: 4px;
                color: var(--tts-purple, #7c3aed);
            }
            .tts-play-stats-audio:hover { color: var(--tts-purple-dark, #5b21b6); }
            .tts-play-stats-audio .dashicons { font-size: 20px; width: 20px; height: 20px; }
            .tts-play-stats-audio.playing .dashicons-controls-play::before { content: "\f523"; }
            .tts-audio-na { color: var(--tts-text-hint, #999); }

            .tts-stats-pagination {
                padding: 12px 20px;
                border-top: 1px solid #ddd;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .tts-stats-pagination-count { color: #666; font-size: 13px; }

            .tts-stats-pagination-controls { display: flex; gap: 4px; }

            .tts-stats-pagination-controls a {
                display: inline-block;
                padding: 4px 10px;
                background: var(--tts-bg-secondary, #f0f0f0);
                border: 1px solid #ddd;
                border-radius: 3px;
                text-decoration: none;
                color: var(--tts-purple, #7c3aed);
                font-size: 13px;
            }

            .tts-stats-pagination-controls a.active {
                background: var(--tts-purple, #7c3aed);
                color: #fff;
                border-color: var(--tts-purple, #7c3aed);
            }

            .tts-stats-pagination-controls a.disabled { color: #ccc; pointer-events: none; }

            .tts-stats-pagination-controls a:hover:not(.active):not(.disabled) { background: #e0e0e0; }

            .tts-topbar-hint { font-size: 13px; color: var(--tts-text-secondary, #666); }

            .dashicons.spin { animation: tts-spin 1s linear infinite; }

            @keyframes tts-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

            /* ── Chart summary mini-cards ── */
            .tts-chart-summary {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 12px;
                margin-bottom: 16px;
            }
            .tts-chart-summary-8 {
                margin-bottom: 0;
            }
            .tts-chart-mini-card {
                padding: 12px 14px;
                background: var(--tts-bg-secondary, #fafafa);
                border: 1px solid var(--tts-border-color, #e2e4e7);
                border-radius: var(--tts-radius-md, 8px);
            }
            .tts-chart-mini-label {
                font-size: 11px;
                color: var(--tts-text-secondary, #757575);
                text-transform: uppercase;
                letter-spacing: 0.3px;
                font-weight: 500;
            }
            .tts-chart-mini-value {
                font-size: 20px;
                font-weight: 600;
                color: var(--tts-text-primary, #1d2327);
                margin-top: 2px;
                line-height: 1.2;
            }
            .tts-chart-mini-delta {
                font-size: 11px;
                font-weight: 600;
                margin-top: 4px;
            }
            .tts-delta-up { color: #00a32a; }
            .tts-delta-down { color: #d63638; }
            .tts-delta-flat { color: var(--tts-text-hint, #999); }
            .tts-delta-hint { font-weight: 400; color: var(--tts-text-hint, #999); font-size: 12px; }
            .tts-chart-mini-icon { margin-bottom: 4px; }
            .tts-chart-mini-icon .dashicons { font-size: 18px; width: 18px; height: 18px; color: var(--tts-purple, #6B45D4); }

            /* ── Chart controls ── */
            .tts-chart-controls {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 12px;
                gap: 12px;
            }
            .tts-chart-toggles { display: flex; gap: 6px; }
            .tts-chart-toggle {
                padding: 5px 12px;
                font-size: 12px;
                font-weight: 500;
                border: 1px solid var(--tts-border-color, #e2e4e7);
                border-radius: 6px;
                background: var(--tts-bg-secondary, #fafafa);
                color: var(--tts-text-secondary, #757575);
                cursor: pointer;
                transition: all 0.15s;
            }
            .tts-chart-toggle:hover { border-color: var(--tts-purple, #6B45D4); color: var(--tts-purple, #6B45D4); }
            .tts-chart-toggle.active {
                background: var(--tts-purple, #6B45D4);
                color: #fff;
                border-color: var(--tts-purple, #6B45D4);
            }

            /* ── Custom legend ── */
            .tts-chart-legend { display: flex; gap: 14px; }
            .tts-chart-legend-item {
                display: flex;
                align-items: center;
                gap: 5px;
                font-size: 12px;
                color: var(--tts-text-secondary, #757575);
            }
            .tts-chart-legend-swatch {
                display: inline-block;
                width: 10px;
                height: 10px;
                border-radius: 2px;
                flex-shrink: 0;
            }

            @media screen and (max-width: 1200px) {
                .tts-chart-summary { grid-template-columns: repeat(2, 1fr); }
                .tts-uo-grid-4 { grid-template-columns: repeat(3, 1fr); }
            }
            @media screen and (max-width: 782px) {
                .tts-chart-summary { grid-template-columns: 1fr; }
                .tts-uo-grid-4 { grid-template-columns: repeat(2, 1fr); }
                .tts-chart-controls { flex-direction: column; align-items: flex-start; }
            }
            </style>

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<?php if ($statistics_enabled): ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
    $('#mementor-tts-manual-stats-update').on('click', function() {
        var $button = $(this);
        var originalText = $button.text();

        $button.prop('disabled', true).text('<?php echo esc_js(__('Refreshing...', 'text-to-speech-tts')); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_manual_aggregate_stats',
                nonce: '<?php echo wp_create_nonce('mementor_tts_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $button.text('<?php echo esc_js(__('Refreshed!', 'text-to-speech-tts')); ?>');
                    setTimeout(function() { window.location.reload(); }, 1000);
                } else {
                    $button.text('<?php echo esc_js(__('Error', 'text-to-speech-tts')); ?>');
                    alert(response.data || '<?php echo esc_js(__('An error occurred while refreshing statistics.', 'text-to-speech-tts')); ?>');
                    setTimeout(function() { $button.text(originalText).prop('disabled', false); }, 2000);
                }
            },
            error: function() {
                $button.text('<?php echo esc_js(__('Error', 'text-to-speech-tts')); ?>');
                alert('<?php echo esc_js(__('Failed to refresh statistics. Please try again.', 'text-to-speech-tts')); ?>');
                setTimeout(function() { $button.text(originalText).prop('disabled', false); }, 2000);
            }
        });
    });

    $('#mementor-tts-reset-stats').on('click', function() {
        var $button = $(this);

        if (!confirm('<?php echo esc_js(__('WARNING: This will permanently delete ALL statistics data including player views, play/pause/completion data, and listening time. This action cannot be undone. Continue?', 'text-to-speech-tts')); ?>')) {
            return;
        }

        var originalText = $button.text();
        $button.prop('disabled', true).text('<?php echo esc_js(__('Resetting...', 'text-to-speech-tts')); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_reset_statistics',
                nonce: '<?php echo wp_create_nonce('mementor_tts_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $button.text('<?php echo esc_js(__('Reset!', 'text-to-speech-tts')); ?>');
                    setTimeout(function() { window.location.reload(); }, 1000);
                } else {
                    $button.text('<?php echo esc_js(__('Error', 'text-to-speech-tts')); ?>');
                    alert(response.data || '<?php echo esc_js(__('An error occurred while resetting statistics.', 'text-to-speech-tts')); ?>');
                    setTimeout(function() { $button.text(originalText).prop('disabled', false); }, 2000);
                }
            },
            error: function() {
                $button.text('<?php echo esc_js(__('Error', 'text-to-speech-tts')); ?>');
                alert('<?php echo esc_js(__('Failed to reset statistics. Please try again.', 'text-to-speech-tts')); ?>');
                setTimeout(function() { $button.text(originalText).prop('disabled', false); }, 2000);
            }
        });
    });

    // Play button in detailed table
    $('.tts-play-stats-audio').on('click', function() {
        var $button = $(this);
        var audioUrl = $button.data('audio-url');

        if (!audioUrl) {
            alert('<?php echo esc_js(__('Audio file not found.', 'text-to-speech-tts')); ?>');
            return;
        }

        var $audio = $button.siblings('.tts-stats-audio-element')[0];

        if (!$audio.src) {
            $audio.src = audioUrl;
        }

        if ($audio.paused) {
            $('.tts-stats-audio-element').each(function() {
                if (this !== $audio && !this.paused) {
                    this.pause();
                    $(this).siblings('.tts-play-stats-audio').removeClass('playing');
                }
            });
            $audio.play();
            $button.addClass('playing');
        } else {
            $audio.pause();
            $button.removeClass('playing');
        }

        $audio.onended = function() { $button.removeClass('playing'); };
        $audio.onpause = function() { $button.removeClass('playing'); };
        $audio.onplay = function() { $button.addClass('playing'); };
    });
});
</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
(function(){
    var canvas = document.getElementById('tts-trend-chart');
    if (!canvas) return;

    var labels = <?php echo wp_json_encode($chart_labels); ?>;
    var dataInitiated = <?php echo wp_json_encode($chart_initiated); ?>;
    var dataPlays = <?php echo wp_json_encode($chart_plays); ?>;
    var dataCompletions = <?php echo wp_json_encode($chart_completions); ?>;

    var ctx = canvas.getContext('2d');

    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Player initiated',
                    data: dataInitiated,
                    borderColor: '#B5D4F4',
                    backgroundColor: 'rgba(181,212,244,0.15)',
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 0,
                    pointHitRadius: 10
                },
                {
                    label: 'Play clicks',
                    data: dataPlays,
                    borderColor: '#6B45D4',
                    backgroundColor: 'rgba(107,69,212,0.12)',
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 0,
                    pointHitRadius: 10
                },
                {
                    label: 'Completions',
                    data: dataCompletions,
                    borderColor: '#1D9E75',
                    backgroundColor: 'rgba(29,158,117,0.10)',
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 0,
                    pointHitRadius: 10
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: '#fff',
                    titleColor: '#1d2327',
                    bodyColor: '#757575',
                    borderColor: '#e2e4e7',
                    borderWidth: 1,
                    padding: 10,
                    cornerRadius: 6,
                    titleFont: { weight: '600', size: 13 },
                    bodyFont: { size: 12 },
                    boxPadding: 4
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: {
                        color: '#999',
                        font: { size: 11 },
                        maxRotation: 0,
                        autoSkip: true,
                        maxTicksLimit: 8
                    },
                    border: { color: '#e2e4e7' }
                },
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.04)' },
                    ticks: {
                        color: '#999',
                        font: { size: 11 },
                        precision: 0
                    },
                    border: { display: false }
                }
            }
        }
    });

    // Toggle buttons
    document.querySelectorAll('.tts-chart-toggle').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.tts-chart-toggle').forEach(function(b) { b.classList.remove('active'); });
            btn.classList.add('active');

            var show = btn.dataset.show;
            var vis = { initiated: true, plays: true, completions: true };

            if (show === 'plays') { vis.initiated = false; vis.completions = false; }
            else if (show === 'completions') { vis.initiated = false; vis.plays = false; }
            else if (show === 'initiated') { vis.plays = false; vis.completions = false; }

            chart.data.datasets[0].hidden = !vis.initiated;
            chart.data.datasets[1].hidden = !vis.plays;
            chart.data.datasets[2].hidden = !vis.completions;
            chart.update();
        });
    });
})();
</script>
<?php endif; ?>
