<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Get API Key status
$api_key = rank_get_api_key(); // Use renamed function
$is_api_key_set = ! empty( $api_key );

// Get health check categories
$health_check_categories = rank_get_health_check_categories(); // Use renamed function

// Determine the current tab
$current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'bulk_fix'; // Default to 'bulk_fix'

// We'll let WordPress handle the wrap div and notices
// But we need to output our own H1 tag with the SVG icon

?>
<div class="wrap" data-api-key-set="<?php echo $is_api_key_set ? 'yes' : 'no'; ?>">
    <h1 style="display:none;" class="wp-heading-inline"><?php echo get_admin_page_title(); ?></h1>
    <?php
    // This is where WordPress will automatically insert notices ABOVE our H1
    // because the notices hooks run before our page content
    ?>
    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 1em;">
        <svg fill="currentColor" class="overflow-visible" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 16 16" style="width: 1.5em; height: 2.5em; flex-shrink: 0;padding-top:2px;"><g transform="translate(-4)"><g transform="translate(4)"><path d="M8,0a8,8,0,1,0,8,8A8.009,8.009,0,0,0,8,0ZM7.726,15.053a6.206,6.206,0,1,1,6.206-6.206A6.206,6.206,0,0,1,7.726,15.053Z"></path><circle cx="3.414" cy="3.414" r="3.414" transform="translate(5.533 5.084)"></circle></g></g></svg>
        <h1>RANK AI by Morningscore</h1>
        <span style="font-size: 12px; color: #666; align-self: center;">v1.0.6</span>
    </div>

<?php // --- Tab Navigation --- ?>
<h2 class="nav-tab-wrapper">
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=bulk_fix" class="nav-tab <?php echo $current_tab === 'bulk_fix' ? 'nav-tab-active' : ''; ?>">
    ❤️ Health
    </a>
            <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=page_booster" class="nav-tab <?php echo $current_tab === 'page_booster' ? 'nav-tab-active' : ''; ?>">
    🚀 Page Booster
    </a>
        <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=rank_writer" class="nav-tab <?php echo $current_tab === 'rank_writer' ? 'nav-tab-active' : ''; ?>">
    ✍️ Rank Writer
    </a>
     <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=api_config" class="nav-tab <?php echo $current_tab === 'api_config' ? 'nav-tab-active' : ''; ?>">
        🔑 API key
    </a>
    <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=data_management" class="nav-tab <?php echo $current_tab === 'data_management' ? 'nav-tab-active' : ''; ?>">
    💾 Data
    </a>
    <div class="nav-tab-spinner"></div>
    <div class="rank-experimental-label" data-tooltip="Expect fixes to work in ≈90% of cases. This is normal for something as complex as WordPress. Nothing breaks if it does not work. Good luck, captain! 🧑‍🚀👍️">90% success</div>
</h2>
<?php // --- End Tab Navigation --- ?>

