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

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

$is_ttswp_connected = Mementor_TTS_Connect::get_connection_status() === 'connected';

// ──────────────────────────────────────────────
// Fetch usage stats from TTSWP API
// ──────────────────────────────────────────────
$usage_stats = null;
if ($is_ttswp_connected) {
    $cache_key = 'tts_usage_stats';
    $force_refresh = isset($_GET['refresh']) && $_GET['refresh'] === '1';

    if (!$force_refresh) {
        $usage_stats = get_transient($cache_key);
    }

    if (false === $usage_stats || null === $usage_stats) {
        $token = Mementor_TTS_Connect::get_site_token();
        $api_url = Mementor_TTS_Connect::get_app_url() . '/api/v1/usage/stats';

        $response = wp_remote_get($api_url, array(
            'timeout' => 15,
            'headers' => array(
                'X-Site-Token' => $token,
                'Accept'       => 'application/json',
            ),
        ));

        if (!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
            $usage_stats = json_decode(wp_remote_retrieve_body($response), true);
            if (is_array($usage_stats)) {
                set_transient($cache_key, $usage_stats, 5 * MINUTE_IN_SECONDS);
            }
        }
    }
}

// ──────────────────────────────────────────────
// Local credit usage by post
// ──────────────────────────────────────────────
$speech_builder = Mementor_TTS_Speech_Builder::get_instance();
$per_page = 10;
$current_page = isset($_GET['usage_page']) ? max(1, absint($_GET['usage_page'])) : 1;
$offset = ($current_page - 1) * $per_page;
$all_time_totals = $speech_builder->get_credit_usage_totals();
$this_month_totals = $speech_builder->get_credit_usage_totals(date('Y-m-01'), date('Y-m-t'));

// Daily chart data (30 days)
$date_from_30d = date('Y-m-d', strtotime('-30 days'));
$date_to_30d = date('Y-m-d');
$daily_chart_raw = $speech_builder->get_daily_credit_chart_data($date_from_30d, $date_to_30d);
$chart_labels = array();
$chart_credits = array();
$chart_generations = 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_credits[] = $row ? intval($row->credits) : 0;
    $chart_generations[] = $row ? intval($row->generations) : 0;
}
$local_usage_stats = $speech_builder->get_credit_usage_stats(null, null, $per_page, $offset);
$total_posts = $speech_builder->get_credit_usage_count();
$total_pages = ceil($total_posts / $per_page);

?>

<?php
$tts_page_title = __('My Stats', 'text-to-speech-tts');
$tts_topbar_actions = '';
if ($is_ttswp_connected) {
    $refresh_url = add_query_arg('refresh', '1');
    $tts_topbar_actions = '<a href="' . esc_url($refresh_url) . '" class="tts-btn tts-btn-primary">'
        . esc_html__('Refresh Stats', 'text-to-speech-tts') . '</a>';
}
$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'); ?>

<?php if (!$is_ttswp_connected) : ?>
    <!-- Not connected -->
    <div class="tts-card">
        <div class="tts-stats-empty-state">
            <span class="dashicons dashicons-chart-bar"></span>
            <h4><?php esc_html_e('Connect to TTSWP to view stats', 'text-to-speech-tts'); ?></h4>
            <p><?php esc_html_e('Connect your site to TTSWP to track credit usage, audio generation, and plan details.', 'text-to-speech-tts'); ?></p>
            <a href="<?php echo esc_url(Mementor_TTS_Connect::get_connect_url()); ?>" class="tts-btn tts-btn-primary">
                <?php esc_html_e('Get Started', 'text-to-speech-tts'); ?>
            </a>
        </div>
    </div>
<?php elseif (!$usage_stats) : ?>
    <!-- Connected but API call failed -->
    <div class="tts-card">
        <div class="tts-stats-empty-state">
            <span class="dashicons dashicons-warning"></span>
            <p><?php esc_html_e('Could not load usage stats. Please try refreshing.', 'text-to-speech-tts'); ?></p>
            <a href="<?php echo esc_url(add_query_arg('refresh', '1')); ?>" class="tts-btn tts-btn-primary">
                <?php esc_html_e('Refresh', 'text-to-speech-tts'); ?>
            </a>
        </div>
    </div>
