<?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'));
}

// ---------------------------------------------------------------------------
// Gather all TTS audio data from post meta
// ---------------------------------------------------------------------------

global $wpdb;

$upload_dir = wp_upload_dir();
$audio_base_dir = $upload_dir['basedir'] . '/text-to-speech-tts/';
$audio_base_url = $upload_dir['baseurl'] . '/text-to-speech-tts/';

// Query all posts that have TTS audio URLs
// Safety cap to prevent excessive memory usage on very large sites
$audio_meta_rows = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT pm.post_id, pm.meta_key, pm.meta_value AS audio_url
         FROM {$wpdb->postmeta} pm
         INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
         WHERE pm.meta_key LIKE %s
           AND pm.meta_value != ''
           AND p.post_status != 'trash'
         ORDER BY pm.post_id DESC
         LIMIT 5000",
        $wpdb->esc_like('_mementor_tts_audio_url') . '%'
    )
);

// Get play stats — combine aggregated historical data with raw current events
$play_counts = array();

// 1. Aggregated table (historical daily rollups)
$agg_table = $wpdb->prefix . 'mementor_tts_player_stats_aggregated';
$agg_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $agg_table));
if ($agg_exists) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from $wpdb->prefix + hardcoded string, verified via SHOW TABLES above.
    $stats_rows = $wpdb->get_results(
        "SELECT post_id, SUM(play_clicks) AS total_plays
         FROM {$agg_table}
         GROUP BY post_id"
    );
    foreach ($stats_rows as $sr) {
        $play_counts[intval($sr->post_id)] = intval($sr->total_plays);
    }
}

// 2. Raw stats table (includes today's unaggregated events)
$raw_table = $wpdb->prefix . 'mementor_tts_player_stats';
$raw_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $raw_table));
if ($raw_exists) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from $wpdb->prefix + hardcoded string, verified via SHOW TABLES above.
    $raw_rows = $wpdb->get_results(
        "SELECT post_id, COUNT(*) AS play_count
         FROM {$raw_table}
         WHERE event_type = 'play'
         GROUP BY post_id"
    );
    foreach ($raw_rows as $rr) {
        $pid = intval($rr->post_id);
        // Use whichever source has the higher count (raw includes all-time + today)
        $play_counts[$pid] = max(isset($play_counts[$pid]) ? $play_counts[$pid] : 0, intval($rr->play_count));
    }
}

// Get generation dates from history table
$history_table = $wpdb->prefix . 'mementor_tts_generation_history';
$gen_dates = array();
$history_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $history_table));
if ($history_exists) {
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from $wpdb->prefix + hardcoded string, verified via SHOW TABLES above.
    $history_rows = $wpdb->get_results(
        "SELECT post_id, MAX(generated_at) AS last_generated
         FROM {$history_table}
         GROUP BY post_id"
    );
    foreach ($history_rows as $hr) {
        $gen_dates[intval($hr->post_id)] = $hr->last_generated;
    }
}

// Build audio items array
$audio_items = array();
$total_size_bytes = 0;
$total_plays = 0;
$seen_post_types = array();
$seen_languages = array();