<div class="tab-content">
    <div class="tab-content-loader"></div>

        <?php // --- Bulk Fix Tab Content --- ?>
        <?php if ( $current_tab === 'bulk_fix' ) : ?>
            <div class="rank-section rank-booster-section">

                <!-- Sub-tab navigation -->
                <div class="rank-booster-subtabs">
                    <button class="rank-booster-subtab active" data-subtab="health-fix">❤️ Problems</button>
                    <button class="rank-booster-subtab" data-subtab="fixes-view">✅ Fixes</button>
                </div>

                <!-- ============ Fix Health Sub-tab ============ -->
                <div id="rank-booster-health-fix" class="rank-booster-subtab-content active">
                    <?php if ($is_api_key_set): ?>

                    <div id="rank-global-credit-status" style="margin-bottom: 15px; font-weight: bold;"></div>

                    <?php
                    // Check if any multilingual plugins are active
                    if (!function_exists('is_plugin_active')) {
                        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
                    }

                    $multilingual_plugins_active = false;
                    $active_plugins = get_option('active_plugins');

                    // Check for WPML
                    if (in_array('sitepress-multilingual-cms/sitepress.php', $active_plugins) ||
                        defined('ICL_SITEPRESS_VERSION') ||
                        defined('WPML_PLUGIN_PATH') ||
                        class_exists('SitePress') ||
                        is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
                        $multilingual_plugins_active = true;
                    }

                    // Check for Polylang
                    if (in_array('polylang/polylang.php', $active_plugins) ||
                        in_array('polylang-pro/polylang.php', $active_plugins) ||
                        function_exists('pll_current_language') ||
                        is_plugin_active('polylang/polylang.php') ||
                        is_plugin_active('polylang-pro/polylang.php')) {
                        $multilingual_plugins_active = true;
                    }

                    // Check for TranslatePress
                    if (in_array('translatepress-multilingual/index.php', $active_plugins) ||
                        class_exists('TRP_Translate_Press') ||
                        is_plugin_active('translatepress-multilingual/index.php')) {
                        $multilingual_plugins_active = true;
                    }

                    // Check for Weglot
                    if (in_array('weglot/weglot.php', $active_plugins) ||
                        function_exists('weglot_get_current_language') ||
                        is_plugin_active('weglot/weglot.php')) {
                        $multilingual_plugins_active = true;
                    }

                    // Display multilingual notice - initially hidden, will be shown only in overview by JavaScript
                    if ($multilingual_plugins_active) {
                        echo '<div id="rank-multilingual-notice" style="background-color: #f0f8ff !important; padding: 15px !important; border-left: 4px solid #007cba !important; margin: 15px 0 !important; display: none !important; visibility: visible !important; opacity: 1 !important; position: relative !important; z-index: 9999 !important; font-size: 14px !important; line-height: 1.4 !important;">';
                        echo '<p style="margin: 0 !important; padding: 0 !important; color: #333 !important;">🌍️ <strong>Language plugin detected and supported </strong> <a href="https://morningscore.io/automatic-seo-wordpress-plugin-rank-ai/#lwptoc13" target="_blank">See guide</a></p>';
                        echo '</div>';
                    }
                    ?>

                    <div id="rank-health-issues-container" style="display:none;">
                        <div style="display: flex; align-items: center; justify-content: space-between;">
                            <h2>Fix health problems automatically</h2>
                            <div id="rank-health-issues-loading">
                                <div class="spinner is-active" style="float:none; margin: 0;"></div>
                            </div>
                        </div>
                        <p class="description">Get all pages on your website fixed automatically for each health problem found in your Morningscore account.</p>
                    </div>

                    <div id="rank-processing-area" style="display:none;">
                        <input type="hidden" id="rank-batch-id" value="">
                        <input type="hidden" id="rank-selected-issue-type" value="">

                        <div id="rank-status-container">
                            <p id="rank-status-message">Ready to process...</p>
                            <div id="rank-progress-bar-container" class="rank-progress-container" style="display:none;">
                                <div id="rank-progress-bar" class="rank-progress-bar" style="width: 0%;">0%</div>
                            </div>
                            <h3 id="rank-counts"></h3>
                        </div>

                        <div id="rank-approval-area" style="margin-bottom: 15px;">
                            <?php // Approval items will be loaded here by JavaScript ?>
                        </div>

                        <div class="rank-buttons-container">
                            <button id="rank-start-button" class="button button-primary" style="display:none;">Manual</button>
                            <button id="rank-auto-process-button" class="button button-secondary" style="display:none; float:right;">Automatic</button>
                        </div>

                        <div class="rank-log-container" style="display:none;">
                            <h3>Processing log<div id="rank-log-spinner" class="spinner" style="float:none; display:none;"></div></h3>
                            <p>All fixes can be changed later in the Fixes tab <span class="rank-edit-icon dashicons dashicons-edit"></span></p>
                            <div id="rank-log-output" class="rank-log"></div>
                        </div>

                        <div class="rank-cancel-container">
                            <button id="rank-cancel-button" class="button">Cancel</button>
                        </div>
                    </div>

                    <?php endif; ?>
                </div>

                <!-- ============ Fixes View Sub-tab ============ -->
                <div id="rank-booster-fixes-view" class="rank-booster-subtab-content" style="display:none;">
                    <h2>View and edit applied Fixes</h2>
                    <p>Click on each to see and edit changes. <b>Fixes can take up to 2 minutes to appear</b></p>

                    <div id="rank-fixes-accordion">
                        <?php foreach ( $health_check_categories as $key => $label ) :
                            // Map the category keys for broken links to match the option names
                            $category_key = $key;
                            if ($key === 'broken_internal_links') {
                                $category_key = 'broken_links_internal';
                            } elseif ($key === 'broken_external_links') {
                                $category_key = 'broken_links_external';
                            }
                        ?>
                            <div class="rank-accordion-item">
                                <button type="button" class="rank-accordion-header" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" style="display: flex; align-items: center; width: 100%; background-color: #f6f7f7; border: 1px solid #ccd0d4; padding: 10px 15px; text-align: left; font-size: 1em; font-weight: 600; cursor: pointer;">
                                    <span style="flex: 1;"><?php echo esc_html( $label ); ?></span>
                                    <span class="rank-accordion-meta">
                                        <span class="rank-accordion-count">✅ (...)</span>
                                        <span class="rank-accordion-toggle dashicons dashicons-arrow-down-alt2" style="margin-left: 10px;"></span>
                                    </span>
                                </button>
                                <div class="rank-accordion-content" style="display: none;">
                                    <div class="rank-accordion-table-container">
                                        <p class="rank-accordion-loading" style="display: none;">Loading... 5-15 seconds</p>
                                        <p class="rank-accordion-no-data" style="display: none;">No fixes found for this category.</p>
                                    </div>
                                    <div class="rank-accordion-pagination"></div>
                                    <div style="text-align: right; margin-top: 10px; padding: 10px 0;">
                                        <?php
                                        $is_broken_links = in_array($key, ['broken_links_internal', 'broken_links_external'], true);
                                        if (!$is_broken_links) :
                                        ?>
                                            <button type="button" class="rank-csv-export-btn button button-small" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" title="Export all fixes in this category to CSV" style="padding: 2px 8px; height: auto; line-height: 1.5; margin-right: 5px;">
                                                <span class="dashicons dashicons-download" style="font-size: 14px; width: 14px; height: 14px; line-height: 1.5;"></span> CSV Export
                                            </button>
                                        <?php endif; ?>
                                        <?php
                                        // Hide "Delete All" for fixes that edit real content and keep a
                                        // backup (headings, image optimizations): a bulk delete would clear
                                        // tracking without restoring the originals. These must be restored
                                        // individually (per row) so each original is put back.
                                        $cat_cfg = function_exists('rank_get_issue_type_config') ? rank_get_issue_type_config($key) : null;
                                        $hide_delete_all = $cat_cfg && ($cat_cfg['handler_type'] ?? '') === 'content_fix';
                                        if (!$hide_delete_all) :
                                        ?>
                                            <button type="button" class="rank-delete-all-btn button button-small" data-category="<?php echo esc_attr( $category_key ); ?>" data-issue-type="<?php echo esc_attr( $key ); ?>" title="Delete all fixes in this category" style="padding: 2px 8px; height: auto; line-height: 1.5;">
                                                <span class="dashicons dashicons-trash" style="font-size: 14px; width: 14px; height: 14px; line-height: 1.5;"></span> Delete All
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

            </div>
        <?php endif; ?>
        <?php // --- End Bulk Fix Tab Content --- ?>


        <?php // --- API Configuration Tab Content --- ?>
        <?php if ( $current_tab === 'api_config' ) : ?>
            <div class="rank-section">
                <h2>🔑 API key</h2>
                <form id="rank-api-key-form" method="post" action="options.php">
                    <?php settings_fields( 'rank_options_group' ); ?>
                    <?php do_settings_sections( 'rank_options_group' ); ?>
                    <table class="form-table">
                        <tr valign="top">
                            <th scope="row">Morningscore API Key</th>
                            <td>
                                <input type="text" id="rank_api_key" name="rank_api_key" value="<?php echo esc_attr( $api_key ); ?>" size="50" />
                                <p class="description">Enter your API key from Morningscore.</p>
                                <?php if ($is_api_key_set): ?>
                                    <p style="color: green;">API Key is set. Now you can <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=bulk_fix">fix health problems</a></p>
                                <?php else: ?>
                                    <p style="color: red;">API Key is not set. Please enter your key.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button('Save API Key'); ?>
                    <div style="margin-top: 100px;">
                        <h3>Find the API key here:</h3>
                        <p>Paid Morningscore subscription needed (<a href="https://morningscore.io/pricing/" target="_blank">all plans offer API</a>) to get API key. All fixes are owned by you forever.</p>
                       <p> <button
  type="button"
  class="button button-secondary"
  onclick="window.open('https://v3.morningscore.io/settings/api','_blank')"
