<?php
/**
 * Keywords Page
 *
 * @package AIContentGenerator
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

require_once ROIDAICO_PLUGIN_DIR . 'includes/class-license-manager.php';
$is_pro = AICG\License_Manager::is_pro();
$can_generate = AICG\License_Manager::can_generate_ai_keywords();
$remaining = AICG\License_Manager::get_remaining_ai_keywords();

$keyword_manager = new AICG\Keyword_Manager();

// Get filter parameters
$current_category = isset($_GET['category']) ? absint($_GET['category']) : null;
$current_status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : null;
$current_language = isset($_GET['language']) ? sanitize_text_field($_GET['language']) : null;
$current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;

// Get keywords
$keywords_data = $keyword_manager->get_all(array(
    'category_id' => $current_category,
    'status' => $current_status,
    'language' => $current_language,
    'page' => $current_page,
    'per_page' => 20,
));

// Get categories for filter
$categories = get_categories(array('hide_empty' => false));

// Pre-fetch child translations for the displayed page items to avoid N+1 queries
$translations_map = array();
if (!empty($keywords_data['items'])) {
    $item_ids = wp_list_pluck($keywords_data['items'], 'id');
    if (!empty($item_ids)) {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_keywords';
        $placeholders = implode(',', array_fill(0, count($item_ids), '%d'));
        $trans_results = $wpdb->get_results($wpdb->prepare(
            "SELECT id, keyword, language, translation_of, status FROM $table WHERE translation_of IN ($placeholders)",
            $item_ids
        ));
        if (!empty($trans_results)) {
            foreach ($trans_results as $tr) {
                $translations_map[$tr->translation_of][] = $tr;
            }
        }
    }
}

if (!function_exists('roidaico_get_active_languages')) {
    function roidaico_get_active_languages() {
        $langs = array();
        
        // Polylang
        if (function_exists('pll_languages_list')) {
            $slugs = pll_languages_list(array('fields' => 'slug')) ?: array();
            $names = pll_languages_list(array('fields' => 'name')) ?: array();
            if (count($slugs) === count($names) && !empty($slugs)) {
                $langs = array_combine($slugs, $names);
            } else {
                foreach ($slugs as $slug) {
                    $langs[$slug] = strtoupper($slug);
                }
            }
        }
        // WPML
        elseif (function_exists('wpml_get_active_languages_filter') || has_filter('wpml_active_languages')) {
            $wpml_langs = apply_filters('wpml_active_languages', null, array('skip_missing' => 0));
            if (is_array($wpml_langs)) {
                foreach ($wpml_langs as $lang) {
                    $langs[$lang['code']] = $lang['english_name'];
                }
            }
        }
        
        // Default languages if no multilingual plugin is active
        if (empty($langs)) {
            $locale = get_locale();
            $lang_code = substr($locale, 0, 2);
            $lang_name = strtoupper($lang_code);
            if ($lang_code === 'en') {
                $lang_name = __('English', 'roidnet-ai-content-generator');
            } elseif ($lang_code === 'ar') {
                $lang_name = __('Arabic', 'roidnet-ai-content-generator');
            } elseif ($lang_code === 'tr') {
                $lang_name = __('Turkish', 'roidnet-ai-content-generator');
            }
            $langs = array(
                $lang_code => $lang_name
            );
        }
        
        return $langs;
    }
}

if (!function_exists('roidaico_get_term_language')) {
    function roidaico_get_term_language($term_id, $taxonomy = 'category') {
        // Polylang
        if (function_exists('pll_get_term_language')) {
            return pll_get_term_language($term_id);
        }
        // WPML
        if (has_filter('wpml_element_language_code')) {
            return apply_filters('wpml_element_language_code', null, array(
                'element_id'   => $term_id,
                'element_type' => $taxonomy
            ));
        }
        return '';
    }
}

$active_languages = roidaico_get_active_languages();
?>

<div class="wrap roidaico-wrap">
    <h1>
        <?php esc_html_e('Keywords Queue', 'roidnet-ai-content-generator'); ?>
        <button type="button" class="page-title-action" id="roidaico-add-keyword-btn">
            <?php esc_html_e('Add Keyword', 'roidnet-ai-content-generator'); ?>
        </button>
        <button type="button" class="page-title-action <?php echo !$can_generate ? 'roidaico-disabled' : ''; ?>" id="roidaico-generate-keywords-btn" <?php echo !$can_generate ? 'disabled' : ''; ?>>
            <?php esc_html_e('Generate Keywords', 'roidnet-ai-content-generator'); ?>
            <?php if (!$is_pro): ?>
                <span class="roidaico-quota-badge">(<?php printf(esc_html__('%s remaining', 'roidnet-ai-content-generator'), esc_html($remaining)); ?>)</span>
            <?php endif; ?>
        </button>
    </h1>

    <!-- Add Keyword Modal -->
    <div id="roidaico-add-keyword-modal" class="roidaico-modal" style="display: none;">
        <div class="roidaico-modal-content">
            <span class="roidaico-modal-close">&times;</span>
            <h2>
                <?php esc_html_e('Add Keyword', 'roidnet-ai-content-generator'); ?>
            </h2>
            <form id="roidaico-add-keyword-form">
                <input type="hidden" id="add-translation-of" name="translation_of" value="">
                <table class="form-table">
                    <tr>
                        <th><label for="add-keywords">
                                <?php esc_html_e('Keywords', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <textarea id="add-keywords" name="keywords" class="large-text" rows="5" required
                                placeholder="<?php esc_attr_e('Enter keywords (one per line or comma-separated)', 'roidnet-ai-content-generator'); ?>"></textarea>
                            <p class="description">
                                <?php esc_html_e('Enter multiple keywords, one per line or separated by commas.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="add-language">
                                <?php esc_html_e('Language', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="add-language" name="language">
                                <?php foreach ($active_languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>" <?php selected($code, get_option('roidaico_default_language', 'en')); ?>>
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="add-category">
                                <?php esc_html_e('Category', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="add-category" name="category_id">
                                <?php foreach ($categories as $category): ?>
                                    <?php 
                                    $term_lang = roidaico_get_term_language($category->term_id);
                                    ?>
                                    <option value="<?php echo esc_attr($category->term_id); ?>" data-lang="<?php echo esc_attr($term_lang); ?>">
                                        <?php echo esc_html($category->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Add to Queue', 'roidnet-ai-content-generator'); ?>
                    </button>
                </p>
            </form>
        </div>
    </div>

    <!-- Generate Keywords Modal -->
    <div id="roidaico-generate-keywords-modal" class="roidaico-modal" style="display: none;">
        <div class="roidaico-modal-content">
            <span class="roidaico-modal-close">&times;</span>
            <h2>
                <?php esc_html_e('Generate Keywords with AI', 'roidnet-ai-content-generator'); ?>
            </h2>
            <form id="roidaico-generate-keywords-form">
                <table class="form-table">
                    <tr>
                        <th><label for="gen-topic">
                                <?php esc_html_e('Topic', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <input type="text" id="gen-topic" name="topic" class="regular-text"
                                placeholder="<?php esc_attr_e('e.g., Digital Marketing Tips', 'roidnet-ai-content-generator'); ?>"
                                required>
                            <p class="description">
                                <?php esc_html_e('Describe the topic to generate keywords for.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="gen-count">
                                <?php esc_html_e('Number of Keywords', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <input type="number" id="gen-count" name="count" value="10" min="1" max="50"
                                class="small-text">
                        </td>
                    </tr>
                    <tr>
                        <th><label for="gen-language">
                                <?php esc_html_e('Language', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="gen-language" name="language">
                                <?php foreach ($active_languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>" <?php selected($code, get_option('roidaico_default_language', 'en')); ?>>
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="gen-category">
                                <?php esc_html_e('Category', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="gen-category" name="category_id">
                                <?php foreach ($categories as $category): ?>
                                    <?php 
                                    $term_lang = roidaico_get_term_language($category->term_id);
                                    ?>
                                    <option value="<?php echo esc_attr($category->term_id); ?>" data-lang="<?php echo esc_attr($term_lang); ?>">
                                        <?php echo esc_html($category->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                </table>
                <div id="roidaico-generated-keywords" style="display: none;">
                    <h3>
                        <?php esc_html_e('Generated Keywords', 'roidnet-ai-content-generator'); ?>
                    </h3>
                    <p class="description">
                        <?php esc_html_e('Select keywords to add to the queue:', 'roidnet-ai-content-generator'); ?>
                    </p>
                    <div id="roidaico-keywords-list"></div>
                </div>
                <p class="submit">
                    <button type="submit" class="button button-primary" id="roidaico-generate-btn">
                        <?php esc_html_e('Generate Keywords', 'roidnet-ai-content-generator'); ?>
                    </button>
                    <button type="button" class="button" id="roidaico-add-selected-btn" style="display: none;">
                        <?php esc_html_e('Add Selected to Queue', 'roidnet-ai-content-generator'); ?>
                    </button>
                </p>
            </form>
        </div>
    </div>

    <!-- Filters -->
    <div class="roidaico-filters">
        <form method="get">
            <input type="hidden" name="page" value="roidaico-keywords">

            <select name="category">
                <option value="">
                    <?php esc_html_e('All Categories', 'roidnet-ai-content-generator'); ?>
                </option>
                <?php foreach ($categories as $category): ?>
                    <?php 
                    $term_lang = roidaico_get_term_language($category->term_id);
                    ?>
                    <option value="<?php echo esc_attr($category->term_id); ?>" data-lang="<?php echo esc_attr($term_lang); ?>" <?php selected($current_category, $category->term_id); ?>>
                        <?php echo esc_html($category->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <select name="status">
                <option value="">
                    <?php esc_html_e('All Statuses', 'roidnet-ai-content-generator'); ?>
                </option>
                <option value="pending" <?php selected($current_status, 'pending'); ?>>
                    <?php esc_html_e('Pending', 'roidnet-ai-content-generator'); ?>
                </option>
                <option value="processing" <?php selected($current_status, 'processing'); ?>>
                    <?php esc_html_e('Processing', 'roidnet-ai-content-generator'); ?>
                </option>
                <option value="completed" <?php selected($current_status, 'completed'); ?>>
                    <?php esc_html_e('Completed', 'roidnet-ai-content-generator'); ?>
                </option>
                <option value="failed" <?php selected($current_status, 'failed'); ?>>
                    <?php esc_html_e('Failed', 'roidnet-ai-content-generator'); ?>
                </option>
            </select>

            <select name="language">
                <option value="">
                    <?php esc_html_e('All Languages', 'roidnet-ai-content-generator'); ?>
                </option>
                <?php foreach ($active_languages as $code => $name): ?>
                    <option value="<?php echo esc_attr($code); ?>" <?php selected($current_language, $code); ?>>
                        <?php echo esc_html($name); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="button">
                <?php esc_html_e('Filter', 'roidnet-ai-content-generator'); ?>
            </button>
        </form>
    </div>

    <!-- Keywords Table -->
    <form id="roidaico-keywords-table-form">
        <!-- Top Bulk Actions -->
        <div class="tablenav top" style="margin: 10px 0 5px 0;">
            <div class="alignleft actions bulkactions">
                <select class="bulk-action-selector">
                    <option value="">
                        <?php esc_html_e('Bulk Actions', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="delete">
                        <?php esc_html_e('Delete', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="generate">
                        <?php esc_html_e('Generate Content', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="translate">
                        <?php esc_html_e('Translate with AI', 'roidnet-ai-content-generator'); ?>
                    </option>
                </select>
                <button type="button" class="button do-bulk-action">
                    <?php esc_html_e('Apply', 'roidnet-ai-content-generator'); ?>
                </button>
            </div>
            <br class="clear" />
        </div>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th class="check-column">
                        <input type="checkbox" id="select-all-keywords">
                    </th>
                    <th>
                        <?php esc_html_e('Keyword', 'roidnet-ai-content-generator'); ?>
                    </th>
                    <th>
                        <?php esc_html_e('Languages', 'roidnet-ai-content-generator'); ?>
                    </th>
                    <th>
                        <?php esc_html_e('Category', 'roidnet-ai-content-generator'); ?>
                    </th>
                    <th>
                        <?php esc_html_e('Status', 'roidnet-ai-content-generator'); ?>
                    </th>
                    <th>
                        <?php esc_html_e('Created', 'roidnet-ai-content-generator'); ?>
                    </th>
                    <th>
                        <?php esc_html_e('Actions', 'roidnet-ai-content-generator'); ?>
                    </th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($keywords_data['items'])): ?>
                    <?php foreach ($keywords_data['items'] as $keyword): ?>
                        <tr data-id="<?php echo esc_attr($keyword->id); ?>" data-category-id="<?php echo esc_attr($keyword->category_id); ?>">
                            <td class="check-column">
                                <input type="checkbox" name="keyword_ids[]" value="<?php echo esc_attr($keyword->id); ?>" data-lang="<?php echo esc_attr($keyword->language); ?>">
                            </td>
                            <td>
                                <strong>
                                    <?php echo esc_html($keyword->keyword); ?>
                                </strong>
                                <?php if (!empty($keyword->translation_of)): ?>
                                    <?php 
                                    $parent_kw = $keyword_manager->get_keyword($keyword->translation_of);
                                    if ($parent_kw):
                                    ?>
                                        <div class="roidaico-translation-relation" style="font-size: 11px; color: #718096; margin-top: 4px;">
                                            <span class="dashicons dashicons-translation" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom;"></span>
                                            <?php printf(esc_html__('Translation of "%s"', 'roidnet-ai-content-generator'), esc_html($parent_kw->keyword)); ?>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (empty($keyword->translation_of)): ?>
                                    <!-- Parent keyword: show language matrix -->
                                    <div class="roidaico-language-matrix" style="display: flex; gap: 6px; align-items: center;">
                                        <!-- Original Language Badge -->
                                        <span class="roidaico-lang-badge original" style="font-size: 10px; background: #2271b1; color: #fff; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold;" title="<?php esc_attr_e('Original Language', 'roidnet-ai-content-generator'); ?>">
                                            <?php echo esc_html($keyword->language); ?>
                                        </span>
                                        
                                        <!-- Divider -->
                                        <span style="color: #ccd0d4;">|</span>

                                        <!-- Translation Sibling Badges -->
                                        <?php 
                                        foreach ($active_languages as $code => $name): 
                                            if ($code === $keyword->language) continue;
                                            
                                            // Check if translation exists in our pre-fetched map
                                            $existing_trans = null;
                                            if (isset($translations_map[$keyword->id])) {
                                                foreach ($translations_map[$keyword->id] as $tr) {
                                                    if ($tr->language === $code) {
                                                        $existing_trans = $tr;
                                                        break;
                                                    }
                                                }
                                            }
                                            
                                            if ($existing_trans):
                                                // Status styling
                                                $bg = '#fff3cd'; $color = '#856404'; $title = __('Pending', 'roidnet-ai-content-generator');
                                                if ($existing_trans->status === 'completed') {
                                                    $bg = '#edfaef'; $color = '#1e7e34'; $title = __('Completed', 'roidnet-ai-content-generator');
                                                } elseif ($existing_trans->status === 'processing') {
                                                    $bg = '#e7f3ff'; $color = '#0056b3'; $title = __('Processing', 'roidnet-ai-content-generator');
                                                } elseif ($existing_trans->status === 'failed') {
                                                    $bg = '#fbeaea'; $color = '#c00'; $title = __('Failed', 'roidnet-ai-content-generator');
                                                }
                                                ?>
                                                <span class="roidaico-lang-badge status-<?php echo esc_attr($existing_trans->status); ?>" 
                                                      style="font-size: 10px; background: <?php echo $bg; ?>; color: <?php echo $color; ?>; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: 500;" 
                                                      title="<?php echo esc_attr(sprintf(__('Translation (%s): %s', 'roidnet-ai-content-generator'), $name, $title)); ?>">
                                                    <?php echo esc_html($code); ?>
                                                </span>
                                            <?php else: ?>
                                                <!-- Translation missing: show add translation link -->
                                                <a href="#" class="roidaico-add-translation-badge" 
                                                   data-id="<?php echo esc_attr($keyword->id); ?>" 
                                                   data-keyword="<?php echo esc_attr($keyword->keyword); ?>"
                                                   data-lang="<?php echo esc_attr($code); ?>"
                                                   style="font-size: 10px; background: #f0f0f1; color: #646970; border: 1px dashed #c3c4c7; padding: 1px 5px; border-radius: 4px; text-transform: uppercase; text-decoration: none; display: inline-flex; align-items: center; gap: 2px;" 
                                                   title="<?php echo esc_attr(sprintf(__('Add translation in %s', 'roidnet-ai-content-generator'), $name)); ?>">
                                                    <span class="dashicons dashicons-plus" style="font-size: 10px; width: 10px; height: 10px; line-height: 10px;"></span>
                                                    <?php echo esc_html($code); ?>
                                                </a>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <!-- Child keyword: point to parent -->
                                    <div class="roidaico-child-lang-info" style="display: inline-flex; align-items: center; gap: 4px; font-size: 11px; color: #646970;">
                                        <span class="dashicons dashicons-arrow-right-alt" style="font-size: 14px; width: 14px; height: 14px; line-height: 14px; color: #a7aaad;"></span>
                                        <span class="roidaico-lang-badge child" style="font-size: 10px; background: #f0f0f1; color: #50575e; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: 500;">
                                            <?php echo esc_html($keyword->language); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $cat = get_category($keyword->category_id);
                                echo esc_html(($cat && !is_wp_error($cat)) ? $cat->name : __('Uncategorized', 'roidnet-ai-content-generator'));
                                ?>
                            </td>
                            <td>
                                <?php if ($keyword->status === 'failed'): ?>
                                    <span class="roidaico-status-badge roidaico-status-failed roidaico-has-error-tooltip" data-error="<?php echo esc_attr($keyword->error_message ? $keyword->error_message : __('Unknown error', 'roidnet-ai-content-generator')); ?>">
                                        <?php echo esc_html(ucfirst($keyword->status)); ?>
                                        <span class="dashicons dashicons-info" style="font-size: 14px; width: 14px; height: 14px; margin-left: 2px; vertical-align: text-bottom;"></span>
                                    </span>
                                <?php else: ?>
                                    <span class="roidaico-status-badge roidaico-status-<?php echo esc_attr($keyword->status); ?>">
                                        <?php echo esc_html(ucfirst($keyword->status)); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($keyword->created_at))); ?>
                            </td>
                            <td>
                                <?php if ($keyword->status === 'pending'): ?>
                                    <button type="button" class="button button-small roidaico-generate-content-btn"
                                        data-id="<?php echo esc_attr($keyword->id); ?>">
                                        <?php esc_html_e('Generate', 'roidnet-ai-content-generator'); ?>
                                    </button>
                                <?php endif; ?>
                                <?php if ($keyword->post_id): ?>
                                    <a href="<?php echo esc_url(get_edit_post_link($keyword->post_id)); ?>"
                                        class="button button-small">
                                        <?php esc_html_e('View Post', 'roidnet-ai-content-generator'); ?>
                                    </a>
                                <?php endif; ?>
                                <?php if (empty($keyword->translation_of)): ?>
                                    <button type="button" class="button button-small roidaico-translate-keyword-btn"
                                        data-id="<?php echo esc_attr($keyword->id); ?>"
                                        data-keyword="<?php echo esc_attr($keyword->keyword); ?>"
                                        data-lang="<?php echo esc_attr($keyword->language); ?>">
                                        <span class="dashicons dashicons-translation" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom; margin-right: 2px;"></span>
                                        <?php esc_html_e('Translate', 'roidnet-ai-content-generator'); ?>
                                    </button>
                                <?php endif; ?>
                                <button type="button" class="button button-small roidaico-delete-keyword-btn"
                                    data-id="<?php echo esc_attr($keyword->id); ?>">
                                    <?php esc_html_e('Delete', 'roidnet-ai-content-generator'); ?>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="roidaico-empty-state">
                            <?php esc_html_e('No keywords in the queue. Add keywords to get started!', 'roidnet-ai-content-generator'); ?>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Bulk Actions -->
        <div class="tablenav bottom">
            <div class="alignleft actions bulkactions">
                <select class="bulk-action-selector">
                    <option value="">
                        <?php esc_html_e('Bulk Actions', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="delete">
                        <?php esc_html_e('Delete', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="generate">
                        <?php esc_html_e('Generate Content', 'roidnet-ai-content-generator'); ?>
                    </option>
                    <option value="translate">
                        <?php esc_html_e('Translate with AI', 'roidnet-ai-content-generator'); ?>
                    </option>
                </select>
                <button type="button" class="button do-bulk-action">
                    <?php esc_html_e('Apply', 'roidnet-ai-content-generator'); ?>
                </button>
            </div>

            <!-- Pagination -->
            <?php if ($keywords_data['total_pages'] > 1): ?>
                <div class="tablenav-pages">
                    <span class="displaying-num">
                        <?php printf(esc_html__('%d items', 'roidnet-ai-content-generator'), $keywords_data['total']); ?>
                    </span>
                    <span class="pagination-links">
                        <?php if ($current_page > 1): ?>
                            <a class="prev-page button"
                                href="<?php echo esc_url(add_query_arg('paged', $current_page - 1)); ?>">‹</a>
                        <?php endif; ?>
                        <span class="paging-input">
                            <?php echo esc_html($current_page); ?> /
                            <?php echo esc_html($keywords_data['total_pages']); ?>
                        </span>
                        <?php if ($current_page < $keywords_data['total_pages']): ?>
                            <a class="next-page button"
                                href="<?php echo esc_url(add_query_arg('paged', $current_page + 1)); ?>">›</a>
                        <?php endif; ?>
                    </span>
                </div>
            <?php endif; ?>
        </div>
    </form>

    <!-- Translate Keyword Modal -->
    <div id="roidaico-translate-keyword-modal" class="roidaico-modal" style="display: none;">
        <div class="roidaico-modal-content">
            <span class="roidaico-modal-close">&times;</span>
            <h2>
                <?php esc_html_e('Translate Keyword', 'roidnet-ai-content-generator'); ?>
            </h2>
            <form id="roidaico-translate-keyword-form">
                <input type="hidden" id="trans-source-id" name="source_id" value="">
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e('Original Keyword', 'roidnet-ai-content-generator'); ?></th>
                        <td><strong id="trans-original-text"></strong></td>
                    </tr>
                    <tr>
                        <th><label for="trans-target-lang">
                                <?php esc_html_e('Target Language', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="trans-target-lang" name="target_lang">
                                <?php foreach ($active_languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>">
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="trans-method">
                                <?php esc_html_e('Translation Method', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="trans-method" name="method">
                                <option value="ai"><?php esc_html_e('Translate with AI (One-click)', 'roidnet-ai-content-generator'); ?></option>
                                <option value="manual"><?php esc_html_e('Enter Translation Manually', 'roidnet-ai-content-generator'); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr id="trans-manual-row" style="display: none;">
                        <th><label for="trans-manual-text">
                                <?php esc_html_e('Translated Keyword', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <input type="text" id="trans-manual-text" name="manual_text" class="regular-text" placeholder="<?php esc_attr_e('e.g., دليل إسطنبول', 'roidnet-ai-content-generator'); ?>">
                            <p class="description">
                                <?php esc_html_e('Enter the SEO keyword translated to your target language.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary" id="roidaico-submit-translate-btn">
                        <?php esc_html_e('Create Translation', 'roidnet-ai-content-generator'); ?>
                    </button>
                </p>
            </form>
        </div>
    </div>
    <!-- Bulk Translate Modal -->
    <div id="roidaico-bulk-translate-modal" class="roidaico-modal" style="display: none;">
        <div class="roidaico-modal-content">
            <span class="roidaico-modal-close">&times;</span>
            <h2>
                <?php esc_html_e('Bulk Translate Keywords', 'roidnet-ai-content-generator'); ?>
            </h2>
            <form id="roidaico-bulk-translate-form">
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e('Selected Keywords', 'roidnet-ai-content-generator'); ?></th>
                        <td><strong id="bulk-trans-count">0</strong></td>
                    </tr>
                    <tr>
                        <th><label for="bulk-trans-target-lang">
                                <?php esc_html_e('Target Language', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="bulk-trans-target-lang" name="target_lang">
                                <option value="all"><?php esc_html_e('All Active Languages (Recommended)', 'roidnet-ai-content-generator'); ?></option>
                                <?php foreach ($active_languages as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>">
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php esc_html_e('Translate selected keywords to a specific language or all active languages. Sibling translations are automatically skipped if they already exist.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary" id="roidaico-submit-bulk-translate-btn">
                        <?php esc_html_e('Start Bulk Translation', 'roidnet-ai-content-generator'); ?>
                    </button>
                </p>
            </form>
        </div>
    </div>
</div>