foreach ($audio_meta_rows as $row) {
    $post_id = intval($row->post_id);
    $audio_url = $row->audio_url;
    $meta_key = $row->meta_key;

    // Extract language from meta key
    $lang = '';
    if ($meta_key !== '_mementor_tts_audio_url') {
        $lang = str_replace('_mementor_tts_audio_url_', '', $meta_key);
    }

    // Skip S3 URLs for file size calculation
    $is_s3 = (strpos($audio_url, 'amazonaws.com') !== false || strpos($audio_url, '.s3.') !== false);

    // Get file size
    $file_size = 0;
    if (!$is_s3) {
        $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $audio_url);
        if (file_exists($file_path)) {
            $file_size = filesize($file_path);
        }
    }

    $total_size_bytes += $file_size;

    // Get post data
    $post = get_post($post_id);
    if (!$post) {
        continue;
    }

    $post_type = get_post_type($post_id);
    if ($post_type) {
        $seen_post_types[$post_type] = true;
    }
    if ($lang) {
        $seen_languages[$lang] = true;
    }

    // Get play count for this post
    $plays = isset($play_counts[$post_id]) ? $play_counts[$post_id] : 0;
    $total_plays += $plays;

    // Get generation date
    $added_date = '';
    if (isset($gen_dates[$post_id])) {
        $added_date = $gen_dates[$post_id];
    }

    // Get attachment ID
    $attachment_id = get_post_meta($post_id, '_mementor_tts_attachment_id', true);

    // Get duration from attachment metadata if available
    $duration = '';
    if ($attachment_id) {
        $meta = wp_get_attachment_metadata($attachment_id);
        if ($meta && isset($meta['length_formatted'])) {
            $duration = $meta['length_formatted'];
        } elseif ($meta && isset($meta['length'])) {
            $mins = floor($meta['length'] / 60);
            $secs = $meta['length'] % 60;
            $duration = sprintf('%d:%02d', $mins, $secs);
        }
    }

    $audio_items[] = array(
        'post_id'       => $post_id,
        'post_title'    => $post->post_title,
        'post_type'     => $post_type,
        'post_url'      => get_permalink($post_id),
        'edit_url'      => get_edit_post_link($post_id, 'raw'),
        'audio_url'     => $audio_url,
        'lang'          => $lang,
        'file_size'     => $file_size,
        'duration'      => $duration,
        'plays'         => $plays,
        'added_date'    => $added_date,
        'attachment_id' => $attachment_id,
    );
}

// Deduplicate: per post, keep only the language-specific meta (e.g. _audio_url_no)
// over the generic _audio_url — they often point to different URLs (CDN vs local)
$deduped_items = array();
foreach ($audio_items as $item) {
    $key = $item['post_id'];
    if (isset($deduped_items[$key])) {
        // Prefer the entry with a language code (more specific)
        if (!empty($item['lang']) && empty($deduped_items[$key]['lang'])) {
            $deduped_items[$key] = $item;
        }
        continue;
    }
    $deduped_items[$key] = $item;
}
$audio_items = array_values($deduped_items);
$total_files = count($audio_items);

// Check for active translation plugins
$has_wpml = defined('ICL_SITEPRESS_VERSION');
$has_weglot = defined('WEGLOT_VERSION');
$has_polylang = function_exists('pll_the_languages');
$show_lang_filter = $has_wpml || $has_weglot || $has_polylang || count($seen_languages) > 1;

// Format total size
if ($total_size_bytes >= 1048576) {
    $total_size_display = number_format($total_size_bytes / 1048576, 1) . ' MB';
} elseif ($total_size_bytes >= 1024) {
    $total_size_display = number_format($total_size_bytes / 1024, 0) . ' KB';
} else {
    $total_size_display = $total_size_bytes . ' B';
}

?>