>
  Direct link to API settings page
</button></p>
                        <img src="<?php echo esc_url( plugins_url( 'get-api-key-morningscore.png', __FILE__ ) ); ?>" alt="How to get your Morningscore API Key" style="max-width: 100%; height: auto; border: 1px solid #c1c1c1; width: 70%;">
                    </div>
                </form>
            </div>

            <?php if ( false ) : // ms-chat admin UI is intentionally hidden; retain markup for later re-enablement. ?>
                <?php
                $ms_chat_state_raw   = isset( $_GET['ms_chat_state'] ) ? sanitize_text_field( wp_unslash( $_GET['ms_chat_state'] ) ) : '';
                $ms_chat_state       = ! empty( $ms_chat_state_raw ) ? Rank_Ms_Chat::verify_state( $ms_chat_state_raw ) : null;
                $ms_chat_deep_link   = ! empty( $ms_chat_state_raw );
                $ms_chat_state_valid = ( null !== $ms_chat_state );

                if ( $ms_chat_deep_link && ! $ms_chat_state_valid ) {
                    Rank_Ms_Chat::clear_link_options();
                }

                $ms_chat_connected = Rank_Ms_Chat::is_connected();
                $ms_chat_linked_at = (int) get_option( Rank_Ms_Chat::OPTION_LINKED_AT, 0 );
                ?>
                <div class="rank-section rank-ms-chat-section<?php echo ( $ms_chat_deep_link && $ms_chat_state_valid ) ? ' rank-ms-chat-section--highlight' : ''; ?>" id="rank-ms-chat-connect">
                    <h2>Morningscore Agent (ms-chat)</h2>
                    <hr>

                    <?php if ( $ms_chat_deep_link && $ms_chat_state_valid ) : ?>
                        <p class="rank-ms-chat-notice rank-ms-chat-notice--info">
                            ms-chat is requesting access to this site. Click <strong>Connect ms-chat</strong> to allow your Morningscore chat agent to run health fixes, page booster, and rank writer here.
                        </p>
                    <?php elseif ( $ms_chat_deep_link && ! $ms_chat_state_valid ) : ?>
                        <p class="rank-ms-chat-notice rank-ms-chat-notice--error">
                            This connection link is invalid or has expired. Open ms-chat and try connecting again.
                        </p>
                    <?php endif; ?>

                    <?php if ( $ms_chat_connected ) : ?>
                        <p><strong>Status:</strong> <span class="rank-ms-chat-status-ok">✓ Connected</span></p>
                        <p><strong>Linked:</strong> <?php echo esc_html( $ms_chat_linked_at ? date_i18n( get_option( 'date_format' ), $ms_chat_linked_at ) : '—' ); ?></p>
                        <p>
                            <button type="button" class="button" id="rank-ms-chat-disconnect">Disconnect</button>
                        </p>
                    <?php else : ?>
                        <p><strong>Status:</strong> Not connected</p>
                        <p class="description">
                            Allow your Morningscore chat agent to run health fixes, page booster, and rank writer here.
                        </p>
                        <p>
                            <button
                                type="button"
                                class="button button-primary<?php echo ( $ms_chat_deep_link && $ms_chat_state_valid ) ? ' rank-ms-chat-connect--highlight' : ''; ?>"
                                id="rank-ms-chat-connect-btn"
                                <?php echo ( ! $is_api_key_set || ( $ms_chat_deep_link && ! $ms_chat_state_valid ) ) ? 'disabled' : ''; ?>
                            >
                                Connect ms-chat
                            </button>
                        </p>
                        <?php if ( ! $is_api_key_set ) : ?>
                            <p class="description" style="color: #b32d2e;">Save your API key above before connecting ms-chat.</p>
                        <?php endif; ?>
                    <?php endif; ?>

                    <p class="description rank-ms-chat-privacy">
                        Registers this site's URL and plugin version with Morningscore daily so the chat agent knows what's installed. No content or health data is sent.
                    </p>

                    <div id="rank-ms-chat-message" class="rank-ms-chat-message" aria-live="polite"></div>

                    <?php if ( ! empty( $ms_chat_state_raw ) ) : ?>
                        <input type="hidden" id="rank-ms-chat-state" value="<?php echo esc_attr( $ms_chat_state_raw ); ?>" />
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        <?php // --- End API Configuration Tab Content --- ?>


        <?php // --- Data Management Tab Content --- ?>
        <?php if ( $current_tab === 'data_management' ) : ?>
            <div class="rank-section">
                <h2>System Status</h2>
                <p>This section shows the status of various system components required for RANK AI to function properly.</p>

                <?php
                // Get system status
                $status = Rank_Processor::system_status_check();
                ?>

                <div class="rank-status-card">
                    <h3>Database Tables</h3>
                    <?php if ($status['table_exists']): ?>
                        <p class="rank-status-ok">✅ SEO overrides table exists.</p>
                    <?php else: ?>
                        <p class="rank-status-error">❌ SEO overrides table does not exist.</p>
                        <p>Try deactivating and reactivating the plugin to create the table.</p>
                    <?php endif; ?>
                </div>

                <div class="rank-status-card">
                    <h3>Action Scheduler</h3>
                    <?php if ($status['action_scheduler']['exists']): ?>
                        <p class="rank-status-ok">✅ Action Scheduler is installed.</p>
                        <?php if (!$status['action_scheduler']['hooks_registered']): ?>
                            <p class="rank-status-error">❌ Rank AI hooks are not registered.</p>
                        <?php endif; ?>
                    <?php else: ?>
                        <p class="rank-status-error">❌ Action Scheduler is not installed.</p>
                    <?php endif; ?>
                </div>

                <div class="rank-status-card">
                    <h3>PHP Version</h3>
                    <?php if ($status['php_version']['is_recommended']): ?>
                        <p class="rank-status-ok">✅ You are using PHP <?php echo $status['php_version']['current']; ?></p>
                    <?php else: ?>
                        <p class="rank-status-warning">⚠️ You are currently on PHP <?php echo $status['php_version']['current']; ?>. PHP <?php echo $status['php_version']['recommended']; ?> or higher is recommended.</p>
                    <?php endif; ?>
                </div>

            </div>

            <div class="rank-section" style="margin-top: 30px;">
                <h2>🔍 Debug Logs</h2>
                <p>View recent debug logs from RANK AI processing. Show this to our support if fixes are not being added to the Fixes tab.</p>

                <div style="margin-bottom: 15px;">
                    <button type="button" id="rank-refresh-logs" class="button button-secondary">Refresh Logs</button>
                    <label style="margin-left: 15px;">
                        <input type="checkbox" id="rank-debug-enabled" <?php checked(get_option('rank_debug_enabled', false)); ?>>
                        Enable debug logging
                    </label>
                </div>

                <div id="rank-logs-container" style="background: #f1f1f1; border: 1px solid #ccc; padding: 15px; height: 500px; overflow-y: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap;">
                    <div id="rank-logs-loading" style="text-align: center; padding: 20px;">
                        <div class="spinner is-active"></div>
                        <p>Loading debug logs...</p>
                    </div>
                    <div id="rank-logs-content" style="display: none;"></div>
                    <div id="rank-logs-error" style="display: none; color: #d63638; text-align: center; padding: 20px;">
                        <p>Unable to load debug logs. Make sure WP_DEBUG_LOG is enabled in wp-config.php</p>
                    </div>
                </div>

                <div style="margin-top: 15px; padding: 10px; background: #e7f3ff; border-left: 4px solid #007cba;">
                    <h4>Debug Log Information:</h4>
                    <ul style="margin: 5px 0;">
                        <li><strong>Location:</strong> Custom RANK AI log file (protected from public access)</li>
                        <li><strong>No WordPress debug required:</strong> Works independently of WP_DEBUG_LOG setting</li>
                        <li><strong>Lines shown:</strong> Last 20 RANK AI log entries</li>
                        <li><strong>File size limit:</strong> Automatically managed (max 200KB)</li>
                        <li><strong>Performance:</strong> Zero overhead when disabled - enable only for troubleshooting</li>
                    </ul>
                </div>
            </div>

            <div class="rank-section rank-danger-zone" style="margin-top: 30px;">
                <h2>Danger Zone</h2>
                <p><strong>Warning:</strong> This action will permanently delete all SEO overrides (titles, alt tags, etc.) created by RANK AI from your database. This cannot be undone.</p>
                <button type="button" id="rank-show-delete-confirm" class="button button-secondary">Delete All RANK AI Changes</button>

                <div id="rank-delete-confirmation-area" style="display: none; margin-top: 15px; padding: 15px; border: 1px solid #dc3232; background-color: #fef7f7;">
                    <p>To confirm deletion, please type "<strong>DELETE</strong>" into the box below and click the confirm button.</p>
                    <label for="rank-delete-confirm-input">Confirmation:</label>
                    <input type="text" id="rank-delete-confirm-input" name="rank_delete_confirm_input" size="20" />
                    <button type="button" id="rank-confirm-delete-button" class="button button-danger" disabled>Confirm Deletion</button>
                    <p id="rank-delete-status" style="margin-top: 10px;"></p>
                </div>
            </div>
        <?php endif; ?>
        <?php // --- End Data Management Tab Content --- ?>

        <?php // --- Rank Writer Tab Content --- ?>
        <?php if ( $current_tab === 'rank_writer' ) : ?>
            <div class="rank-section rank-writer-section">
                <h2>Rank Writer Articles</h2>
                <p class="description">Upload articles from Rank Writer to WordPress as draft posts. Articles will appear under Posts → <a href="/wp-admin/edit.php" target="_blank">All Posts</a> (Draft) ready for review and publishing 🚜</p>

                <?php if ($is_api_key_set): ?>
                    <!-- Bulk Action Bar (hidden initially) -->
                    <div id="rank-writer-bulk-actions" class="rank-writer-bulk-actions" style="display: none;">
                        <span id="rank-writer-selected-count">0 selected</span>
                        <button id="rank-writer-upload-btn" class="button button-primary">
                            Upload <span id="rank-writer-upload-count">0</span> articles as drafts
                        </button>
                    </div>

                    <!-- Articles Table -->
                    <div id="rank-writer-table-container">
                        <table class="wp-list-table widefat fixed striped" id="rank-writer-table" style="display: none;">
                            <thead>
                                <tr>
                                    <th class="check-column"><input type="checkbox" id="rank-writer-select-all"></th>
                                    <th>Created</th>
                                    <th>Title</th>
                                    <th class="rank-writer-added-column">Added</th>
                                </tr>
                            </thead>
                            <tbody id="rank-writer-tbody">
                                <!-- Dynamic content loaded by JavaScript -->
                            </tbody>
                        </table>

                        <!-- Empty State -->
                        <div id="rank-writer-empty" class="rank-writer-empty-state" style="display: none;">
                            <p>Create your first article with Rank Writer to have it appear here</p>
                            <a href="https://morningscore.io" target="_blank" class="button button-secondary">Go to Morningscore</a>
                        </div>

                        <!-- Loading State -->
                        <div id="rank-writer-loading" class="rank-writer-loading">
                            <div class="spinner is-active" style="float: none;"></div>
                            <p>Loading articles...</p>
                        </div>

                        <!-- Error State -->
                        <div id="rank-writer-error" class="rank-writer-error-state" style="display: none;">
                            <p id="rank-writer-error-message">Error loading articles.</p>
                            <button id="rank-writer-retry" class="button button-secondary">Retry</button>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <div id="rank-writer-pagination" class="rank-writer-pagination" style="display: none;">
                        <button id="rank-writer-prev" class="button" disabled>&laquo; Previous</button>
                        <span id="rank-writer-page-info">Page 1 of 1</span>
                        <button id="rank-writer-next" class="button" disabled>Next &raquo;</button>
                    </div>
                <?php else: ?>
                    <div class="notice notice-warning">
                        <p>Please <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=api_config">configure your API key</a> first to use Rank Writer.</p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        <?php // --- End Rank Writer Tab Content --- ?>

        <?php // --- Rank Booster Tab Content --- ?>
        <?php if ( $current_tab === 'page_booster' ) : ?>
            <?php if ($is_api_key_set): ?>
            <div class="rank-section rank-booster-section">

                <!-- Sub-tab navigation -->
                <div class="rank-booster-subtabs">
                    <button class="rank-booster-subtab active" data-subtab="optimize">🚀 Optimize</button>
                    <button class="rank-booster-subtab" data-subtab="history">✅️ Pages Optimized</button>
                    <span style="background:#e53935; color:#fff; font-size:11px; font-weight:bold;padding: 5px 12px; border-radius:3px; margin-left:auto;height:16px;">Beta</span>
                </div>

                <!-- ============ Optimize Sub-tab ============ -->
                <div id="rank-booster-optimize" class="rank-booster-subtab-content active">

                    <!-- Active session banner (shown on page load if processing) -->
                    <div id="rb-active-banner" style="display:none;" class="rb-banner rb-banner-info">
                        <span id="rb-active-banner-text"></span>
                        <button id="rb-view-progress" class="button button-small">View progress</button>
                        <button id="rb-banner-close" class="rb-banner-close" title="Dismiss">&times;</button>
                    </div>

                    <!-- Credit status — always rendered so the layout doesn't jump -->
                    <div id="rb-credit-status" style="margin-bottom:15px; font-weight:bold; min-height:1.4em;">&nbsp;</div>

                    <!-- URL Input -->
                    <!-- URL Input area -->
                    <div id="rb-url-input-area" style="margin-top: 40px" >
                        <h3>Enter URLs to optimize</h3>
                        <p class="description">Paste one URL per line, or separate with commas. Max 100. <a target="_blank" href="https://morningscore.io/page-booster-live/">Guide</a></p>
                        <textarea id="rb-urls" rows="6" class="large-text" style="width:60%; max-width:1300px;" placeholder="https://yoursite.com/blog-post-1&#10;https://yoursite.com/blog-post-2"></textarea>
                        <br><br>
                        <button id="rb-prepare-btn" class="button button-primary">Prepare Optimization</button>
                        <span id="rb-prepare-spinner" class="spinner" style="float:none;"></span>
                    </div>

                    <!-- How it works + V8 Engine side by side -->
                    <div id="rb-v8-info" style="display:flex; gap:20px; align-items:flex-start; margin-top:100px; max-width:1300px;">
                        <div style="flex:1;">
                            <h3 style="margin:0 0 14px; font-size:14px; color:#1d2327;">This tool can automatically improve SEO of any page</h3>
                            <div style="display:flex; flex-direction:column; gap:0; border-left:3px solid #563ac9; margin-left:2px;">
                                <div style="display:flex; align-items:flex-start; gap:12px; padding:10px 14px; border-bottom:1px solid #f0f0f0;">
                                    <span style="flex-shrink:0; width:26px; height:26px; background:#563ac9; color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:13px; font-weight:700;">1</span>
                                    <div>
                                        <strong style="font-size:13px;">Insert any URL you want to boost</strong><br>
                                        <span style="font-size:12px; color:#666;">We support pages edited with <span style="color:#563ac9; font-weight:600;">Classic Editor, Gutenberg, Divi</span> and <span style="color:#563ac9; font-weight:600;">Elementor</span>. Other editors: <span style="color:#563ac9; font-weight:600;">limited</span> functionality.</span>
                                    </div>
                                </div>
                                <div style="display:flex; align-items:flex-start; gap:12px; padding:10px 14px; border-bottom:1px solid #f0f0f0;">
                                    <span style="flex-shrink:0; width:26px; height:26px; background:#563ac9; color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:13px; font-weight:700;">2</span>
                                    <div>
                                        <strong style="font-size:13px;">You can choose automatic analysis</strong><br>
                                        <span style="font-size:12px; color:#666;">RANK analyzes your page and checks for <span style="color:#563ac9; font-weight:600;">11 optimizations</span></span>
                                    </div>
                                </div>
                                <div style="display:flex; align-items:flex-start; gap:12px; padding:10px 14px; border-bottom:1px solid #f0f0f0;">
                                    <span style="flex-shrink:0; width:26px; height:26px; background:#563ac9; color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:13px; font-weight:700;">3</span>
                                    <div>
                                        <strong style="font-size:13px;">Or go manual</strong><br>
                                        <span style="font-size:12px; color:#666;">For each page you can decide <span style="color:#563ac9; font-weight:600;">exactly what to fix</span> and which <span style="color:#563ac9; font-weight:600;">keywords</span> to optimize for.</span>
                                    </div>
                                </div>
                                <div style="display:flex; align-items:flex-start; gap:12px; padding:10px 14px; border-bottom:1px solid #f0f0f0;">
                                    <span style="flex-shrink:0; width:26px; height:26px; background:#563ac9; color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:13px; font-weight:700;">4</span>
                                    <div>
                                        <strong style="font-size:13px;">Now RANK works in the background</strong><br>
                                        <span style="font-size:12px; color:#666;">Each page can take up to <span style="color:#563ac9; font-weight:600;">30 minutes</span>. Runs <span style="color:#563ac9; font-weight:600;">fully in the background</span> - you can leave and come back.</span>
                                    </div>
                                </div>
                                <div style="display:flex; align-items:flex-start; gap:12px; padding:10px 14px;">
                                    <span style="flex-shrink:0; width:26px; height:26px; background:#563ac9; color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:13px; font-weight:700;">5</span>
                                    <div>
                                        <strong style="font-size:13px;">Preview, Edit draft or publish directly</strong><br>
                                        <span style="font-size:12px; color:#666;">You get a summary of all changes. <span style="color:#563ac9; font-weight:600;">Preview, edit draft</span> and <span style="color:#563ac9; font-weight:600;">publish</span>. Original content is <span style="color:#563ac9; font-weight:600;">untouched</span> until you publish.</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- V8 Engine info box -->
                        <div style="flex:0 0 400px; display:flex; flex-direction:column; gap:12px;">
                            <div class="rb-v8-box" style="background:linear-gradient(135deg,#1a1a2e 0%,#16213e 100%); color:#e0e0e0; border-radius:10px; padding:20px; border-top:4px solid #26f8d3; position:relative; overflow:hidden;">
                                <div style="position:absolute; top:0; right:0; width:60px; height:100%; opacity:0.07; background:repeating-linear-gradient(90deg,#fff 0px,#fff 8px,transparent 8px,transparent 16px);"></div>
                                <h3 style="margin:0 0 6px; color:#26f8d3; font-size:18px; letter-spacing:1px;">PRO ENGINE</h3>
                                <p style="margin:0 0 10px; font-size:12px; color:#aab; line-height:1.4;">Page Booster runs on the best models and technologies:</p>
                                <ul style="margin:0 0 0 0; padding:0; font-size:12.5px; line-height:1.7; list-style:none;">
                                    <li>⚡ ChatGPT for analysis</li>
                                    <li>🔬 Exa for deep research</li>
                                    <li>✍️ Sonnet + Gemini for content</li>
                                    <li>🎨 Content treated up to 11 times<br><span style="color:#888; font-size:11px; margin-left:20px;">(like 11 layers of paint)</span></li>
                                </ul>
                            </div>
                            <div id="rb-v8-graphic">
                                <img src="<?php echo esc_url( plugins_url( 'v8-tractor.png', __FILE__ ) ); ?>" alt="V8 Engine Tractor" style="max-width:100%; height:auto; border-radius:6px; display:block; padding:10px;">
                            </div>
                        </div>
                    </div>

                    <!-- Results table (hidden until prepare) -->
                    <div id="rb-table-area" style="display:none;">

                        <a href="#" id="rb-back-btn" style="display:block; margin-bottom:10px; font-size:13px; color:#2271b1; text-decoration:none; cursor:pointer; text-align:right;">← Back</a>

                        <!-- SEO plugin notice (shown when no supported plugin is detected) -->
                        <div id="rb-seo-plugin-notice" style="display:none;" class="rb-banner rb-banner-warning"></div>

                        <!-- Optimize button (top) -->
                        <div class="rb-optimize-bar">
                            <button id="rb-optimize-btn-top" class="button button-primary button-hero rb-optimize-btn" disabled>Optimize 0 pages</button>
                            <span class="rb-total-credits" id="rb-total-credits-top">Total: 0 credits</span>
                        </div>

                        <!-- Bulk actions bar -->
                        <div id="rb-bulk-bar" style="display:none;" class="rb-bulk-bar">
                            <span id="rb-selected-count">0 selected</span>
                            <button id="rb-bulk-edit-btn" class="button">Edit</button>
                            <div id="rb-bulk-dropdown" class="rb-dropdown" style="display:none;">
                                <label class="rb-dropdown-item rb-dropdown-separator">
                                    <input type="radio" name="rb-bulk-mode" value="automatic" checked> Automatic (10 credits)
                                </label>
                                <hr>
                                <?php foreach ( Rank_Booster::get_check_categories() as $slug => $label ) : ?>
                                <label class="rb-dropdown-item">
                                    <input type="checkbox" name="rb-bulk-check" value="<?php echo esc_attr($slug); ?>"> <?php echo esc_html($label); ?> (2 credits)
                                </label>
                                <?php endforeach; ?>
                                <hr>
                                <label class="rb-dropdown-item">
                                    <input type="checkbox" name="rb-bulk-update-publish-date"> Update publish date when pushing live
                                </label>
                                <div class="rb-dropdown-actions">
                                    <button id="rb-bulk-apply" class="button button-small button-primary">Apply to selected</button>
                                    <button id="rb-bulk-remove" class="button button-small" style="color:#d63638;">Remove selected</button>
                                </div>
                            </div>
                        </div>

                        <table class="wp-list-table widefat fixed striped" id="rb-table">
                            <thead>
                                <tr>
                                    <th class="check-column"><input type="checkbox" id="rb-select-all"></th>
                                    <th>URL</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="rb-tbody">
                                <!-- Dynamic rows from JS -->
                            </tbody>
                        </table>

                    </div>

                    <!-- Processing area (hidden until optimize starts) -->
                    <div id="rb-processing-area" style="display:none;">
                        <div class="rb-processing-header">
                            <h3>Processing…</h3>
                            <button id="rb-abort-btn" class="button rb-abort-btn">⛔ Abort Processing</button>
                        </div>
                        <div style="display:flex; gap:15px; align-items:flex-start;">

                            <div id="rb-processing-log" class="rb-processing-log" style="flex:1;"></div>
                             <div class="rb-processing-info" style="flex:0 0 260px; background:#f0f6fc; border-left:4px solid #007cba; padding:12px 14px; font-size:13px; line-height:1.5;height:307px;">
                                <strong>☕️ Runs in background</strong>
                                <ul style="padding:0;">
                                    <li>Optimization takes up to 30 minutes per post</li>
                                    <li>Heavy AI models + quality takes time</li>
                                    <li>You can leave and come back</li>
                                </ul>
                                  <strong>🙏 Please review everything</strong><ul style="padding:0;">
                                    <li>Always edit and add your human touch</li>
                                    <li>Good original content gets more visibility!</li>
                                <li>Google detects all AI-only content</li></ul>
                            </div>
                        </div>

                        <!-- Locked table view -->
                        <div id="rb-locked-table-area"></div>
                    </div>

                </div>

                <!-- ============ History Sub-tab ============ -->
                <div id="rank-booster-history" class="rank-booster-subtab-content" style="display:none;">
                    <h3>Pages Optimized</h3>
                    <p class="description" id="rb-history-description">All pages that have been processed by Page Booster.</p>
                    <div id="rb-history-loading" class="spinner is-active" style="float:none;"></div>
                    <table class="wp-list-table widefat fixed striped" id="rb-history-table" style="display:none;">
                        <thead>
                            <tr>
                                <th style="width:29%;">URL</th>
                                <th style="width:14%;">Optimized</th>
                                <th style="width:9%;">Mode</th>
                                <th style="width:9%;">Checks</th>
                                <th style="width:9%;">Status</th>
                                <th style="width:30%; text-align:right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="rb-history-tbody"></tbody>
                    </table>
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <div id="rb-history-pagination" class="rb-pagination" style="display:none;">
                            <button id="rb-history-prev" class="button" disabled>&laquo; Previous</button>
                            <span id="rb-history-page-info">Page 1 of 1</span>
                            <button id="rb-history-next" class="button" disabled>Next &raquo;</button>
                        </div>
                        <div id="rb-history-csv-wrap" style="display:none;">
                            <button id="rb-history-csv-btn" class="button button-small" title="Export all optimized pages to CSV">
                                <span class="dashicons dashicons-download" style="font-size:14px; width:14px; height:14px; line-height:1.5;"></span> CSV Export
                            </button>
                        </div>
                    </div>
                    <div id="rb-history-empty" style="display:none;">
                        <p>No pages have been optimized yet. Go to the Optimize tab to get started.</p>
                    </div>
                </div>


                <!-- Summary modal -->
                <div id="rb-summary-modal" class="rb-modal" style="display:none;">
                    <div class="rb-modal-content rb-modal-large">
                        <div class="rb-modal-header">
                            <h3>Optimization Summary</h3>
                            <button class="rb-modal-close">&times;</button>
                        </div>
                        <div class="rb-modal-body" id="rb-summary-body"></div>
                        <div class="rb-modal-footer">
                            <button class="button rb-modal-close">Close</button>
                        </div>
                    </div>
                </div>

                <!-- Content modal -->
                <div id="rb-content-modal" class="rb-modal" style="display:none;">
                    <div class="rb-modal-content rb-modal-large">
                        <div class="rb-modal-header">
                            <h3>Optimized Content</h3>
                            <button class="rb-modal-close">&times;</button>
                        </div>
                        <div class="rb-modal-body">
                            <div id="rb-content-rendered" class="rb-content-rendered"></div>
                            <textarea id="rb-content-html" readonly style="display:none;"></textarea>
                        </div>
                        <div class="rb-modal-footer">
                            <button class="button button-primary" id="rb-content-copy">Copy HTML</button>
                            <button class="button rb-modal-close">Close</button>
                        </div>
                    </div>
                </div>

                <!-- Row settings modal -->
                <div id="rb-row-settings" class="rb-modal" style="display:none;">
                    <div class="rb-modal-content">
                        <div class="rb-modal-header">
                            <h3>Page Settings</h3>
                            <button class="rb-modal-close">&times;</button>
                        </div>
                        <div class="rb-modal-body">
                            <label><strong>Focus Keywords</strong> <small>(max 3)</small></label>
                            <div id="rb-row-keywords">
                                <div id="rb-row-keywords-list" class="rb-keywords-list"></div>
                                <div style="display:flex;gap:6px;align-items:center;">
                                    <input type="text" id="rb-row-keyword-input" class="regular-text" placeholder="Type keyword and press Enter…" style="flex:1;">
                                    <button type="button" id="rb-row-keyword-add" class="button button-small">Add</button>
                                </div>
                            </div>
                            <div id="rb-row-keywords-api" class="rb-keywords-api" style="display:none;">
                                <small>Loading keywords from Morningscore…</small>
                            </div>

                            <label style="margin-top:12px;display:block;">
                                <input type="checkbox" id="rb-row-update-publish-date"> Update publish date when pushing live
                            </label>

                            <div id="rb-row-custom-prompt-section" style="display:none;">
                                <label style="margin-top:12px;display:block;"><strong>Custom Prompt</strong></label>
                                <div class="rb-custom-prompt-wrap">
                                    <textarea id="rb-row-custom-prompt" rows="3" class="large-text" maxlength="2000" placeholder="Add custom instructions for the AI"></textarea>
                                    <span id="rb-row-custom-prompt-count" class="rb-char-count">0 / 2000</span>
                                </div>
                                <p id="rb-row-custom-prompt-error" class="rb-inline-error" style="display:none;"></p>
                            </div>
                        </div>
                        <div class="rb-modal-footer">
                            <button class="button button-primary rb-modal-close" id="rb-row-settings-save">Done</button>
                        </div>
                    </div>
                </div>

            </div>
            <?php else: ?>
                <div class="notice notice-warning">
                    <p>Please <a href="?page=<?php echo esc_attr( $_REQUEST['page'] ); ?>&tab=api_config">configure your API key</a> first to use Page Booster.</p>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        <?php // --- End Rank Booster Tab Content --- ?>

</div> <?php // end .tab-content ?>

<div style="text-align: left; margin: 20px 0;"> <?php // Added container for centering ?>
    <a href="https://morningscore.io" target="_blank"><img src="<?php echo esc_url( plugins_url( 'Rank.webp', __FILE__ ) ); ?>" alt="RANK AI Logo" width="200"></a>
</div> <!-- Close the wrap div -->

<?php
// Debug information section removed - use Data Management tab for debug logs
?>