<?php else : ?>
    <!-- TTSWP Usage Overview -->
    <div class="tts-card">
        <div class="tts-card-header tts-card-header-inline">
            <h3 class="tts-card-title"><?php esc_html_e('Usage Overview', 'text-to-speech-tts'); ?></h3>
            <div style="display: flex; align-items: center; gap: 8px;">
                <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-account')); ?>" class="tts-btn tts-btn-primary">
                    <?php esc_html_e('Manage Plan & Credits', 'text-to-speech-tts'); ?>
                </a>
                <span class="tts-pill tts-pill-success"><?php esc_html_e('Connected', 'text-to-speech-tts'); ?></span>
            </div>
        </div>

        <?php
        $allocation = intval($usage_stats['monthly_allocation'] ?? 0);
        $credits_remaining = intval($usage_stats['credits_remaining'] ?? 0);
        $credits_used = intval($usage_stats['credits_used_30d'] ?? 0);
        $monthly_balance = intval($usage_stats['monthly_balance'] ?? 0);
        $purchased_balance = intval($usage_stats['purchased_balance'] ?? 0);
        $used_pct = $allocation > 0 ? min(round(($credits_used / $allocation) * 100), 100) : 0;
        ?>
        <div class="tts-chart-summary">
            <div class="tts-chart-mini-card">
                <div class="tts-chart-mini-icon"><span class="dashicons dashicons-awards"></span></div>
                <div class="tts-chart-mini-label"><?php esc_html_e('Current Plan', 'text-to-speech-tts'); ?></div>
                <div class="tts-chart-mini-value"><?php echo esc_html($usage_stats['plan_name'] ?? 'Free'); ?></div>
                <div class="tts-chart-mini-delta tts-delta-flat">
                    <?php echo $allocation > 0 ? esc_html(number_format($allocation) . ' ' . __('credits/mo', 'text-to-speech-tts')) : esc_html__('No allocation', 'text-to-speech-tts'); ?>
                </div>
            </div>
            <div class="tts-chart-mini-card">
                <div class="tts-chart-mini-icon"><span class="dashicons dashicons-database"></span></div>
                <div class="tts-chart-mini-label"><?php esc_html_e('Credits Remaining', 'text-to-speech-tts'); ?></div>
                <div class="tts-chart-mini-value"><?php echo esc_html(number_format($credits_remaining)); ?></div>
                <div class="tts-chart-mini-delta tts-delta-flat">
                    <?php echo esc_html(number_format($monthly_balance) . ' ' . __('monthly', 'text-to-speech-tts') . ' + ' . number_format($purchased_balance) . ' ' . __('topped up', 'text-to-speech-tts')); ?>
                </div>
            </div>
            <div class="tts-chart-mini-card">
                <div class="tts-chart-mini-icon"><span class="dashicons dashicons-chart-bar"></span></div>
                <div class="tts-chart-mini-label"><?php esc_html_e('Credits Used (30d)', 'text-to-speech-tts'); ?></div>
                <div class="tts-chart-mini-value"><?php echo esc_html(number_format($credits_used)); ?></div>
                <div class="tts-chart-mini-delta tts-delta-flat"><?php echo esc_html($used_pct . '% ' . __('of monthly allocation', 'text-to-speech-tts')); ?></div>
            </div>
            <div class="tts-chart-mini-card">
                <div class="tts-chart-mini-icon"><span class="dashicons dashicons-performance"></span></div>
                <div class="tts-chart-mini-label"><?php esc_html_e('Monthly Allocation', 'text-to-speech-tts'); ?></div>
                <div class="tts-chart-mini-value"><?php echo $allocation > 0 ? esc_html(number_format($allocation)) : '—'; ?></div>
                <div class="tts-chart-mini-delta tts-delta-flat"><?php echo $allocation > 0 ? esc_html__('Credits per billing cycle', 'text-to-speech-tts') : esc_html__('Upgrade for monthly credits', 'text-to-speech-tts'); ?></div>
            </div>
        </div>
    </div>