<?php
$tts_page_title = __('Audio Library', 'text-to-speech-tts');
$tts_topbar_actions = '<button type="button" class="tts-btn" id="tts-library-refresh">'
    . esc_html__('Refresh', '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'); ?>

            <!-- Summary Metrics -->
            <div class="tts-chart-summary tts-library-summary-grid">
                <div class="tts-chart-mini-card">
                    <div class="tts-chart-mini-icon"><span class="dashicons dashicons-media-audio"></span></div>
                    <div class="tts-chart-mini-label"><?php esc_html_e('Audio Files', 'text-to-speech-tts'); ?></div>
                    <div class="tts-chart-mini-value"><?php echo esc_html(number_format($total_files)); ?></div>
                </div>
                <div class="tts-chart-mini-card">
                    <div class="tts-chart-mini-icon"><span class="dashicons dashicons-cloud"></span></div>
                    <div class="tts-chart-mini-label"><?php esc_html_e('Storage Used', 'text-to-speech-tts'); ?></div>
                    <div class="tts-chart-mini-value"><?php echo esc_html($total_size_display); ?></div>
                </div>
                <div class="tts-chart-mini-card">
                    <div class="tts-chart-mini-icon"><span class="dashicons dashicons-controls-play"></span></div>
                    <div class="tts-chart-mini-label"><?php esc_html_e('Total Plays', 'text-to-speech-tts'); ?></div>
                    <div class="tts-chart-mini-value"><?php echo esc_html(number_format($total_plays)); ?></div>
                </div>
            </div>

            <!-- Audio Library Table -->
            <div class="tts-card">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Audio Files', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php echo esc_html(sprintf(
                        /* translators: %d: number of audio files */
                        _n('%d file', '%d files', $total_files, 'text-to-speech-tts'),
                        $total_files
                    )); ?></p>
                </div>

                <?php if (empty($audio_items)) : ?>
                <div class="tts-library-empty">
                    <p><?php esc_html_e('No audio files generated yet.', 'text-to-speech-tts'); ?></p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-content')); ?>" class="tts-btn tts-btn-primary">
                        <?php esc_html_e('Generate your first audio', 'text-to-speech-tts'); ?> &rarr;
                    </a>
                </div>
                <?php else : ?>

                <!-- Filters -->
                <div class="tts-library-filters">
                    <input type="text"
                           placeholder="<?php esc_attr_e('Search posts...', 'text-to-speech-tts'); ?>"
                           class="tts-search-input"
                           id="tts-library-search" />

                    <select class="tts-filter-select" id="tts-filter-type">
                        <option value=""><?php esc_html_e('All post types', 'text-to-speech-tts'); ?></option>
                        <?php foreach (array_keys($seen_post_types) as $pt) : ?>
                            <option value="<?php echo esc_attr($pt); ?>"><?php echo esc_html(ucfirst($pt)); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <?php if ($show_lang_filter) : ?>
                    <select class="tts-filter-select" id="tts-filter-lang">
                        <option value=""><?php esc_html_e('All languages', 'text-to-speech-tts'); ?></option>
                        <?php foreach (array_keys($seen_languages) as $lc) : ?>
                            <option value="<?php echo esc_attr($lc); ?>"><?php echo esc_html(strtoupper($lc)); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>

                    <select class="tts-filter-select" id="tts-filter-sort">
                        <option value="newest"><?php esc_html_e('Newest first', 'text-to-speech-tts'); ?></option>
                        <option value="oldest"><?php esc_html_e('Oldest first', 'text-to-speech-tts'); ?></option>
                        <option value="most_played"><?php esc_html_e('Most played', 'text-to-speech-tts'); ?></option>
                        <option value="largest"><?php esc_html_e('Largest file', 'text-to-speech-tts'); ?></option>
                    </select>
                </div>

                <!-- Bulk Actions Bar -->
                <div class="tts-bulk-bar" id="tts-bulk-bar" style="display:none;">
                    <span class="tts-bulk-count">
                        <strong id="tts-selected-count">0</strong> <?php esc_html_e('files selected', 'text-to-speech-tts'); ?>
                    </span>
                    <div class="tts-bulk-actions">
                        <button class="tts-btn tts-bulk-download">&darr; <?php esc_html_e('Download all', 'text-to-speech-tts'); ?></button>
                        <button class="tts-btn tts-btn-danger tts-bulk-delete">&times; <?php esc_html_e('Delete selected', 'text-to-speech-tts'); ?></button>
                    </div>
                    <button class="tts-btn tts-bulk-cancel"><?php esc_html_e('Cancel', 'text-to-speech-tts'); ?></button>
                </div>

                <!-- Table Header -->
                <div class="tts-library-header">
                    <span class="tts-lib-col-check"><input type="checkbox" id="tts-select-all" class="tts-checkbox" /></span>
                    <span class="tts-lib-col-title"><?php esc_html_e('Title', 'text-to-speech-tts'); ?></span>
                    <span class="tts-lib-col-type"><?php esc_html_e('Type', 'text-to-speech-tts'); ?></span>
                    <?php if ($show_lang_filter) : ?>
                    <span class="tts-lib-col-lang"><?php esc_html_e('Lang', 'text-to-speech-tts'); ?></span>
                    <?php endif; ?>
                    <span class="tts-lib-col-added"><?php esc_html_e('Added', 'text-to-speech-tts'); ?></span>
                    <span class="tts-lib-col-duration"><?php esc_html_e('Duration', 'text-to-speech-tts'); ?></span>
                    <span class="tts-lib-col-size"><?php esc_html_e('Size', 'text-to-speech-tts'); ?></span>
                    <span class="tts-lib-col-plays"><?php esc_html_e('Plays', 'text-to-speech-tts'); ?></span>
                    <span class="tts-lib-col-actions"><?php esc_html_e('Actions', 'text-to-speech-tts'); ?></span>
                </div>

                <!-- Table Rows -->
                <div id="tts-library-rows">
                <?php foreach ($audio_items as $item) :
                    // Format file size per row
                    if ($item['file_size'] >= 1048576) {
                        $size_display = number_format($item['file_size'] / 1048576, 1) . ' MB';
                    } elseif ($item['file_size'] >= 1024) {
                        $size_display = number_format($item['file_size'] / 1024, 0) . ' KB';
                    } elseif ($item['file_size'] > 0) {
                        $size_display = $item['file_size'] . ' B';
                    } else {
                        $size_display = '—';
                    }

                    // Format date
                    $date_display = '—';
                    if (!empty($item['added_date'])) {
                        $date_display = wp_date(get_option('date_format'), strtotime($item['added_date']));
                    }
                ?>
                    <div class="tts-library-row"
                         data-post-id="<?php echo esc_attr($item['post_id']); ?>"
                         data-type="<?php echo esc_attr($item['post_type']); ?>"
                         data-lang="<?php echo esc_attr($item['lang']); ?>"
                         data-size="<?php echo esc_attr($item['file_size']); ?>"
                         data-plays="<?php echo esc_attr($item['plays']); ?>"
                         data-date="<?php echo esc_attr($item['added_date']); ?>">

                        <span class="tts-lib-col-check">
                            <input type="checkbox" class="tts-checkbox tts-row-check"
                                   data-post="<?php echo esc_attr($item['post_id']); ?>"
                                   data-url="<?php echo esc_attr($item['audio_url']); ?>" />
                        </span>

                        <span class="tts-lib-col-title">
                            <a href="<?php echo esc_url($item['post_url']); ?>" target="_blank"><?php echo esc_html($item['post_title']); ?></a>
                        </span>

                        <span class="tts-lib-col-type">
                            <span class="tts-tag"><?php echo esc_html($item['post_type']); ?></span>
                        </span>

                        <?php if ($show_lang_filter) : ?>
                        <span class="tts-lib-col-lang">
                            <?php if (!empty($item['lang'])) : ?>
                                <span class="tts-lang-tag"><?php echo esc_html(strtoupper($item['lang'])); ?></span>
                            <?php else : ?>
                                —
                            <?php endif; ?>
                        </span>
                        <?php endif; ?>

                        <span class="tts-lib-col-added"><?php echo esc_html($date_display); ?></span>
                        <span class="tts-lib-col-duration"><?php echo esc_html($item['duration'] ?: '—'); ?></span>
                        <span class="tts-lib-col-size"><?php echo esc_html($size_display); ?></span>
                        <span class="tts-lib-col-plays"><?php echo esc_html(number_format($item['plays'])); ?></span>

                        <span class="tts-lib-col-actions">
                            <button class="tts-btn tts-play-btn" data-src="<?php echo esc_attr($item['audio_url']); ?>" title="<?php esc_attr_e('Play', 'text-to-speech-tts'); ?>">&#9654;</button>
                            <a href="<?php echo esc_url($item['audio_url']); ?>" download class="tts-btn" title="<?php esc_attr_e('Download', 'text-to-speech-tts'); ?>">&darr;</a>
                            <button class="tts-btn tts-regenerate-btn"
                                    data-post="<?php echo esc_attr($item['post_id']); ?>"
                                    data-lang="<?php echo esc_attr($item['lang']); ?>"
                                    title="<?php esc_attr_e('Regenerate audio', 'text-to-speech-tts'); ?>">&#8634;</button>
                            <button class="tts-btn tts-btn-danger tts-delete-btn"
                                    data-post="<?php echo esc_attr($item['post_id']); ?>"
                                    title="<?php esc_attr_e('Delete', 'text-to-speech-tts'); ?>">&times;</button>
                        </span>
                    </div>
                <?php endforeach; ?>
                </div>

                <?php endif; ?>
            </div>

            <style>
            /* Summary cards */
            .tts-library-summary-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
                margin-bottom: 16px;
            }
            .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;
            }

            /* Filters */
            .tts-library-filters {
                display: flex;
                gap: 8px;
                padding: 0 0 16px;
                flex-wrap: wrap;
            }

            .tts-search-input {
                flex: 1;
                min-width: 200px;
                font-size: 13px;
                padding: 7px 12px;
                border: var(--tts-border);
                border-radius: var(--tts-radius-md);
                background: var(--tts-bg-secondary);
                color: var(--tts-text-primary);
            }

            .tts-search-input:focus {
                border-color: var(--tts-purple);
                outline: none;
                box-shadow: 0 0 0 3px var(--tts-purple-bg);
            }

            .tts-filter-select {
                font-size: 12px;
                padding: 7px 10px;
                border: var(--tts-border);
                border-radius: var(--tts-radius-md);
                background: var(--tts-bg-secondary);
                color: var(--tts-text-primary);
            }

            /* Grid layout */
            <?php $cols = $show_lang_filter ? '32px 2fr 80px 50px 100px 80px 70px 60px 160px' : '32px 2fr 80px 100px 80px 70px 60px 160px'; ?>
            .tts-library-header,
            .tts-library-row {
                display: grid;
                grid-template-columns: <?php echo esc_attr($cols); ?>;
                align-items: center;
                gap: 12px;
                padding: 10px 2px;
                font-size: 12px;
            }

            .tts-library-header {
                font-size: 10px;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.06em;
                color: var(--tts-text-hint, #999);
                border-bottom: var(--tts-border);
                padding-bottom: 8px;
            }

            .tts-library-row {
                border-bottom: var(--tts-border);
                color: var(--tts-text-primary);
                transition: background 0.1s;
            }

            .tts-library-row:last-child {
                border-bottom: none;
            }

            .tts-library-row:hover {
                background: var(--tts-bg-secondary);
            }

            /* Title column */
            .tts-lib-col-title a {
                color: var(--tts-text-primary);
                text-decoration: none;
                font-weight: 500;
                font-size: 13px;
            }

            .tts-lib-col-title a:hover {
                color: var(--tts-purple);
            }

            /* Tags */
            .tts-tag {
                font-size: 11px;
                padding: 2px 6px;
                border-radius: var(--tts-radius-sm);
                background: var(--tts-bg-secondary);
                color: var(--tts-text-secondary);
            }

            .tts-lang-tag {
                font-size: 11px;
                font-weight: 600;
                padding: 2px 6px;
                border-radius: var(--tts-radius-sm);
                background: var(--tts-bg-secondary);
                color: var(--tts-text-secondary);
                border: var(--tts-border);
                text-transform: uppercase;
            }

            /* Actions */
            .tts-lib-col-actions {
                display: flex;
                align-items: center;
                gap: 4px;
            }

            .tts-play-btn,
            .tts-delete-btn {
                width: 28px;
                height: 28px;
                padding: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 11px;
                flex-shrink: 0;
            }

            .tts-regenerate-btn {
                font-size: 11px;
                color: var(--tts-purple);
                border-color: var(--tts-purple-border, #d4c5f9);
                background: var(--tts-purple-bg);
                padding: 4px 8px;
            }

            .tts-regenerate-btn.is-success {
                color: #0F6E56;
                border-color: #0F6E56;
                background: #e6f7f1;
            }

            .tts-regenerate-btn:hover {
                background: var(--tts-purple-border, #d4c5f9);
            }

            .tts-regenerate-btn.is-loading {
                opacity: 0.6;
                pointer-events: none;
            }

            .tts-regenerate-btn.is-loading::after {
                content: '';
                width: 10px;
                height: 10px;
                border: 1.5px solid var(--tts-purple);
                border-top-color: transparent;
                border-radius: 50%;
                animation: tts-lib-spin 0.6s linear infinite;
                margin-left: 4px;
                display: inline-block;
            }

            @keyframes tts-lib-spin {
                to { transform: rotate(360deg); }
            }

            /* Empty state */
            .tts-library-empty {
                text-align: center;
                padding: 40px 20px;
                color: var(--tts-text-hint, #999);
                font-size: 13px;
            }

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

            /* Checkbox */
            .tts-checkbox {
                cursor: pointer;
                flex-shrink: 0;
            }

            /* Bulk bar */
            .tts-bulk-bar {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 10px 14px;
                margin: 0 0 12px;
                background: var(--tts-purple-bg);
                border: 0.5px solid var(--tts-purple-border, #d4c5f9);
                border-radius: var(--tts-radius-md);
                font-size: 13px;
            }

            .tts-bulk-count {
                flex: 1;
                color: var(--tts-purple, #7c3aed);
            }

            .tts-bulk-actions {
                display: flex;
                gap: 8px;
            }

            /* Responsive */
            @media screen and (max-width: 1200px) {
                .tts-library-header,
                .tts-library-row {
                    font-size: 11px;
                    gap: 8px;
                }
            }
            </style>

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

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Refresh
    $('#tts-library-refresh').on('click', function() {
        window.location.reload();
    });

    // Filtering
    var $search = $('#tts-library-search');
    var $typeFilter = $('#tts-filter-type');
    var $langFilter = $('#tts-filter-lang');
    var $sortFilter = $('#tts-filter-sort');
    var $rows = $('#tts-library-rows .tts-library-row');

    function filterRows() {
        var q = $search.val().toLowerCase();
        var type = $typeFilter.val();
        var lang = $langFilter.length ? $langFilter.val() : '';

        $rows.each(function() {
            var $row = $(this);
            var title = $row.find('.tts-lib-col-title').text().toLowerCase();
            var rowType = $row.data('type');
            var rowLang = $row.data('lang') || '';

            var matchQ = !q || title.indexOf(q) !== -1;
            var matchType = !type || rowType === type;
            var matchLang = !lang || rowLang === lang;

            $row.toggle(matchQ && matchType && matchLang);
        });
    }

    function sortRows() {
        var sort = $sortFilter.val();
        var $container = $('#tts-library-rows');
        var rows = $container.children('.tts-library-row').get();

        rows.sort(function(a, b) {
            var $a = $(a), $b = $(b);
            switch (sort) {
                case 'newest':
                    return ($b.data('date') || '').localeCompare($a.data('date') || '');
                case 'oldest':
                    return ($a.data('date') || '').localeCompare($b.data('date') || '');
                case 'most_played':
                    return parseInt($b.data('plays') || 0) - parseInt($a.data('plays') || 0);
                case 'largest':
                    return parseInt($b.data('size') || 0) - parseInt($a.data('size') || 0);
            }
            return 0;
        });

        $.each(rows, function(i, row) {
            $container.append(row);
        });
    }

    $search.on('input', filterRows);
    $typeFilter.on('change', filterRows);
    if ($langFilter.length) $langFilter.on('change', filterRows);
    $sortFilter.on('change', function() { sortRows(); filterRows(); });

    // Inline play
    var currentAudio = null;
    var currentBtn = null;

    $(document).on('click', '.tts-play-btn', function() {
        var $btn = $(this);

        if (currentAudio) {
            currentAudio.pause();
            if (currentBtn) currentBtn.html('&#9654;');
            if (currentBtn && currentBtn[0] === $btn[0]) {
                currentAudio = null;
                currentBtn = null;
                return;
            }
        }

        var src = $btn.data('src');
        currentAudio = new Audio(src);
        currentBtn = $btn;
        currentAudio.play();
        $btn.html('&#9724;');

        currentAudio.addEventListener('ended', function() {
            $btn.html('&#9654;');
            currentAudio = null;
            currentBtn = null;
        });
    });

    // Regenerate
    $(document).on('click', '.tts-regenerate-btn', function() {
        var $btn = $(this);
        var postId = $btn.data('post');

        $btn.addClass('is-loading');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_generate_audio',
                post_id: postId,
                nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>'
            },
            success: function(response) {
                $btn.removeClass('is-loading');
                if (response.success) {
                    $btn.html('&#10003;').addClass('is-success');
                    setTimeout(function() {
                        $btn.html('&#8634;').removeClass('is-success');
                    }, 2000);
                    if (typeof mementorTTSShowNotification === 'function') {
                        mementorTTSShowNotification('<?php echo esc_js(__('Audio was successfully regenerated.', 'text-to-speech-tts')); ?>', 'success');
                    }
                } else {
                    alert(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error regenerating audio.', 'text-to-speech-tts')); ?>');
                }
            },
            error: function() {
                $btn.removeClass('is-loading');
                alert('<?php echo esc_js(__('Error regenerating audio.', 'text-to-speech-tts')); ?>');
            }
        });
    });

    // Bulk selection
    var $selectAll = $('#tts-select-all');
    var $bulkBar = $('#tts-bulk-bar');
    var $countEl = $('#tts-selected-count');

    function updateBulkBar() {
        var checked = $('.tts-row-check:checked').length;
        $countEl.text(checked);
        $bulkBar.toggle(checked > 0);
        $selectAll.prop('indeterminate', checked > 0 && checked < $('.tts-row-check:visible').length);
        if (checked === $('.tts-row-check:visible').length && checked > 0) {
            $selectAll.prop('checked', true).prop('indeterminate', false);
        } else if (checked === 0) {
            $selectAll.prop('checked', false).prop('indeterminate', false);
        }
    }

    $selectAll.on('change', function() {
        $('.tts-row-check:visible').prop('checked', this.checked);
        updateBulkBar();
    });

    $(document).on('change', '.tts-row-check', updateBulkBar);

    // Bulk cancel
    $(document).on('click', '.tts-bulk-cancel', function() {
        $('.tts-row-check, #tts-select-all').prop('checked', false).prop('indeterminate', false);
        updateBulkBar();
    });

    // Bulk download (single file = direct, multiple = zip)
    $(document).on('click', '.tts-bulk-download', function() {
        var $checked = $('.tts-row-check:checked');
        var count = $checked.length;
        if (!count) return;

        if (count === 1) {
            // Single file — download directly
            var a = document.createElement('a');
            a.href = $checked.first().data('url');
            a.download = '';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            return;
        }

        // Multiple files — create zip
        var urls = [];
        $checked.each(function() { urls.push($(this).data('url')); });

        var $btn = $('.tts-bulk-download');
        $btn.prop('disabled', true).text('<?php echo esc_js(__('Creating zip...', 'text-to-speech-tts')); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_bulk_download_zip',
                urls: urls,
                nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>'
            },
            success: function(response) {
                $btn.prop('disabled', false).html('&darr; <?php echo esc_js(__('Download all', 'text-to-speech-tts')); ?>');
                if (response.success) {
                    var a = document.createElement('a');
                    a.href = response.data.url;
                    a.download = response.data.filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    alert(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error creating zip file.', 'text-to-speech-tts')); ?>');
                }
            },
            error: function() {
                $btn.prop('disabled', false).html('&darr; <?php echo esc_js(__('Download all', 'text-to-speech-tts')); ?>');
                alert('<?php echo esc_js(__('Error creating zip file.', 'text-to-speech-tts')); ?>');
            }
        });
    });

    // Bulk delete
    $(document).on('click', '.tts-bulk-delete', function() {
        var $checked = $('.tts-row-check:checked');
        var count = $checked.length;
        if (!count) return;
        if (!confirm('<?php echo esc_js(__('Delete', 'text-to-speech-tts')); ?> ' + count + ' <?php echo esc_js(__('audio files? This cannot be undone.', 'text-to-speech-tts')); ?>')) return;

        var postIds = [];
        $checked.each(function() { postIds.push($(this).data('post')); });

        var completed = 0;
        postIds.forEach(function(postId) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_delete_audio',
                    post_id: postId,
                    nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>'
                },
                success: function(response) {
                    completed++;
                    if (response.success) {
                        $('.tts-library-row[data-post-id="' + postId + '"]').remove();
                    }
                    if (completed === postIds.length) {
                        $selectAll.prop('checked', false);
                        updateBulkBar();
                    }
                },
                error: function() {
                    completed++;
                    if (completed === postIds.length) {
                        updateBulkBar();
                    }
                }
            });
        });
    });

    // Bulk rename
    $(document).on('click', '.tts-bulk-rename', function() {
        var $checked = $('.tts-row-check:checked');
        var count = $checked.length;
        if (!count) return;
        if (!confirm('<?php echo esc_js(__('Rename', 'text-to-speech-tts')); ?> ' + count + ' <?php echo esc_js(__('audio file(s) to use post title in filename? Only old-format files (mementor-ID-lang.mp3) will be renamed.', 'text-to-speech-tts')); ?>')) return;

        var postIds = [];
        $checked.each(function() {
            var pid = $(this).data('post');
            if (postIds.indexOf(pid) === -1) postIds.push(pid);
        });

        var completed = 0;
        var totalRenamed = 0;
        var $btn = $('.tts-bulk-rename');
        $btn.prop('disabled', true).text('<?php echo esc_js(__('Renaming...', 'text-to-speech-tts')); ?> 0/' + postIds.length);

        postIds.forEach(function(postId) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_rename_audio',
                    post_id: postId,
                    nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>'
                },
                success: function(response) {
                    completed++;
                    if (response.success && response.data.renamed > 0) {
                        totalRenamed += response.data.renamed;
                    }
                    $btn.text('<?php echo esc_js(__('Renaming...', 'text-to-speech-tts')); ?> ' + completed + '/' + postIds.length);
                    if (completed === postIds.length) {
                        $btn.prop('disabled', false).html('&#9998; <?php echo esc_js(__('Rename filenames', 'text-to-speech-tts')); ?>');
                        if (totalRenamed > 0) {
                            alert(totalRenamed + ' <?php echo esc_js(__('file(s) renamed. Refreshing page...', 'text-to-speech-tts')); ?>');
                            window.location.reload();
                        } else {
                            alert('<?php echo esc_js(__('No old-format files found in selection. All files already use the new naming format.', 'text-to-speech-tts')); ?>');
                        }
                    }
                },
                error: function() {
                    completed++;
                    $btn.text('<?php echo esc_js(__('Renaming...', 'text-to-speech-tts')); ?> ' + completed + '/' + postIds.length);
                    if (completed === postIds.length) {
                        $btn.prop('disabled', false).html('&#9998; <?php echo esc_js(__('Rename filenames', 'text-to-speech-tts')); ?>');
                        if (totalRenamed > 0) {
                            window.location.reload();
                        }
                    }
                }
            });
        });
    });

    // Delete
    $(document).on('click', '.tts-delete-btn', function() {
        if (!confirm('<?php echo esc_js(__('Delete this audio file? This cannot be undone.', 'text-to-speech-tts')); ?>')) return;

        var $btn = $(this);
        var $row = $btn.closest('.tts-library-row');
        var postId = $btn.data('post');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_delete_audio',
                post_id: postId,
                nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error deleting audio.', 'text-to-speech-tts')); ?>');
                }
            },
            error: function() {
                alert('<?php echo esc_js(__('Error deleting audio.', 'text-to-speech-tts')); ?>');
            }
        });
    });
});
</script>