<?php endif; ?>

    <!-- Usage Chart (30 days) -->
    <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('Usage Overview', 'text-to-speech-tts'); ?></h3>
            <div class="tts-chart-legend">
                <span class="tts-chart-legend-dot" style="background: #6B45D4;"></span> <?php esc_html_e('Credits', 'text-to-speech-tts'); ?>
                <span class="tts-chart-legend-dot" style="background: #1D9E75; margin-left: 12px;"></span> <?php esc_html_e('Generations', 'text-to-speech-tts'); ?>
            </div>
        </div>
        <div class="tts-chart-toggles" style="display: flex; gap: 6px; margin-bottom: 12px;">
            <button type="button" class="tts-chart-toggle active" data-show="all"><?php esc_html_e('All', 'text-to-speech-tts'); ?></button>
            <button type="button" class="tts-chart-toggle" data-show="credits"><?php esc_html_e('Credits', 'text-to-speech-tts'); ?></button>
            <button type="button" class="tts-chart-toggle" data-show="generations"><?php esc_html_e('Generations', 'text-to-speech-tts'); ?></button>
        </div>
        <div style="height: 260px;">
            <canvas id="tts-usage-chart"></canvas>
        </div>
        <p style="text-align: center; font-size: 12px; color: var(--tts-text-hint); margin: 8px 0 0;"><?php esc_html_e('Last 30 days', 'text-to-speech-tts'); ?></p>
    </div>

    <!-- Credit Usage by Post -->
    <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('Credit Usage by Post', 'text-to-speech-tts'); ?></h3>
            <p class="tts-card-desc"><?php esc_html_e('Track credits used for audio generation on each post/page.', 'text-to-speech-tts'); ?></p>
        </div>

        <div class="tts-grid-3 tts-uo-grid">
            <div class="tts-uo-card tts-uo-border-blue">
                <div class="tts-uo-card-icon"><span class="dashicons dashicons-database"></span></div>
                <div class="tts-metric-label"><?php esc_html_e('Total Credits Used', 'text-to-speech-tts'); ?></div>
                <div class="tts-uo-value"><?php echo esc_html(number_format($all_time_totals['total_credits'])); ?></div>
                <div class="tts-metric-hint"><?php esc_html_e('All time', 'text-to-speech-tts'); ?></div>
            </div>
            <div class="tts-uo-card tts-uo-border-blue">
                <div class="tts-uo-card-icon"><span class="dashicons dashicons-update"></span></div>
                <div class="tts-metric-label"><?php esc_html_e('Total Generations', 'text-to-speech-tts'); ?></div>
                <div class="tts-uo-value"><?php echo esc_html(number_format($all_time_totals['total_generations'])); ?></div>
                <div class="tts-metric-hint"><?php esc_html_e('All time', 'text-to-speech-tts'); ?></div>
            </div>
            <div class="tts-uo-card tts-uo-border-blue">
                <div class="tts-uo-card-icon"><span class="dashicons dashicons-calendar"></span></div>
                <div class="tts-metric-label"><?php esc_html_e('This Month', 'text-to-speech-tts'); ?></div>
                <div class="tts-uo-value"><?php echo esc_html(number_format($this_month_totals['total_credits'])); ?></div>
                <div class="tts-metric-hint"><?php echo esc_html(wp_date('F Y')); ?></div>
            </div>
        </div>

        <?php if (empty($local_usage_stats)) : ?>
            <div class="tts-stats-empty-state tts-stats-empty-state-compact" style="margin-top: 16px;">
                <span class="dashicons dashicons-info"></span>
                <p><?php esc_html_e('No credit usage recorded yet. Generate audio for a post to see usage statistics here.', 'text-to-speech-tts'); ?></p>
            </div>
        <?php else : ?>
            <?php
            // Find max credits for mini progress bars
            $max_credits = 1;
            foreach ($local_usage_stats as $s) {
                if ($s->total_credits > $max_credits) $max_credits = $s->total_credits;
            }
            $model_names = array(
                'eleven_flash_v2_5' => 'Flash v2.5',
                'eleven_flash_v2' => 'Flash v2',
                'eleven_turbo_v2_5' => 'Turbo v2.5',
                'eleven_turbo_v2' => 'Turbo v2',
                'eleven_multilingual_v2' => 'Multilingual v2',
                'eleven_multilingual_v1' => 'Multilingual v1',
                'eleven_monolingual_v1' => 'Monolingual v1',
            );
            ?>
            <table class="tts-cup-table" style="margin-top: 16px;">
                <thead>
                    <tr>
                        <th style="width: 30%;"><?php esc_html_e('Post/Page', 'text-to-speech-tts'); ?></th>
                        <th style="width: 10%;"><?php esc_html_e('Characters', 'text-to-speech-tts'); ?></th>
                        <th style="width: 20%;"><?php esc_html_e('Total Credits', 'text-to-speech-tts'); ?></th>
                        <th style="width: 12%;"><?php esc_html_e('Last Credits', 'text-to-speech-tts'); ?></th>
                        <th style="width: 14%;"><?php esc_html_e('Last Generated', 'text-to-speech-tts'); ?></th>
                        <th style="width: 14%;"><?php esc_html_e('Generations', 'text-to-speech-tts'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($local_usage_stats as $stat) :
                        $credit_pct = round(($stat->total_credits / $max_credits) * 100);
                        $model_id = isset($stat->model_id) ? $stat->model_id : '';
                        $model_display = isset($model_names[$model_id]) ? $model_names[$model_id] : $model_id;
                        $gen_ts = strtotime($stat->last_generated);
                    ?>
                    <tr>
                        <td>
                            <?php if (!empty($stat->post_title)) : ?>
                                <a href="<?php echo esc_url(get_edit_post_link($stat->post_id)); ?>" class="tts-cup-post-link">
                                    <?php echo esc_html($stat->post_title); ?>
                                </a>
                                <span class="tts-cup-meta">
                                    <span class="tts-cup-type"><?php echo esc_html($stat->post_type); ?></span>
                                    <?php if ($model_display) : ?>
                                        <span class="tts-cup-model"><?php echo esc_html($model_display); ?></span>
                                    <?php endif; ?>
                                </span>
                            <?php else : ?>
                                <span class="tts-cup-deleted"><?php
                                    /* translators: %d: ID of a post that has since been deleted from the site. */
                                    echo esc_html(sprintf(__('Deleted post #%d', 'text-to-speech-tts'), $stat->post_id));
                                ?></span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo esc_html(number_format(isset($stat->last_characters) ? $stat->last_characters : 0)); ?></td>
                        <td>
                            <div class="tts-cup-credits-cell">
                                <span><?php echo esc_html(number_format($stat->total_credits)); ?></span>
                                <div class="tts-cup-minibar"><div class="tts-cup-minibar-fill" style="width: <?php echo esc_attr($credit_pct); ?>%;"></div></div>
                            </div>
                        </td>
                        <td><?php echo esc_html(number_format(isset($stat->last_credits) ? $stat->last_credits : 0)); ?></td>
                        <td><span title="<?php echo esc_attr(wp_date(get_option('date_format') . ' ' . get_option('time_format'), $gen_ts)); ?>"><?php echo esc_html(human_time_diff($gen_ts, current_time('timestamp')) . ' ' . __('ago', 'text-to-speech-tts')); ?></span></td>
                        <td><?php echo esc_html(number_format($stat->generation_count)); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($total_pages > 1) : ?>
            <div class="tts-stats-pagination">
                <span class="tts-stats-pagination-count">
                    <?php /* translators: %s: Total number of items in the paginated list, formatted with thousands separators. */ ?>
                    <?php echo esc_html(sprintf(_n('%s item', '%s items', $total_posts, 'text-to-speech-tts'), number_format($total_posts))); ?>
                </span>
                <?php
                $page_links = paginate_links(array(
                    'base'      => add_query_arg('usage_page', '%#%'),
                    'format'    => '',
                    'prev_text' => '&laquo;',
                    'next_text' => '&raquo;',
                    'total'     => $total_pages,
                    'current'   => $current_page,
                ));
                if ($page_links) {
                    echo wp_kses_post($page_links);
                }
                ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <style>
    /* ── Usage Overview cards ── */
    .tts-uo-grid { gap: 12px; }
    .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;
        color: var(--tts-text-hint, #999);
    }
    .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-uo-value.tts-uo-good { color: #00a32a; }
    .tts-uo-value.tts-uo-warn { color: #dba617; }
    .tts-uo-value.tts-uo-danger { color: #d63638; }
    .tts-uo-inline-icon {
        font-size: 18px !important;
        width: 18px !important;
        height: 18px !important;
        vertical-align: middle;
        margin-right: 2px;
    }

    /* ── Progress bar ── */
    .tts-uo-progress { display: flex; align-items: center; gap: 10px; margin-top: 10px; }
    .tts-uo-progress-track { flex: 1; height: 8px; background: var(--tts-bg-tertiary, #f0f0f0); border-radius: 4px; overflow: hidden; }
    .tts-uo-progress-fill { height: 100%; border-radius: 4px; transition: width 0.3s ease; }
    .tts-uo-progress-pct { font-size: 12px; font-weight: 600; color: var(--tts-text-secondary, #757575); min-width: 36px; text-align: right; }

    /* ── Shared metric hint ── */
    .tts-metric-hint { font-size: 11px; color: var(--tts-text-secondary, #757575); margin-top: 6px; line-height: 1.4; }

    /* ── Empty states ── */
    .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 0; max-width: 500px; margin-left: auto; margin-right: auto; }
    .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; }

    /* ── Mini-card grid (matches statistics page) ── */
    .tts-chart-summary { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
    .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-icon { margin-bottom: 4px; }
    .tts-chart-mini-icon .dashicons { font-size: 18px; width: 18px; height: 18px; color: var(--tts-purple, #6B45D4); }
    .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; margin-top: 4px; }
    .tts-delta-flat { color: var(--tts-text-hint, #999); }
    @media screen and (max-width: 1024px) {
        .tts-chart-summary { grid-template-columns: repeat(2, 1fr); }
    }

    /* ── Credit Usage by Post table ── */
    .tts-cup-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 13px;
    }
    .tts-cup-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-cup-table tbody tr {
        border-bottom: 1px solid var(--tts-border-color, #e2e4e7);
        transition: background 0.15s;
        cursor: pointer;
    }
    .tts-cup-table tbody tr:nth-child(even) { background: var(--tts-bg-secondary, #fafafa); }
    .tts-cup-table tbody tr:hover { background: #f0edff; }
    .tts-cup-table tbody td {
        padding: 10px 12px;
        vertical-align: middle;
        color: var(--tts-text-primary, #1d2327);
    }

    /* Post link + meta */
    .tts-cup-post-link {
        font-weight: 500;
        color: var(--tts-text-primary, #1d2327);
        text-decoration: none;
    }
    .tts-cup-post-link:hover { color: var(--tts-purple, #7c3aed); }
    .tts-cup-meta { display: flex; gap: 5px; margin-top: 3px; }
    .tts-cup-type, .tts-cup-model {
        display: inline-block;
        padding: 1px 6px;
        border-radius: 3px;
        font-size: 10px;
        font-weight: 500;
    }
    .tts-cup-type { background: var(--tts-bg-tertiary, #f0f0f0); color: var(--tts-text-secondary, #666); }
    .tts-cup-model { background: #f0edff; color: var(--tts-purple, #7c3aed); }
    .tts-cup-deleted { color: #a00; font-style: italic; }

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

    /* Pagination */
    .tts-stats-pagination { padding: 12px 20px; text-align: right; border-top: 1px solid var(--tts-border-color, #e2e4e7); }
    .tts-stats-pagination-count { margin-right: 10px; color: #666; }
    .tts-stats-pagination .page-numbers { display: inline-block; padding: 4px 10px; margin: 0 2px; background: var(--tts-bg-secondary, #f0f0f0); border: 1px solid #ddd; border-radius: 3px; text-decoration: none; color: var(--tts-purple, #2271b1); }
    .tts-stats-pagination .page-numbers.current { background: var(--tts-purple, #7c3aed); color: #fff; border-color: var(--tts-purple, #7c3aed); }
    .tts-stats-pagination .page-numbers:hover:not(.current) { background: #e0e0e0; }
    /* Chart legend + toggles */
    .tts-chart-legend { display: flex; align-items: center; gap: 4px; font-size: 12px; color: var(--tts-text-secondary, #666); }
    .tts-chart-legend-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
    .tts-chart-toggle {
        padding: 4px 12px; font-size: 12px; border: 1px solid var(--tts-border-color, #e2e4e7);
        border-radius: var(--tts-radius-md, 8px); background: var(--tts-bg-secondary, #fafafa);
        color: var(--tts-text-secondary, #666); cursor: pointer; transition: all 0.15s;
    }
    .tts-chart-toggle:hover { border-color: var(--tts-purple, #7c3aed); color: var(--tts-purple, #7c3aed); }
    .tts-chart-toggle.active { background: var(--tts-purple, #7c3aed); color: #fff; border-color: var(--tts-purple, #7c3aed); }
    </style>

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

    var ctx = canvas.getContext('2d');
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo wp_json_encode($chart_labels); ?>,
            datasets: [
                {
                    label: '<?php esc_html_e('Credits', 'text-to-speech-tts'); ?>',
                    data: <?php echo wp_json_encode($chart_credits); ?>,
                    borderColor: '#6B45D4',
                    backgroundColor: 'rgba(107,69,212,0.08)',
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 0,
                    pointHoverRadius: 4
                },
                {
                    label: '<?php esc_html_e('Generations', 'text-to-speech-tts'); ?>',
                    data: <?php echo wp_json_encode($chart_generations); ?>,
                    borderColor: '#1D9E75',
                    backgroundColor: 'rgba(29,158,117,0.08)',
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 0,
                    pointHoverRadius: 4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: '#fff',
                    titleColor: '#1d2327',
                    bodyColor: '#50575e',
                    borderColor: '#e2e4e7',
                    borderWidth: 1,
                    padding: 10,
                    cornerRadius: 8
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: { autoSkip: true, maxTicksLimit: 8, font: { size: 11 }, color: '#999' }
                },
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.04)' },
                    ticks: { precision: 0, font: { size: 11 }, color: '#999' }
                }
            }
        }
    });

    // 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.getAttribute('data-show');
            chart.data.datasets[0].hidden = (show === 'generations');
            chart.data.datasets[1].hidden = (show === 'credits');
            chart.update();
        });
    });
})();
</script>

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