<?php
if (!defined('ABSPATH')) {
    exit;
}
// includes/admin.php

/**
 * Get count of synced content
 */
function wordchat_get_synced_content_count() {
    $all_posts = get_posts([
        'post_type' => ['post', 'page'],
        'post_status' => 'publish',
        'numberposts' => -1
    ]);

    $count = 0;
    foreach ($all_posts as $post) {
        if (get_post_meta($post->ID, 'wordchat_synced', true)) {
            $count++;
        }
    }

    return $count;
}

/**
 * Sync content immediately (not via WP Cron)
 * This is more reliable than wp_schedule_single_event which can be delayed
 */
function wordchat_sync_content_now($post_id) {
    $post = get_post($post_id);
    if (!$post) {
        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', 'Post not found');
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    if (!$site_id || !$api_key) {
        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', 'Missing credentials');
        return;
    }

    $url = get_permalink($post);
    $categories = get_the_category($post_id);
    $category = $categories && !empty($categories) ? $categories[0]->name : null;

    // Build text with optional WooCommerce product enrichment
    $text = strip_tags($post->post_title . ". " . $post->post_content);

    if ($post->post_type === 'product' && function_exists('wc_get_product')) {
        $wc_product = wc_get_product($post_id);
        if ($wc_product) {
            $meta = [];
            if ($wc_product->get_price()) $meta[] = "Price: " . strip_tags(wc_price($wc_product->get_price()));
            if ($wc_product->get_sku()) $meta[] = "SKU: " . $wc_product->get_sku();
            $stock_map = ['instock' => 'In Stock', 'outofstock' => 'Out of Stock', 'onbackorder' => 'On Backorder'];
            $meta[] = "Stock: " . ($stock_map[$wc_product->get_stock_status()] ?? $wc_product->get_stock_status());
            if ($wc_product->get_short_description()) $meta[] = "Summary: " . strip_tags($wc_product->get_short_description());
            if ($meta) $text .= "\n\nProduct Details:\n" . implode("\n", $meta);
        }
    }

    $payload = [
        'site_id' => $site_id,
        'api_key' => $api_key,
        'domain' => get_site_url(),
        'chunks' => [[
            'title' => $post->post_title,
            'text' => $text,
            'url' => $url,
            'category' => $category ? $category : 'Uncategorized',
            'content_type' => $post->post_type
        ]]
    ];

    $response = wp_remote_post(WORDCHAT_API_URL . '/ingest', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($payload),
        'timeout' => 30
    ]);

    if (is_wp_error($response)) {
        $error_msg = $response->get_error_message();
        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', $error_msg);
        error_log("WordChat sync error for post $post_id: $error_msg");
        return;
    }

    $status_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);

    if ($status_code === 200) {
        update_post_meta($post_id, 'wordchat_synced', true);
        update_post_meta($post_id, 'wordchat_synced_at', current_time('mysql'));
        update_post_meta($post_id, 'wordchat_sync_status', 'synced');
        delete_post_meta($post_id, 'wordchat_sync_error'); // Clear any previous errors
    } else {
        // Parse error from response
        $error_data = json_decode($response_body, true);
        $error_msg = isset($error_data['error']) ? $error_data['error'] : "HTTP $status_code";

        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', $error_msg);
        error_log("WordChat sync failed for post $post_id: $error_msg (HTTP $status_code)");
    }
}

function wordchat_admin_menu() {
    add_menu_page(
        'Word.Chat Pro', 'Word.Chat Pro', 'manage_options', 'wordchat-pro', 'wordchat_render_admin_page', 'dashicons-format-chat', 90
    );
}
add_action('admin_menu', 'wordchat_admin_menu');

/**
 * Handle successful upgrade callback from Stripe
 */
function wordchat_handle_upgrade_callback() {
    // Check if we're on the WordChat admin page with upgrade=success parameter
    if (isset($_GET['page']) && $_GET['page'] === 'wordchat-pro' &&
        isset($_GET['upgrade']) && $_GET['upgrade'] === 'success') {

        // Immediately poll backend for updated status
        $site_id = get_option('wordchat_site_id');
        $api_key = get_option('wordchat_api_key');
        $domain = get_site_url();

        if ($site_id && $api_key) {
            $response = wp_remote_post(WORDCHAT_API_URL . '/analytics', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode([
                    'site_id' => $site_id,
                    'api_key' => $api_key,
                    'domain' => $domain
                ]),
                'timeout' => 15
            ]);

            if (!is_wp_error($response)) {
                $data = json_decode(wp_remote_retrieve_body($response), true);

                if (isset($data['is_paid']) && $data['is_paid']) {
                    // Update Pro status
                    update_option('wordchat_is_paid', '1');

                    // Store license key if provided
                    if (isset($data['current_license_key']) && !empty($data['current_license_key'])) {
                        update_option('wordchat_license_key', $data['current_license_key']);
                    }

                    // Show success notice
                    add_action('admin_notices', function() {
                        echo '<div class="notice notice-success is-dismissible">';
                        echo '<p><strong>🎉 Upgrade Successful!</strong> You now have Pro access with unlimited content and messages.</p>';
                        echo '</div>';
                    });
                }
            }
        }

        // Clean up URL (remove upgrade parameter)
        wp_safe_redirect(admin_url('admin.php?page=wordchat-pro'));
        exit;
    }
}
add_action('admin_init', 'wordchat_handle_upgrade_callback');

// Enqueue admin styles
function wordchat_admin_enqueue_styles($hook) {
    // Only load on our admin pages
    if (strpos($hook, 'wordchat-pro') === false) {
        return;
    }

    wp_enqueue_style(
        'wordchat-admin',
        plugin_dir_url(dirname(__FILE__)) . 'css/admin.css',
        [],
        WORDCHAT_VERSION
    );

    wp_enqueue_script(
        'wordchat-content-writer',
        plugin_dir_url(dirname(__FILE__)) . 'js/content-writer.js',
        ['jquery'],
        WORDCHAT_VERSION,
        true
    );

    // Provide WordChatVars to content-writer.js in admin context
    wp_localize_script('wordchat-content-writer', 'WordChatVars', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wordchat_query_nonce'),
    ]);
}
add_action('admin_enqueue_scripts', 'wordchat_admin_enqueue_styles');

function wordchat_render_admin_page() {
    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    $registration_status = get_option('wordchat_registration_status');

    // Check if registration failed or incomplete
    if (!$site_id || $registration_status === 'failed') {
        wordchat_show_registration_prompt();
        return;
    }

    // Show success banner if recently registered
    if (get_transient('wordchat_show_welcome')) {
        echo '<div class="notice notice-success is-dismissible">';
        echo '<p><strong>' . esc_html__('🎉 Welcome to Word.Chat!', 'wordchat-pro') . '</strong> ';
        echo esc_html__('Your site is successfully connected. Start by syncing some content below.', 'wordchat-pro') . '</p>';
        echo '</div>';
        delete_transient('wordchat_show_welcome');
    }

    $is_paid = get_option('wordchat_is_paid') === '1' ? 'Pro' : 'Free';
    $max_items = $is_paid === 'Pro' ? PHP_INT_MAX : 10;

    $sync_message = '';
    $sync_error = '';
    $settings_message = '';

    // Get active tab from URL or POST
    // Default to 'content-sync' if no content is synced yet (onboarding)
    $synced_content_count = wordchat_get_synced_content_count();
    $default_tab = ($synced_content_count === 0) ? 'content-sync' : 'latest-activity';

    $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : $default_tab;
    if (isset($_POST['wordchat_active_tab'])) {
        $active_tab = sanitize_text_field($_POST['wordchat_active_tab']);
    }

    // Handle widget settings update
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wordchat_settings_nonce'])) {
        // Verify nonce
        if (!wp_verify_nonce($_POST['wordchat_settings_nonce'], 'wordchat_settings_action')) {
            wp_die(__('Security check failed. Please try again.', 'wordchat-pro'));
        }

        // Update widget header text
        if (isset($_POST['wordchat_header_text'])) {
            update_option('wordchat_header_text', sanitize_text_field($_POST['wordchat_header_text']));
        }

        // Update intro message
        if (isset($_POST['wordchat_intro_message'])) {
            update_option('wordchat_intro_message', sanitize_text_field($_POST['wordchat_intro_message']));
        }

        // Update site name for intro
        if (isset($_POST['wordchat_site_name'])) {
            update_option('wordchat_site_name', sanitize_text_field($_POST['wordchat_site_name']));
        }

        // Update navigate to response page setting
        if (isset($_POST['wordchat_navigate_to_response'])) {
            update_option('wordchat_navigate_to_response', '1');
        } else {
            update_option('wordchat_navigate_to_response', '0');
        }

        // Update primary color
        if (isset($_POST['wordchat_primary_color'])) {
            $color = sanitize_hex_color($_POST['wordchat_primary_color']);
            update_option('wordchat_primary_color', $color ? $color : '#1A73E8');
        }

        // Update widget start state
        if (isset($_POST['wordchat_start_open'])) {
            update_option('wordchat_start_open', '1');
        } else {
            update_option('wordchat_start_open', '0');
        }

        // Update widget position
        if (isset($_POST['wordchat_position'])) {
            $position = sanitize_text_field($_POST['wordchat_position']);
            update_option('wordchat_position', in_array($position, ['left', 'right']) ? $position : 'right');
        }

        // Update placeholder text
        if (isset($_POST['wordchat_placeholder'])) {
            update_option('wordchat_placeholder', sanitize_text_field($_POST['wordchat_placeholder']));
        }

        // Update button text
        if (isset($_POST['wordchat_button_text'])) {
            update_option('wordchat_button_text', sanitize_text_field($_POST['wordchat_button_text']));
        }

        // Update excluded pages
        $excluded = isset($_POST['wordchat_excluded_pages']) && is_array($_POST['wordchat_excluded_pages'])
            ? array_map('absint', $_POST['wordchat_excluded_pages'])
            : [];
        update_option('wordchat_excluded_pages', $excluded);

        $settings_message = __('Settings saved successfully.', 'wordchat-pro');
    }

    // Handle sync form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wordchat_sync_ids'])) {
        // Verify nonce
        if (!isset($_POST['wordchat_sync_nonce']) || !wp_verify_nonce($_POST['wordchat_sync_nonce'], 'wordchat_sync_action')) {
            wp_die(__('Security check failed. Please try again.', 'wordchat-pro'));
        }

        $selected_ids = array_map('absint', $_POST['wordchat_sync_ids']);
        $success_count = 0;
        $error_count = 0;

        // Get all currently synced posts
        $all_posts = get_posts(['post_type' => ['post', 'page'], 'post_status' => 'publish', 'numberposts' => -1]);
        $synced_ids = [];
        foreach ($all_posts as $p) {
            if (get_post_meta($p->ID, 'wordchat_synced', true)) {
                $synced_ids[] = $p->ID;
            }
        }

        // Determine which to unsync
        $to_unsync = array_diff($synced_ids, $selected_ids);

        // Unsync deselected items
        foreach ($to_unsync as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;

            $url = get_permalink($post);
            $payload = [
                'site_id' => $site_id,
                'api_key' => $api_key,
                'url' => $url
            ];

            $response = wp_remote_post(WORDCHAT_API_URL . '/unsync', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode($payload),
                'timeout' => 30
            ]);

            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                delete_post_meta($post_id, 'wordchat_synced');
                delete_post_meta($post_id, 'wordchat_synced_at');
            }
        }

        // Sync selected items (immediate sync for better UX)
        foreach ($selected_ids as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;

            // Mark as synced and pending
            update_post_meta($post_id, 'wordchat_synced', true);
            update_post_meta($post_id, 'wordchat_sync_status', 'pending');

            // Sync immediately (don't rely on WP Cron which can be unreliable)
            wordchat_sync_content_now($post_id);
            $success_count++;
        }

        if ($success_count > 0) {
            $sync_message = sprintf(
                __('%d item(s) synced successfully. <a href="%s" target="_blank" rel="noopener">Visit your site to see the chatbot &rarr;</a>', 'wordchat-pro'),
                $success_count,
                esc_url(home_url())
            );
        }
        if ($error_count > 0) {
            $sync_error = sprintf(__('%d item(s) could not be synced.', 'wordchat-pro'), $error_count);
        }
    }

    // Get pages first, then posts (sorted by type)
    $pages = get_posts(['post_type' => 'page', 'post_status' => 'publish', 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC']);
    $post_posts = get_posts(['post_type' => 'post', 'post_status' => 'publish', 'numberposts' => -1, 'orderby' => 'date', 'order' => 'DESC']);

    // Combine: pages first, then posts
    $posts = array_merge($pages, $post_posts);

    // Get current settings with defaults
    $header_text = get_option('wordchat_header_text', 'Ask us anything');
    $site_name = get_option('wordchat_site_name', get_bloginfo('name'));
    $intro_message = get_option('wordchat_intro_message', sprintf('Welcome to %s! Can I help answer any questions?', $site_name));
    $navigate_to_response = get_option('wordchat_navigate_to_response', '0'); // Default: disabled

    // Get new customization settings with defaults
    $primary_color = get_option('wordchat_primary_color', '#1A73E8');
    $start_open = get_option('wordchat_start_open', '0'); // Default: closed
    $position = get_option('wordchat_position', 'right'); // Default: right
    $placeholder = get_option('wordchat_placeholder', 'Ask a question...');
    $button_text = get_option('wordchat_button_text', 'Send');

    ?>
    <div class="wrap wordchat-admin-wrap">
        <h1>
            <?php echo esc_html__('Word.Chat Settings', 'wordchat-pro'); ?>
            <span style="font-size: 13px; font-weight: 400; color: #666; margin-left: 12px; vertical-align: middle;">
                <span style="background: #f0f0f1; padding: 4px 10px; border-radius: 4px; font-weight: 500;">
                    Version <?php echo esc_html(WORDCHAT_VERSION); ?>
                </span>
                <?php if (get_option('wordchat_is_paid') === '1'): ?>
                    <span style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 4px 10px; border-radius: 4px; font-weight: 600; font-size: 11px; text-transform: uppercase;">
                        Pro
                    </span>
                <?php else: ?>
                    <span style="background: #e5e7eb; color: #6b7280; padding: 4px 10px; border-radius: 4px; font-weight: 500; font-size: 11px; text-transform: uppercase;">
                        Free
                    </span>
                <?php endif; ?>
            </span>
        </h1>
        <p><?php echo esc_html__('Chat with your WordPress content using AI. Visitors can ask questions about your pages and posts.', 'wordchat-pro'); ?></p>

        <?php if ($settings_message): ?>
            <div class="notice notice-success is-dismissible"><p><?php echo esc_html($settings_message); ?></p></div>
        <?php endif; ?>

        <?php if ($sync_message): ?>
            <div class="notice notice-success is-dismissible"><p><?php echo wp_kses($sync_message, ['a' => ['href' => [], 'target' => [], 'rel' => []]]); ?></p></div>
        <?php endif; ?>

        <?php if ($sync_error): ?>
            <div class="notice notice-error is-dismissible"><p><?php echo esc_html($sync_error); ?></p></div>
        <?php endif; ?>

        <!-- Tab Navigation -->
        <div class="wordchat-tabs">
            <button class="wordchat-tab <?php echo $active_tab === 'latest-activity' ? 'active' : ''; ?>" data-tab="latest-activity"><?php echo esc_html__('Latest Activity', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'content-sync' ? 'active' : ''; ?>" data-tab="content-sync"><?php echo esc_html__('Content Sync', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'content-writer' ? 'active' : ''; ?>" data-tab="content-writer">
                <?php echo esc_html__('✨ AI Content Writer', 'wordchat-pro'); ?>
                <span style="background: #3b82f6; color: white; font-size: 10px; padding: 2px 6px; border-radius: 10px; margin-left: 4px;">NEW</span>
            </button>
            <button class="wordchat-tab <?php echo $active_tab === 'widget-customization' ? 'active' : ''; ?>" data-tab="widget-customization"><?php echo esc_html__('Chat Widget Customization', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'unanswered' ? 'active' : ''; ?>" data-tab="unanswered"><?php echo esc_html__('Unanswered Questions', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'knowledge-base' ? 'active' : ''; ?>" data-tab="knowledge-base"><?php echo esc_html__('Knowledge Base', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'license' ? 'active' : ''; ?>" data-tab="license">
                <?php
                echo esc_html__('License', 'wordchat-pro');
                if (get_option('wordchat_license_key') && get_option('wordchat_license_status') === 'active') {
                    echo ' <span style="color: #46b450;">✓</span>';
                }
                ?>
            </button>
            <button class="wordchat-tab <?php echo $active_tab === 'account' ? 'active' : ''; ?>" data-tab="account"><?php echo esc_html__('Account', 'wordchat-pro'); ?></button>
            <button class="wordchat-tab <?php echo $active_tab === 'feedback' ? 'active' : ''; ?>" data-tab="feedback"><?php echo esc_html__('Feedback', 'wordchat-pro'); ?></button>
        </div>

        <!-- Tab: Latest Activity (First) -->
        <div id="tab-latest-activity" class="wordchat-tab-content <?php echo $active_tab === 'latest-activity' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                    <h2 style="margin: 0;"><?php echo esc_html__('Activity Overview', 'wordchat-pro'); ?></h2>
                    <button id="wordchat-refresh-analytics" class="button button-secondary" style="display: flex; align-items: center; gap: 6px;" onclick="wordchatLoadAnalytics()" title="<?php echo esc_attr__('Refresh analytics data', 'wordchat-pro'); ?>">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="23 4 23 10 17 10"></polyline>
                            <polyline points="1 20 1 14 7 14"></polyline>
                            <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
                        </svg>
                        <?php echo esc_html__('Refresh', 'wordchat-pro'); ?>
                    </button>
                </div>

                <!-- Loading State -->
                <div id="wordchat-analytics-loading" style="padding: 40px; text-align: center;">
                    <div class="wordchat-spinner-admin"></div>
                    <p style="margin-top: 16px; color: #6B7280;"><?php echo esc_html__('Loading analytics...', 'wordchat-pro'); ?></p>
                </div>

                <!-- Analytics Dashboard -->
                <div id="wordchat-analytics-dashboard" style="display: none;">
                    <!-- Metrics Cards - WordPress Admin Blue Theme -->
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 32px;">
                        <!-- Chats This Month -->
                        <div style="background: linear-gradient(135deg, #2271b1 0%, #135e96 100%); color: white; padding: 20px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);">
                            <div style="font-size: 36px; font-weight: 600; margin-bottom: 8px; line-height: 1;" id="metric-month-chats">—</div>
                            <div style="font-size: 13px; opacity: 0.95; font-weight: 500;"><?php echo esc_html__('Chats This Month', 'wordchat-pro'); ?></div>
                        </div>
                        <!-- Pages Navigated To -->
                        <div style="background: linear-gradient(135deg, #72aee6 0%, #3582c4 100%); color: white; padding: 20px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);">
                            <div style="font-size: 36px; font-weight: 600; margin-bottom: 8px; line-height: 1;" id="metric-navigations">—</div>
                            <div style="font-size: 13px; opacity: 0.95; font-weight: 500;"><?php echo esc_html__('Pages Navigated To', 'wordchat-pro'); ?></div>
                        </div>
                        <!-- Total Chats All-Time -->
                        <div style="background: white; border: 1px solid #c3c4c7; padding: 20px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.04);">
                            <div style="font-size: 36px; font-weight: 600; margin-bottom: 8px; color: #2271b1; line-height: 1;" id="metric-total-chats">—</div>
                            <div style="font-size: 13px; color: #50575e; font-weight: 500;"><?php echo esc_html__('Total Chats All-Time', 'wordchat-pro'); ?></div>
                        </div>
                        <!-- Content Synced -->
                        <div style="background: white; border: 1px solid #c3c4c7; padding: 20px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.04);">
                            <div style="font-size: 36px; font-weight: 600; margin-bottom: 8px; color: #2271b1; line-height: 1;" id="metric-content-synced">—</div>
                            <div style="font-size: 13px; color: #50575e; font-weight: 500;"><?php echo esc_html__('Content Synced', 'wordchat-pro'); ?></div>
                        </div>
                    </div>

                    <!-- Top URLs Section -->
                    <div id="wordchat-top-urls-section" style="margin-bottom: 32px; display: none;">
                        <h3 style="font-size: 18px; font-weight: 600; color: #111827; margin-bottom: 16px;">
                            <?php echo esc_html__('Most Navigated Pages This Month', 'wordchat-pro'); ?>
                        </h3>
                        <div id="wordchat-top-urls" style="background: #F9FAFB; padding: 16px; border-radius: 8px; border: 1px solid #E5E7EB;">
                            <!-- Will be populated by JavaScript -->
                        </div>
                    </div>

                    <!-- Latest Messages Section -->
                    <div>
                        <h3 style="font-size: 18px; font-weight: 600; color: #111827; margin-bottom: 16px;">
                            <?php echo esc_html__('Latest Chat Messages', 'wordchat-pro'); ?>
                        </h3>
                        <div id="wordchat-messages-container">
                            <!-- Will be populated by JavaScript -->
                        </div>
                    </div>
                </div>

                <!-- Error State -->
                <div id="wordchat-analytics-error" style="display: none; padding: 40px; text-align: center;">
                    <p style="color: #DC2626; font-weight: 600;"><?php echo esc_html__('Unable to load analytics', 'wordchat-pro'); ?></p>
                    <p style="color: #6B7280; margin-top: 8px;" id="wordchat-error-message"></p>
                    <button class="button button-primary" onclick="wordchatLoadAnalytics()" style="margin-top: 16px;">
                        <?php echo esc_html__('Retry', 'wordchat-pro'); ?>
                    </button>
                </div>
            </div>
        </div>

        <!-- Tab: Content Sync (Second) -->
        <div id="tab-content-sync" class="wordchat-tab-content <?php echo $active_tab === 'content-sync' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <h2><?php echo esc_html__('Select Content to Sync', 'wordchat-pro'); ?></h2>

                <?php if ($synced_content_count === 0): ?>
                <!-- Onboarding message for new users -->
                <div style="margin-bottom: 24px; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; color: white;">
                    <h3 style="margin: 0 0 12px 0; color: white; font-size: 18px;">
                        <?php echo esc_html__('👋 Welcome to Word.Chat!', 'wordchat-pro'); ?>
                    </h3>
                    <p style="margin: 0 0 16px 0; font-size: 15px; line-height: 1.6;">
                        <?php echo esc_html__('Get started by syncing your content below. Select the posts and pages you want your AI chatbot to learn from, then click "Save & Sync Selected Content".', 'wordchat-pro'); ?>
                    </p>
                    <p style="margin: 0; font-size: 14px; opacity: 0.9;">
                        <strong><?php echo esc_html__('Free Plan:', 'wordchat-pro'); ?></strong>
                        <?php echo esc_html__('10 posts + 5 pages + 10 products | 50 chats/month', 'wordchat-pro'); ?>
                    </p>
                </div>
                <?php endif; ?>

                <p style="margin-bottom: 16px; color: #6B7280;">
                    <?php
                    if ($is_paid === 'Pro') {
                        echo esc_html__('Select the posts and pages you want to make available to the AI chatbot. Check the boxes next to content you want to sync.', 'wordchat-pro');
                    } else {
                        echo esc_html__('Select up to 10 posts and 5 pages for the free plan. Upgrade to Pro for unlimited content.', 'wordchat-pro');
                    }
                    ?>
                </p>
                <form method="post" id="wordchat-sync-form">
                    <?php wp_nonce_field('wordchat_sync_action', 'wordchat_sync_nonce'); ?>
                    <input type="hidden" name="wordchat_active_tab" value="content-sync">

                    <div style="margin-bottom: 16px;">
                        <button type="button" class="button" onclick="wordchatSelectAll()"><?php echo esc_html__('Select All', 'wordchat-pro'); ?></button>
                        <button type="button" class="button" onclick="wordchatDeselectAll()"><?php echo esc_html__('Deselect All', 'wordchat-pro'); ?></button>
                        <span class="wordchat-helper-text" style="margin-left: 16px;">
                            <span id="wordchat-selected-count">0</span> <?php echo esc_html__('items selected', 'wordchat-pro'); ?>
                        </span>
                    </div>

                    <?php if ($is_paid !== 'Pro'): ?>
                    <div id="wordchat-free-limit-warning" style="display: none; margin-bottom: 16px; padding: 12px 16px; background: #FEF3C7; border-left: 4px solid #F59E0B; border-radius: 4px;">
                        <p style="margin: 0; color: #92400E;">
                            <strong><?php echo esc_html__('Free Plan Limit:', 'wordchat-pro'); ?></strong>
                            <?php echo esc_html__('You can sync up to 10 posts and 5 pages on the free plan.', 'wordchat-pro'); ?>
                            <?php
                            $upgrade_url = add_query_arg([
                                'utm_source' => 'plugin',
                                'utm_medium' => 'content_sync_warning',
                                'utm_campaign' => 'upgrade',
                                'site_id' => get_option('wordchat_site_id')
                            ], 'https://www.word.chat/pricing');
                            ?>
                            <a href="<?php echo esc_url($upgrade_url); ?>" target="_blank" style="text-decoration: underline; color: #92400E; font-weight: 600;">
                                <?php echo esc_html__('Upgrade to Pro for unlimited content', 'wordchat-pro'); ?>
                            </a>
                        </p>
                    </div>
                    <?php endif; ?>

                    <table class="widefat striped">
                        <thead><tr>
                            <th style="width: 40px;"></th>
                            <th><?php echo esc_html__('Title', 'wordchat-pro'); ?></th>
                            <th><?php echo esc_html__('Type', 'wordchat-pro'); ?></th>
                            <th><?php echo esc_html__('Status', 'wordchat-pro'); ?></th>
                            <th><?php echo esc_html__('Last Modified', 'wordchat-pro'); ?></th>
                            <th><?php echo esc_html__('Last Synced', 'wordchat-pro'); ?></th>
                            <th style="width: 80px;"><?php echo esc_html__('Actions', 'wordchat-pro'); ?></th>
                        </tr></thead>
                        <tbody>
                        <?php
                        $synced_count = 0;
                        foreach ($posts as $post):
                            $is_synced = get_post_meta($post->ID, 'wordchat_synced', true);
                            $synced_at = get_post_meta($post->ID, 'wordchat_synced_at', true);
                            $sync_status = get_post_meta($post->ID, 'wordchat_sync_status', true);
                            $sync_error = get_post_meta($post->ID, 'wordchat_sync_error', true);
                            $modified_date = get_the_modified_date('Y-m-d H:i', $post);

                            if ($is_synced) $synced_count++;

                            // Determine status display
                            $status_class = 'not-synced';
                            $status_icon = '';
                            $status_text = __('Not Synced', 'wordchat-pro');
                            $status_tooltip = '';

                            if ($sync_status === 'pending') {
                                $status_class = 'needs-resync';
                                $status_icon = '⏳';
                                $status_text = __('Syncing...', 'wordchat-pro');
                            } elseif ($sync_status === 'error') {
                                $status_class = 'error';
                                $status_icon = '⚠️';
                                $status_text = __('Sync Failed', 'wordchat-pro');
                                $status_tooltip = $sync_error ? esc_attr($sync_error) : '';
                            } elseif ($is_synced) {
                                $status_class = 'synced';
                                $status_icon = '✓';
                                $status_text = __('Synced', 'wordchat-pro');
                            }
                        ?>
                            <tr>
                                <td>
                                    <input type="checkbox" class="wordchat-sync-checkbox"
                                           name="wordchat_sync_ids[]"
                                           value="<?php echo absint($post->ID); ?>"
                                           <?php checked($is_synced); ?>
                                           onchange="wordchatUpdateCount()">
                                </td>
                                <td><strong><?php echo esc_html($post->post_title); ?></strong></td>
                                <td>
                                    <span style="text-transform: capitalize; color: #6B7280;">
                                        <?php echo esc_html($post->post_type); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="wordchat-status <?php echo esc_attr($status_class); ?>"
                                          title="<?php echo $status_tooltip; ?>">
                                        <?php echo $status_icon . ' ' . esc_html($status_text); ?>
                                    </span>
                                    <?php if ($sync_error): ?>
                                        <br><small style="color: #DC2626;"><?php echo esc_html($sync_error); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td style="color: #6B7280; font-size: 13px;">
                                    <?php echo esc_html($modified_date); ?>
                                </td>
                                <td style="color: #6B7280; font-size: 13px;">
                                    <?php echo $synced_at ? esc_html($synced_at) : '—'; ?>
                                </td>
                                <td>
                                    <?php if ($sync_status === 'error'): ?>
                                        <button type="button" class="button button-small"
                                                onclick="wordchatRetrySync(<?php echo absint($post->ID); ?>)"
                                                title="<?php echo esc_attr__('Retry sync for this item', 'wordchat-pro'); ?>">
                                            <?php echo esc_html__('Retry', 'wordchat-pro'); ?>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>

                    <p style="margin-top: 24px; display: flex; align-items: center; gap: 16px;">
                        <button type="submit" class="button button-primary">
                            <?php echo esc_html__('Save & Sync Selected Content', 'wordchat-pro'); ?>
                        </button>
                        <span class="wordchat-helper-text">
                            <?php printf(
                                esc_html__('Currently %d of %d items synced', 'wordchat-pro'),
                                $synced_count,
                                count($posts)
                            ); ?>
                        </span>
                    </p>
                </form>
            </div>
        </div>

        <!-- Tab: Widget Customization (Second) -->
        <div id="tab-widget-customization" class="wordchat-tab-content <?php echo $active_tab === 'widget-customization' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <h2><?php echo esc_html__('Widget Customization', 'wordchat-pro'); ?></h2>
                <p style="margin-bottom: 20px; padding: 12px; background: #FFF3CD; border-left: 4px solid #FFC107; color: #856404; font-size: 14px; border-radius: 4px;">
                    <strong><?php echo esc_html__('Note:', 'wordchat-pro'); ?></strong>
                    <?php echo esc_html__('After saving changes, you may need to clear your browser cache or any WordPress caching plugins (WP Super Cache, W3 Total Cache, etc.) to see the updated widget styling.', 'wordchat-pro'); ?>
                </p>
                <form method="post">
                    <?php wp_nonce_field('wordchat_settings_action', 'wordchat_settings_nonce'); ?>
                    <input type="hidden" name="wordchat_active_tab" value="widget-customization">

                    <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="wordchat_header_text"><?php echo esc_html__('Widget Header Text', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="wordchat_header_text" name="wordchat_header_text"
                                   value="<?php echo esc_attr($header_text); ?>"
                                   class="regular-text" />
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('This appears at the top of the chat widget.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_site_name"><?php echo esc_html__('Site Name', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="wordchat_site_name" name="wordchat_site_name"
                                   value="<?php echo esc_attr($site_name); ?>"
                                   class="regular-text" />
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('Used in the intro message. Defaults to your site name.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_intro_message"><?php echo esc_html__('Intro Message', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <textarea id="wordchat_intro_message" name="wordchat_intro_message"
                                      rows="3" class="large-text"><?php echo esc_textarea($intro_message); ?></textarea>
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('The first message visitors see when they open the chat widget.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <?php echo esc_html__('Navigation', 'wordchat-pro'); ?>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" id="wordchat_navigate_to_response" name="wordchat_navigate_to_response"
                                       value="1" <?php checked($navigate_to_response, '1'); ?> />
                                <?php echo esc_html__('Navigate to response page', 'wordchat-pro'); ?>
                            </label>
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('When enabled, users will be automatically redirected to the source page after receiving an answer.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_primary_color"><?php echo esc_html__('Primary Color', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <input type="color" id="wordchat_primary_color" name="wordchat_primary_color"
                                   value="<?php echo esc_attr($primary_color); ?>" />
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('Choose the primary color for the chat widget (headers, buttons, user messages). Default is blue (#1A73E8).', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <?php echo esc_html__('Widget Behavior', 'wordchat-pro'); ?>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" id="wordchat_start_open" name="wordchat_start_open"
                                       value="1" <?php checked($start_open, '1'); ?> />
                                <?php echo esc_html__('Start widget open', 'wordchat-pro'); ?>
                            </label>
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('When enabled, the chat widget will be expanded when the page loads. Default is closed.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_position"><?php echo esc_html__('Widget Position', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <select id="wordchat_position" name="wordchat_position">
                                <option value="right" <?php selected($position, 'right'); ?>><?php echo esc_html__('Right Side', 'wordchat-pro'); ?></option>
                                <option value="left" <?php selected($position, 'left'); ?>><?php echo esc_html__('Left Side', 'wordchat-pro'); ?></option>
                            </select>
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('Choose which side of the screen the chat widget appears on. Default is right.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_placeholder"><?php echo esc_html__('Input Placeholder', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="wordchat_placeholder" name="wordchat_placeholder"
                                   value="<?php echo esc_attr($placeholder); ?>"
                                   class="regular-text" />
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('The placeholder text shown in the message input field.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="wordchat_button_text"><?php echo esc_html__('Send Button Text', 'wordchat-pro'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="wordchat_button_text" name="wordchat_button_text"
                                   value="<?php echo esc_attr($button_text); ?>"
                                   class="regular-text" />
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('The text displayed on the send button.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <?php echo esc_html__('Hide Widget On', 'wordchat-pro'); ?>
                        </th>
                        <td>
                            <?php
                            $excluded_pages = get_option('wordchat_excluded_pages', []);
                            $all_pages_posts = get_posts([
                                'post_type' => ['post', 'page'],
                                'post_status' => 'publish',
                                'numberposts' => -1,
                                'orderby' => 'title',
                                'order' => 'ASC'
                            ]);
                            ?>
                            <div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 8px;">
                                <?php if (empty($all_pages_posts)): ?>
                                    <p style="color: #6B7280; margin: 0;"><?php echo esc_html__('No published content found.', 'wordchat-pro'); ?></p>
                                <?php else: ?>
                                    <?php foreach ($all_pages_posts as $pp): ?>
                                        <label style="display: block; padding: 4px 0; cursor: pointer;">
                                            <input type="checkbox" name="wordchat_excluded_pages[]"
                                                   value="<?php echo absint($pp->ID); ?>"
                                                   <?php checked(in_array($pp->ID, $excluded_pages)); ?> />
                                            <?php echo esc_html($pp->post_title); ?>
                                            <span style="color: #9CA3AF; font-size: 12px;">(<?php echo esc_html($pp->post_type); ?>)</span>
                                        </label>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            <p class="wordchat-helper-text">
                                <?php echo esc_html__('Select pages where the chat widget should NOT appear.', 'wordchat-pro'); ?>
                            </p>
                        </td>
                    </tr>
                </table>

                <p style="margin-top: 24px;">
                    <button type="submit" class="button button-primary">
                        <?php echo esc_html__('Save Settings', 'wordchat-pro'); ?>
                    </button>
                </p>
            </form>

                <!-- Preview Chat Section -->
                <div style="margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px;">
                    <h3><?php echo esc_html__('Preview Chat', 'wordchat-pro'); ?></h3>
                    <p style="color: #6B7280; margin-bottom: 16px;">
                        <?php echo esc_html__('Test how the chatbot looks and works with your current settings. Changes are reflected after saving.', 'wordchat-pro'); ?>
                    </p>
                    <div id="wordchat-preview-container" style="position:relative; height:550px; border:1px dashed #ccc; border-radius:8px; background:#f9fafb; display:none; overflow:hidden;"></div>
                    <p style="margin-top: 12px;">
                        <button type="button" id="wordchat-preview-btn" class="button button-secondary">
                            <?php echo esc_html__('Preview Chat', 'wordchat-pro'); ?>
                        </button>
                        <button type="button" id="wordchat-preview-close-btn" class="button" style="display:none; margin-left: 8px;">
                            <?php echo esc_html__('Close Preview', 'wordchat-pro'); ?>
                        </button>
                    </p>
                </div>
            </div>
        </div>

        <!-- Tab: Unanswered Questions -->
        <div id="tab-unanswered" class="wordchat-tab-content <?php echo $active_tab === 'unanswered' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                    <h2 style="margin: 0;"><?php echo esc_html__('Unanswered Questions', 'wordchat-pro'); ?></h2>
                    <button id="wordchat-refresh-unanswered" class="button button-secondary" onclick="wordchatLoadUnanswered()">
                        <?php echo esc_html__('Refresh', 'wordchat-pro'); ?>
                    </button>
                </div>
                <p style="color: #6B7280; margin-bottom: 20px;">
                    <?php echo esc_html__('Questions visitors asked that had no matching content. Use these to improve your coverage.', 'wordchat-pro'); ?>
                </p>

                <div id="wordchat-unanswered-loading" style="padding: 40px; text-align: center;">
                    <div class="wordchat-spinner-admin"></div>
                    <p style="margin-top: 16px; color: #6B7280;"><?php echo esc_html__('Loading...', 'wordchat-pro'); ?></p>
                </div>

                <div id="wordchat-unanswered-dashboard" style="display: none;">
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 24px;">
                        <div style="background: #FEF2F2; border: 1px solid #FECACA; padding: 16px; border-radius: 6px;">
                            <div style="font-size: 28px; font-weight: 600; color: #DC2626;" id="metric-unanswered">0</div>
                            <div style="font-size: 13px; color: #991B1B;"><?php echo esc_html__('Unanswered', 'wordchat-pro'); ?></div>
                        </div>
                        <div style="background: #EFF6FF; border: 1px solid #BFDBFE; padding: 16px; border-radius: 6px;">
                            <div style="font-size: 28px; font-weight: 600; color: #2563EB;" id="metric-unanswered-total">0</div>
                            <div style="font-size: 13px; color: #1E40AF;"><?php echo esc_html__('Total Chats', 'wordchat-pro'); ?></div>
                        </div>
                        <div style="background: #FFFBEB; border: 1px solid #FDE68A; padding: 16px; border-radius: 6px;">
                            <div style="font-size: 28px; font-weight: 600; color: #D97706;" id="metric-unanswered-rate">0%</div>
                            <div style="font-size: 13px; color: #92400E;"><?php echo esc_html__('Unanswered Rate', 'wordchat-pro'); ?></div>
                        </div>
                    </div>
                    <div id="wordchat-unanswered-table"></div>
                </div>

                <div id="wordchat-unanswered-empty" style="display: none; padding: 40px; text-align: center;">
                    <p style="color: #059669; font-weight: 600; font-size: 16px;">
                        <?php echo esc_html__('No unanswered questions in the last 30 days.', 'wordchat-pro'); ?>
                    </p>
                    <p style="color: #6B7280;"><?php echo esc_html__('Your content coverage is great!', 'wordchat-pro'); ?></p>
                </div>
            </div>
        </div>

        <!-- Tab: Knowledge Base -->
        <div id="tab-knowledge-base" class="wordchat-tab-content <?php echo $active_tab === 'knowledge-base' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <h2><?php echo esc_html__('Knowledge Base', 'wordchat-pro'); ?></h2>
                <p style="color: #6B7280; margin-bottom: 20px;">
                    <?php echo esc_html__('Add custom question-answer pairs. These are given priority when visitors ask matching questions.', 'wordchat-pro'); ?>
                </p>

                <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; margin-bottom: 24px;">
                    <h3 style="margin-top: 0;"><?php echo esc_html__('Add Q&A Pair', 'wordchat-pro'); ?></h3>
                    <div style="margin-bottom: 12px;">
                        <label style="display: block; font-weight: 500; margin-bottom: 4px;"><?php echo esc_html__('Question', 'wordchat-pro'); ?></label>
                        <input type="text" id="wordchat-qa-question" class="large-text" maxlength="500" placeholder="<?php echo esc_attr__('e.g., What are your business hours?', 'wordchat-pro'); ?>" />
                    </div>
                    <div style="margin-bottom: 12px;">
                        <label style="display: block; font-weight: 500; margin-bottom: 4px;"><?php echo esc_html__('Answer', 'wordchat-pro'); ?></label>
                        <textarea id="wordchat-qa-answer" class="large-text" rows="3" maxlength="2000" placeholder="<?php echo esc_attr__('e.g., We are open Monday to Friday, 9am to 5pm EST.', 'wordchat-pro'); ?>"></textarea>
                    </div>
                    <button type="button" id="wordchat-qa-add-btn" class="button button-primary" onclick="wordchatQAAdd()">
                        <?php echo esc_html__('Add Q&A Pair', 'wordchat-pro'); ?>
                    </button>
                    <span id="wordchat-qa-counter" style="margin-left: 12px; color: #6B7280; font-size: 13px;"></span>
                    <div id="wordchat-qa-add-status" style="margin-top: 8px; display: none;"></div>
                </div>

                <div id="wordchat-qa-loading" style="padding: 20px; text-align: center;">
                    <div class="wordchat-spinner-admin"></div>
                </div>

                <div id="wordchat-qa-table-container" style="display: none;"></div>
            </div>
        </div>

        <!-- Tab: License (Pro Features) -->
        <div id="tab-license" class="wordchat-tab-content <?php echo $active_tab === 'license' ? 'active' : ''; ?>">
            <?php wordchat_render_license_tab(); ?>
        </div>

        <!-- Tab: Account (Third) -->
        <div id="tab-account" class="wordchat-tab-content <?php echo $active_tab === 'account' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <!-- Site Description (moved to top) -->
                <h2><?php echo esc_html__('About Your Site', 'wordchat-pro'); ?></h2>
                <p style="margin-bottom: 16px; color: #6B7280;">
                    <?php echo esc_html__('This description helps our AI understand your site and validate if questions are relevant. It\'s automatically generated when you first sync content, but you can customize it below.', 'wordchat-pro'); ?>
                </p>
                <form method="post" id="wordchat-site-description-form">
                    <?php wp_nonce_field('wordchat_site_description_action', 'wordchat_site_description_nonce'); ?>
                    <input type="hidden" name="wordchat_active_tab" value="account">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="wordchat_site_description"><?php echo esc_html__('AI Context', 'wordchat-pro'); ?></label>
                            </th>
                            <td>
                                <?php
                                $default_description = get_bloginfo('name');
                                $tagline = get_bloginfo('description');
                                if ($tagline) {
                                    $default_description .= ' — ' . $tagline;
                                }
                                ?>
                                <textarea id="wordchat_site_description" name="wordchat_site_description"
                                          rows="4" class="large-text"
                                          placeholder="<?php echo esc_attr__('e.g., This site is about sustainable living, eco-friendly products, and green technology.', 'wordchat-pro'); ?>"><?php echo esc_textarea($default_description); ?></textarea>
                                <p class="wordchat-helper-text">
                                    <?php echo esc_html__('A concise 2-3 sentence description of your site\'s content and purpose.', 'wordchat-pro'); ?>
                                </p>
                                <div id="wordchat-site-description-status" style="margin-top: 8px; display: none;"></div>
                            </td>
                        </tr>
                    </table>
                    <p>
                        <button type="submit" class="button button-primary">
                            <?php echo esc_html__('Save Description', 'wordchat-pro'); ?>
                        </button>
                    </p>
                </form>

                <!-- Account Information -->
                <h3 style="margin-top: 32px; margin-bottom: 16px;"><?php echo esc_html__('Account Information', 'wordchat-pro'); ?></h3>
                <table class="form-table">
                    <tr>
                        <th><?php echo esc_html__('Site ID', 'wordchat-pro'); ?></th>
                        <td>
                            <div class="wordchat-credential-field">
                                <input type="text" readonly class="regular-text" value="<?php echo esc_attr($site_id); ?>">
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__('API Key', 'wordchat-pro'); ?></th>
                        <td>
                            <div class="wordchat-credential-field">
                                <input type="text" readonly class="regular-text" value="<?php echo esc_attr($api_key); ?>">
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th><?php echo esc_html__('Plan', 'wordchat-pro'); ?></th>
                        <td>
                            <span class="wordchat-plan-badge <?php echo $is_paid === 'Pro' ? 'pro' : 'free'; ?>">
                                <?php echo esc_html($is_paid); ?>
                            </span>
                        </td>
                    </tr>
                </table>

                <?php if ($is_paid !== 'Pro'): ?>
                    <h3 style="margin-top: 32px; margin-bottom: 16px;"><?php echo esc_html__('Upgrade', 'wordchat-pro'); ?></h3>
                    <p style="margin-top: 24px;">
                        <?php
                        $pricing_url = add_query_arg([
                            'utm_source' => 'plugin',
                            'utm_medium' => 'account_tab',
                            'utm_campaign' => 'upgrade',
                            'site_id' => get_option('wordchat_site_id')
                        ], 'https://www.word.chat/pricing');
                        ?>
                        <a href="<?php echo esc_url($pricing_url); ?>"
                           target="_blank"
                           class="button button-primary">
                            <?php echo esc_html__('Upgrade to Pro →', 'wordchat-pro'); ?>
                        </a>
                        <span class="wordchat-helper-text" style="margin-left: 12px;">
                            <?php echo esc_html__('Unlock unlimited content sync and advanced features', 'wordchat-pro'); ?>
                        </span>
                    </p>
                <?php else: ?>
                    <h3 style="margin-top: 32px; margin-bottom: 16px;"><?php echo esc_html__('Manage Subscription', 'wordchat-pro'); ?></h3>
                    <p style="margin-bottom: 12px; color: #6B7280;">
                        <?php echo esc_html__('View billing details or cancel your Pro subscription.', 'wordchat-pro'); ?>
                    </p>
                    <p style="margin-top: 16px;">
                        <a href="https://www.word.chat/manage-subscription?site_id=<?php echo urlencode($site_id); ?>&domain=<?php echo urlencode(get_site_url()); ?>"
                           target="_blank"
                           class="button button-secondary">
                            <?php echo esc_html__('Manage Your Subscription →', 'wordchat-pro'); ?>
                        </a>
                    </p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tab: Feedback (Fourth) -->
        <div id="tab-feedback" class="wordchat-tab-content <?php echo $active_tab === 'feedback' ? 'active' : ''; ?>">
            <div class="wordchat-card">
                <h2><?php echo esc_html__('Send Us Feedback', 'wordchat-pro'); ?></h2>
                <p style="margin-bottom: 24px; color: #6B7280;">
                    <?php echo esc_html__('We\'d love to hear from you! Share your thoughts, report issues, or suggest new features.', 'wordchat-pro'); ?>
                </p>

                <form method="post" id="wordchat-feedback-form">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="feedback_name"><?php echo esc_html__('Name', 'wordchat-pro'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="feedback_name" name="name"
                                       value="<?php echo esc_attr(wp_get_current_user()->display_name); ?>"
                                       class="regular-text" required />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="feedback_email"><?php echo esc_html__('Email', 'wordchat-pro'); ?></label>
                            </th>
                            <td>
                                <input type="email" id="feedback_email" name="email"
                                       value="<?php echo esc_attr(wp_get_current_user()->user_email); ?>"
                                       class="regular-text" required />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="feedback_message"><?php echo esc_html__('Message', 'wordchat-pro'); ?></label>
                            </th>
                            <td>
                                <textarea id="feedback_message" name="message"
                                          rows="6" class="large-text" required
                                          placeholder="<?php echo esc_attr__('Share your feedback, bug reports, or feature requests...', 'wordchat-pro'); ?>"></textarea>
                                <p class="wordchat-helper-text">
                                    <?php echo esc_html__('Please be as detailed as possible to help us improve Word.Chat.', 'wordchat-pro'); ?>
                                </p>
                                <div id="wordchat-feedback-status" style="margin-top: 8px; display: none;"></div>
                            </td>
                        </tr>
                    </table>

                    <p style="margin-top: 24px;">
                        <button type="submit" class="button button-primary">
                            <?php echo esc_html__('Send Feedback', 'wordchat-pro'); ?>
                        </button>
                    </p>
                </form>
            </div>
        </div>

        <!-- Tab: AI Content Writer (Fifth) -->
        <div id="tab-content-writer" class="wordchat-tab-content <?php echo $active_tab === 'content-writer' ? 'active' : ''; ?>">
            <?php wordchat_render_content_writer_tab(); ?>
        </div>
    </div>

    <script>
    const wordchatMaxItems = <?php echo absint($max_items); ?>;
    const wordchatIsPaid = <?php echo $is_paid === 'Pro' ? 'true' : 'false'; ?>;

    function wordchatSelectAll() {
        document.querySelectorAll('.wordchat-sync-checkbox').forEach(cb => cb.checked = true);
        wordchatUpdateCount();
    }

    function wordchatDeselectAll() {
        document.querySelectorAll('.wordchat-sync-checkbox').forEach(cb => cb.checked = false);
        wordchatUpdateCount();
    }

    function wordchatUpdateCount() {
        const checkboxes = document.querySelectorAll('.wordchat-sync-checkbox:checked');
        const count = checkboxes.length;

        // Count posts and pages separately
        let postCount = 0;
        let pageCount = 0;
        checkboxes.forEach(cb => {
            const row = cb.closest('tr');
            const typeCell = row.querySelector('td:nth-child(3)');
            const type = typeCell ? typeCell.textContent.trim().toLowerCase() : '';
            if (type === 'post') postCount++;
            if (type === 'page') pageCount++;
        });

        document.getElementById('wordchat-selected-count').textContent = count;

        // Show warning if over limit on free plan (10 posts + 5 pages)
        if (!wordchatIsPaid) {
            const warning = document.getElementById('wordchat-free-limit-warning');
            if (warning) {
                if (postCount > 10 || pageCount > 5) {
                    warning.style.display = 'block';
                    const siteId = '<?php echo esc_js(get_option('wordchat_site_id', '')); ?>';
                    const upgradeUrl = 'https://www.word.chat/pricing?utm_source=plugin&utm_medium=content_sync_dynamic&utm_campaign=upgrade&site_id=' + encodeURIComponent(siteId);
                    warning.querySelector('p').innerHTML = '<strong><?php echo esc_js(__('Free Plan Limit:', 'wordchat-pro')); ?></strong> ' +
                        '<?php echo esc_js(__('You can sync up to 10 posts and 5 pages.', 'wordchat-pro')); ?> ' +
                        'Currently: ' + postCount + ' posts, ' + pageCount + ' pages. ' +
                        '<a href="' + upgradeUrl + '" target="_blank" style="text-decoration: underline; color: #92400E; font-weight: 600;">' +
                        '<?php echo esc_js(__('Upgrade to Pro', 'wordchat-pro')); ?></a>';
                } else {
                    warning.style.display = 'none';
                }
            }
        }
    }

    // Prevent form submission if over limit
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('wordchat-sync-form');
        if (form) {
            form.addEventListener('submit', function(e) {
                if (!wordchatIsPaid) {
                    const checkboxes = document.querySelectorAll('.wordchat-sync-checkbox:checked');
                    let postCount = 0;
                    let pageCount = 0;

                    checkboxes.forEach(cb => {
                        const row = cb.closest('tr');
                        const typeCell = row.querySelector('td:nth-child(3)');
                        const type = typeCell ? typeCell.textContent.trim().toLowerCase() : '';
                        if (type === 'post') postCount++;
                        if (type === 'page') pageCount++;
                    });

                    if (postCount > 10 || pageCount > 5) {
                        e.preventDefault();
                        alert('<?php echo esc_js(__('Free plan allows up to 10 posts and 5 pages. You have selected ', 'wordchat-pro')); ?>' +
                              postCount + ' <?php echo esc_js(__('posts and', 'wordchat-pro')); ?> ' + pageCount + ' <?php echo esc_js(__('pages.', 'wordchat-pro')); ?>');
                        return false;
                    }
                }
            });
        }

        // Initialize count
        wordchatUpdateCount();
    });

    function wordchatRetrySync(postId) {
        if (!confirm('<?php echo esc_js(__('Retry syncing this item?', 'wordchat-pro')); ?>')) {
            return;
        }

        const button = event.target;
        button.disabled = true;
        button.textContent = '<?php echo esc_js(__('Retrying...', 'wordchat-pro')); ?>';

        // Create form data
        const formData = new FormData();
        formData.append('action', 'wordchat_retry_sync');
        formData.append('post_id', postId);
        formData.append('nonce', '<?php echo esc_js(wp_create_nonce('wordchat_retry_sync')); ?>');

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert('<?php echo esc_js(__('Sync completed successfully! Page will reload.', 'wordchat-pro')); ?>');
                location.reload();
            } else {
                alert('<?php echo esc_js(__('Sync failed:', 'wordchat-pro')); ?> ' + (data.data || 'Unknown error'));
                button.disabled = false;
                button.textContent = '<?php echo esc_js(__('Retry', 'wordchat-pro')); ?>';
            }
        })
        .catch(err => {
            alert('<?php echo esc_js(__('Retry failed:', 'wordchat-pro')); ?> ' + err);
            button.disabled = false;
            button.textContent = '<?php echo esc_js(__('Retry', 'wordchat-pro')); ?>';
        });
    }

    // Upgrade function removed - now links to word.chat/pricing page

    // Tab switching functionality
    document.addEventListener('DOMContentLoaded', function() {
        const tabs = document.querySelectorAll('.wordchat-tab');
        const tabContents = document.querySelectorAll('.wordchat-tab-content');

        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const targetTab = this.getAttribute('data-tab');

                // Remove active class from all tabs and contents
                tabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(c => c.classList.remove('active'));

                // Add active class to clicked tab and corresponding content
                this.classList.add('active');
                const targetContent = document.getElementById('tab-' + targetTab);
                if (targetContent) {
                    targetContent.classList.add('active');
                }
            });
        });

        // Load analytics on page load
        wordchatLoadAnalytics();
    });

    // Load analytics data
    function wordchatLoadAnalytics() {
        const loadingEl = document.getElementById('wordchat-analytics-loading');
        const dashboardEl = document.getElementById('wordchat-analytics-dashboard');
        const errorEl = document.getElementById('wordchat-analytics-error');
        const refreshBtn = document.getElementById('wordchat-refresh-analytics');

        // Show loading state
        if (loadingEl) loadingEl.style.display = 'block';
        if (dashboardEl) dashboardEl.style.display = 'none';
        if (errorEl) errorEl.style.display = 'none';

        // Disable and spin refresh button
        if (refreshBtn) {
            refreshBtn.disabled = true;
            const svg = refreshBtn.querySelector('svg');
            if (svg) {
                svg.style.animation = 'wordchat-spin-refresh 1s linear infinite';
            }
        }

        fetch("<?php echo esc_url(WORDCHAT_API_URL . '/analytics'); ?>", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                site_id: "<?php echo esc_js($site_id); ?>",
                api_key: "<?php echo esc_js($api_key); ?>",
                domain: "<?php echo esc_js(get_site_url()); ?>"
            })
        })
        .then(res => res.json())
        .then(data => {
            // Hide loading, show dashboard
            if (loadingEl) loadingEl.style.display = 'none';
            if (dashboardEl) dashboardEl.style.display = 'block';

            // Re-enable refresh button
            if (refreshBtn) {
                refreshBtn.disabled = false;
                const svg = refreshBtn.querySelector('svg');
                if (svg) {
                    svg.style.animation = '';
                }
            }

            // Update metrics
            document.getElementById('metric-month-chats').textContent = data.current_month_chats || 0;
            document.getElementById('metric-navigations').textContent = data.current_month_navigations || 0;
            document.getElementById('metric-total-chats').textContent = data.total_chats || 0;
            document.getElementById('metric-content-synced').textContent = data.content_synced || 0;

            // Populate site description in Account tab if available
            const siteDescriptionEl = document.getElementById('wordchat_site_description');
            if (siteDescriptionEl && data.site_description) {
                siteDescriptionEl.value = data.site_description;
            }

            // Show top URLs if available
            if (data.top_navigated_urls && data.top_navigated_urls.length > 0) {
                const topUrlsSection = document.getElementById('wordchat-top-urls-section');
                const topUrlsContainer = document.getElementById('wordchat-top-urls');
                topUrlsSection.style.display = 'block';

                let urlsHTML = '<ul style="margin: 0; padding: 0; list-style: none;">';
                data.top_navigated_urls.forEach((item, index) => {
                    urlsHTML += `
                        <li style="padding: 8px 0; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center;">
                            <span style="color: #1A73E8; font-weight: 500;">${index + 1}. ${escapeHtml(item.url)}</span>
                            <span style="background: #DBEAFE; color: #1E40AF; padding: 4px 12px; border-radius: 12px; font-size: 13px; font-weight: 600;">
                                ${item.count} navigations
                            </span>
                        </li>
                    `;
                });
                urlsHTML += '</ul>';
                topUrlsContainer.innerHTML = urlsHTML;
            }

            // Display messages with free/paid differentiation
            const messagesContainer = document.getElementById('wordchat-messages-container');
            const isPaid = data.is_paid;
            const messages = data.latest_messages || [];

            if (messages.length === 0) {
                messagesContainer.innerHTML = '<p style="color: #6B7280; text-align: center; padding: 40px;"><?php echo esc_js(__('No chat messages yet. Messages will appear here once visitors start using the chat widget.', 'wordchat-pro')); ?></p>';
                return;
            }

            // Free users: show only first 3 with upgrade prompt
            const messagesToShow = isPaid ? messages : messages.slice(0, 3);

            let messagesHTML = '<div style="background: white; border: 1px solid #E5E7EB; border-radius: 8px; overflow: hidden;">';

            messagesToShow.forEach((msg, index) => {
                const date = new Date(msg.created_at);
                const formattedDate = date.toLocaleString('en-US', {
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });

                messagesHTML += `
                    <div style="padding: 16px; border-bottom: 1px solid #F3F4F6; ${index === 0 ? '' : ''}">
                        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">
                            <div style="flex: 1;">
                                <div style="font-weight: 600; color: #111827; margin-bottom: 4px; font-size: 14px;">
                                    <strong><?php echo esc_js(__('Q:', 'wordchat-pro')); ?></strong> ${escapeHtml(msg.question)}
                                </div>
                                <div style="color: #6B7280; font-size: 14px; line-height: 1.6;">
                                    <strong><?php echo esc_js(__('A:', 'wordchat-pro')); ?></strong> ${escapeHtml(msg.answer)}
                                </div>
                            </div>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #9CA3AF;">
                            <span>${formattedDate}</span>
                            ${msg.navigated_to_url ? `<span style="color: #1A73E8;">→ ${escapeHtml(msg.navigated_to_url)}</span>` : ''}
                        </div>
                    </div>
                `;
            });

            messagesHTML += '</div>';

            // Add upgrade prompt for free users (WordPress admin theme)
            if (!isPaid && messages.length > 3) {
                const siteId = '<?php echo esc_js(get_option('wordchat_site_id', '')); ?>';
                const activityUpgradeUrl = 'https://www.word.chat/pricing?utm_source=plugin&utm_medium=activity_tab&utm_campaign=upgrade&site_id=' + encodeURIComponent(siteId);
                messagesHTML += `
                    <div style="margin-top: 24px; padding: 24px; background: linear-gradient(135deg, #2271b1 0%, #135e96 100%); border-radius: 6px; border: 1px solid #135e96; text-align: center; color: white; box-shadow: 0 1px 3px rgba(0,0,0,0.12);">
                        <h3 style="margin: 0 0 12px 0; font-size: 18px; font-weight: 600; color: white;">
                            <?php echo esc_js(__('Want to see all', 'wordchat-pro')); ?> ${messages.length} <?php echo esc_js(__('messages?', 'wordchat-pro')); ?>
                        </h3>
                        <p style="margin: 0 0 18px 0; opacity: 0.95; font-size: 14px; line-height: 1.5;">
                            <?php echo esc_js(__('Upgrade to Pro to view your complete chat history and unlock advanced analytics.', 'wordchat-pro')); ?>
                        </p>
                        <a href="${activityUpgradeUrl}" target="_blank" class="button" style="background: white !important; color: #2271b1 !important; border: 1px solid white !important; font-weight: 600 !important; padding: 10px 24px !important; font-size: 14px !important; height: auto !important; line-height: 1 !important; box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important; text-decoration: none !important; display: inline-block !important;">
                            <?php echo esc_js(__('Upgrade to Pro →', 'wordchat-pro')); ?>
                        </a>
                    </div>
                `;
            }

            messagesContainer.innerHTML = messagesHTML;
        })
        .catch(err => {
            console.error('Analytics load error:', err);
            if (loadingEl) loadingEl.style.display = 'none';
            if (errorEl) {
                errorEl.style.display = 'block';
                const errorMsgEl = document.getElementById('wordchat-error-message');
                if (errorMsgEl) {
                    errorMsgEl.textContent = err.message || '<?php echo esc_js(__('Unknown error occurred', 'wordchat-pro')); ?>';
                }
            }

            // Re-enable refresh button on error
            if (refreshBtn) {
                refreshBtn.disabled = false;
                const svg = refreshBtn.querySelector('svg');
                if (svg) {
                    svg.style.animation = '';
                }
            }
        });
    }

    // Helper function to escape HTML
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Handle feedback form submission
    document.addEventListener('DOMContentLoaded', function() {
        const feedbackForm = document.getElementById('wordchat-feedback-form');
        if (feedbackForm) {
            feedbackForm.addEventListener('submit', function(e) {
                e.preventDefault();

                const submitBtn = this.querySelector('button[type="submit"]');
                const statusEl = document.getElementById('wordchat-feedback-status');
                const nameEl = document.getElementById('feedback_name');
                const emailEl = document.getElementById('feedback_email');
                const messageEl = document.getElementById('feedback_message');

                // Disable button and show loading
                submitBtn.disabled = true;
                submitBtn.textContent = '<?php echo esc_js(__('Sending...', 'wordchat-pro')); ?>';
                statusEl.style.display = 'none';

                fetch("<?php echo esc_url(WORDCHAT_API_URL . '/submit-feedback'); ?>", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        site_id: "<?php echo esc_js($site_id); ?>",
                        name: nameEl.value,
                        email: emailEl.value,
                        message: messageEl.value,
                        site_url: "<?php echo esc_js(get_site_url()); ?>"
                    })
                })
                .then(res => res.json())
                .then(data => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php echo esc_js(__('Send Feedback', 'wordchat-pro')); ?>';

                    if (data.status === 'success') {
                        statusEl.style.display = 'block';
                        statusEl.style.color = '#10B981';
                        statusEl.innerHTML = '✓ ' + (data.message || '<?php echo esc_js(__('Thank you for your feedback!', 'wordchat-pro')); ?>');

                        // Clear form
                        messageEl.value = '';
                    } else {
                        statusEl.style.display = 'block';
                        statusEl.style.color = '#DC2626';
                        statusEl.innerHTML = '✗ <?php echo esc_js(__('Error:', 'wordchat-pro')); ?> ' + (data.error || '<?php echo esc_js(__('Unknown error', 'wordchat-pro')); ?>');
                    }

                    // Hide message after 5 seconds
                    setTimeout(() => {
                        statusEl.style.display = 'none';
                    }, 5000);
                })
                .catch(err => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php echo esc_js(__('Send Feedback', 'wordchat-pro')); ?>';
                    statusEl.style.display = 'block';
                    statusEl.style.color = '#DC2626';
                    statusEl.innerHTML = '✗ <?php echo esc_js(__('Failed to send:', 'wordchat-pro')); ?> ' + err.message;
                });
            });
        }
    });

    // --- Knowledge Base (Custom Q&A) ---
    const wordchatQANonce = '<?php echo esc_js(wp_create_nonce('wordchat_qa_nonce')); ?>';
    let wordchatQALoaded = false;

    function wordchatQALoad() {
        const loadingEl = document.getElementById('wordchat-qa-loading');
        const tableEl = document.getElementById('wordchat-qa-table-container');
        if (loadingEl) loadingEl.style.display = 'block';
        if (tableEl) tableEl.style.display = 'none';

        const formData = new FormData();
        formData.append('action', 'wordchat_qa_list');
        formData.append('nonce', wordchatQANonce);

        fetch(ajaxurl, { method: 'POST', body: formData })
        .then(r => r.json())
        .then(resp => {
            if (loadingEl) loadingEl.style.display = 'none';
            if (!resp.success) return;

            const pairs = resp.data.qa_pairs || [];
            const counter = document.getElementById('wordchat-qa-counter');
            if (counter) {
                if (wordchatIsPaid) {
                    counter.textContent = pairs.length + ' <?php echo esc_js(__('Q&A pairs', 'wordchat-pro')); ?>';
                } else {
                    counter.textContent = pairs.length + ' / 5 <?php echo esc_js(__('Q&A pairs used', 'wordchat-pro')); ?>';
                }
            }

            if (pairs.length === 0) {
                tableEl.innerHTML = '<p style="color:#6B7280;text-align:center;padding:20px;"><?php echo esc_js(__('No Q&A pairs yet. Add your first one above.', 'wordchat-pro')); ?></p>';
                tableEl.style.display = 'block';
                return;
            }

            let html = '<table class="widefat striped"><thead><tr><th><?php echo esc_js(__('Question', 'wordchat-pro')); ?></th><th><?php echo esc_js(__('Answer', 'wordchat-pro')); ?></th><th style="width:80px"><?php echo esc_js(__('Active', 'wordchat-pro')); ?></th><th style="width:100px"><?php echo esc_js(__('Actions', 'wordchat-pro')); ?></th></tr></thead><tbody>';
            pairs.forEach(qa => {
                const truncAnswer = qa.answer.length > 100 ? qa.answer.substring(0, 100) + '...' : qa.answer;
                html += '<tr id="qa-row-' + qa.id + '"><td>' + escapeHtml(qa.question) + '</td><td style="color:#6B7280;font-size:13px;">' + escapeHtml(truncAnswer) + '</td><td><input type="checkbox" ' + (qa.is_active ? 'checked' : '') + ' onchange="wordchatQAToggle(' + qa.id + ', this.checked)" /></td><td><button class="button button-small button-link-delete" onclick="wordchatQADelete(' + qa.id + ')"><?php echo esc_js(__('Delete', 'wordchat-pro')); ?></button></td></tr>';
            });
            html += '</tbody></table>';
            tableEl.innerHTML = html;
            tableEl.style.display = 'block';
        })
        .catch(() => { if (loadingEl) loadingEl.style.display = 'none'; });
    }

    function wordchatQAAdd() {
        const q = document.getElementById('wordchat-qa-question').value.trim();
        const a = document.getElementById('wordchat-qa-answer').value.trim();
        const statusEl = document.getElementById('wordchat-qa-add-status');
        if (!q || !a) { statusEl.style.display = 'block'; statusEl.style.color = '#DC2626'; statusEl.textContent = '<?php echo esc_js(__('Both question and answer are required.', 'wordchat-pro')); ?>'; return; }

        const btn = document.getElementById('wordchat-qa-add-btn');
        btn.disabled = true;

        const formData = new FormData();
        formData.append('action', 'wordchat_qa_add');
        formData.append('nonce', wordchatQANonce);
        formData.append('question', q);
        formData.append('answer', a);

        fetch(ajaxurl, { method: 'POST', body: formData })
        .then(r => r.json())
        .then(resp => {
            btn.disabled = false;
            if (resp.success) {
                document.getElementById('wordchat-qa-question').value = '';
                document.getElementById('wordchat-qa-answer').value = '';
                statusEl.style.display = 'block'; statusEl.style.color = '#059669'; statusEl.textContent = '<?php echo esc_js(__('Q&A pair added!', 'wordchat-pro')); ?>';
                setTimeout(() => statusEl.style.display = 'none', 3000);
                wordchatQALoad();
            } else {
                statusEl.style.display = 'block'; statusEl.style.color = '#DC2626';
                statusEl.textContent = (resp.data && resp.data.error) || (resp.data && resp.data.detail) || '<?php echo esc_js(__('Failed to add Q&A pair.', 'wordchat-pro')); ?>';
            }
        })
        .catch(() => { btn.disabled = false; });
    }

    function wordchatQAToggle(id, active) {
        const formData = new FormData();
        formData.append('action', 'wordchat_qa_update');
        formData.append('nonce', wordchatQANonce);
        formData.append('qa_id', id);
        formData.append('is_active', active ? '1' : '0');
        fetch(ajaxurl, { method: 'POST', body: formData });
    }

    function wordchatQADelete(id) {
        if (!confirm('<?php echo esc_js(__('Delete this Q&A pair?', 'wordchat-pro')); ?>')) return;
        const formData = new FormData();
        formData.append('action', 'wordchat_qa_delete');
        formData.append('nonce', wordchatQANonce);
        formData.append('qa_id', id);
        fetch(ajaxurl, { method: 'POST', body: formData })
        .then(r => r.json())
        .then(resp => { if (resp.success) wordchatQALoad(); });
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.wordchat-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                if (this.getAttribute('data-tab') === 'knowledge-base' && !wordchatQALoaded) {
                    wordchatQALoaded = true;
                    wordchatQALoad();
                }
            });
        });
        if ('<?php echo esc_js($active_tab); ?>' === 'knowledge-base') {
            wordchatQALoaded = true;
            wordchatQALoad();
        }
    });

    // Load unanswered questions data (Pro: all 50)
    let wordchatUnansweredLoaded = false;
    function wordchatLoadUnanswered() {
        const loadingEl = document.getElementById('wordchat-unanswered-loading');
        const dashboardEl = document.getElementById('wordchat-unanswered-dashboard');
        const emptyEl = document.getElementById('wordchat-unanswered-empty');

        if (loadingEl) loadingEl.style.display = 'block';
        if (dashboardEl) dashboardEl.style.display = 'none';
        if (emptyEl) emptyEl.style.display = 'none';

        fetch("<?php echo esc_url(WORDCHAT_API_URL . '/analytics/unanswered'); ?>", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                site_id: "<?php echo esc_js($site_id); ?>",
                api_key: "<?php echo esc_js($api_key); ?>",
                domain: "<?php echo esc_js(get_site_url()); ?>"
            })
        })
        .then(res => res.json())
        .then(data => {
            if (loadingEl) loadingEl.style.display = 'none';

            if (!data.questions || data.questions.length === 0) {
                if (emptyEl) emptyEl.style.display = 'block';
                return;
            }

            if (dashboardEl) dashboardEl.style.display = 'block';
            document.getElementById('metric-unanswered').textContent = data.total_unanswered || 0;
            document.getElementById('metric-unanswered-total').textContent = data.total_chats || 0;
            document.getElementById('metric-unanswered-rate').textContent = (data.unanswered_rate || 0) + '%';

            // Pro: show all questions
            const questions = wordchatIsPaid ? data.questions : data.questions.slice(0, 5);
            const tableContainer = document.getElementById('wordchat-unanswered-table');
            let html = '<table class="widefat striped"><thead><tr><th><?php echo esc_js(__('Question', 'wordchat-pro')); ?></th><th style="width:100px"><?php echo esc_js(__('Times Asked', 'wordchat-pro')); ?></th><th style="width:130px"><?php echo esc_js(__('Last Asked', 'wordchat-pro')); ?></th><th style="width:120px"><?php echo esc_js(__('Action', 'wordchat-pro')); ?></th></tr></thead><tbody>';

            questions.forEach(q => {
                const date = q.last_asked ? new Date(q.last_asked).toLocaleDateString() : '—';
                const postNewUrl = '<?php echo esc_js(admin_url('post-new.php?post_title=')); ?>' + encodeURIComponent(q.question);
                html += '<tr><td>' + escapeHtml(q.question) + '</td><td><span style="background:#DBEAFE;color:#1E40AF;padding:2px 8px;border-radius:10px;font-size:12px;font-weight:600;">' + q.ask_count + '</span></td><td style="color:#6B7280;font-size:13px;">' + date + '</td><td><a href="' + postNewUrl + '" class="button button-small"><?php echo esc_js(__('Write about this', 'wordchat-pro')); ?></a></td></tr>';
            });

            html += '</tbody></table>';

            if (!wordchatIsPaid && data.questions.length > 5) {
                const siteId = '<?php echo esc_js(get_option('wordchat_site_id', '')); ?>';
                html += '<div style="margin-top:16px;padding:16px;background:linear-gradient(135deg,#2271b1,#135e96);border-radius:6px;text-align:center;color:white;"><p style="margin:0 0 8px;"><?php echo esc_js(__('See all', 'wordchat-pro')); ?> ' + data.questions.length + ' <?php echo esc_js(__('unanswered questions with Pro', 'wordchat-pro')); ?></p><a href="https://www.word.chat/pricing?utm_source=plugin&utm_medium=unanswered_tab&utm_campaign=upgrade&site_id=' + encodeURIComponent(siteId) + '" target="_blank" class="button" style="background:white!important;color:#2271b1!important;border:1px solid white!important;font-weight:600!important;"><?php echo esc_js(__('Upgrade to Pro', 'wordchat-pro')); ?></a></div>';
            }

            tableContainer.innerHTML = html;
        })
        .catch(err => {
            if (loadingEl) loadingEl.style.display = 'none';
            if (emptyEl) {
                emptyEl.style.display = 'block';
                emptyEl.innerHTML = '<p style="color:#DC2626;"><?php echo esc_js(__('Failed to load unanswered questions.', 'wordchat-pro')); ?></p>';
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.wordchat-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                if (this.getAttribute('data-tab') === 'unanswered' && !wordchatUnansweredLoaded) {
                    wordchatUnansweredLoaded = true;
                    wordchatLoadUnanswered();
                }
            });
        });
        if ('<?php echo esc_js($active_tab); ?>' === 'unanswered') {
            wordchatUnansweredLoaded = true;
            wordchatLoadUnanswered();
        }
    });

    // Preview chat widget in admin
    document.addEventListener('DOMContentLoaded', function() {
        const previewBtn = document.getElementById('wordchat-preview-btn');
        const closeBtn = document.getElementById('wordchat-preview-close-btn');
        const container = document.getElementById('wordchat-preview-container');
        if (!previewBtn || !container) return;

        previewBtn.addEventListener('click', function() {
            container.style.display = 'block';
            container.innerHTML = '';
            previewBtn.style.display = 'none';
            closeBtn.style.display = 'inline-block';

            const previewVars = {
                ajax_url: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
                nonce: '<?php echo esc_js(wp_create_nonce('wordchat_query_nonce')); ?>',
                header_text: document.getElementById('wordchat_header_text') ? document.getElementById('wordchat_header_text').value : '',
                intro_message: document.getElementById('wordchat_intro_message') ? document.getElementById('wordchat_intro_message').value : '',
                navigate_to_response: false,
                primary_color: document.getElementById('wordchat_primary_color') ? document.getElementById('wordchat_primary_color').value : '#1A73E8',
                start_open: true,
                position: document.getElementById('wordchat_position') ? document.getElementById('wordchat_position').value : 'right',
                placeholder: document.getElementById('wordchat_placeholder') ? document.getElementById('wordchat_placeholder').value : 'Ask a question...',
                button_text: document.getElementById('wordchat_button_text') ? document.getElementById('wordchat_button_text').value : 'Send'
            };

            const style = document.createElement('style');
            style.textContent = '#wordchat-preview-container .wordchat-widget-container { position: absolute !important; } #wordchat-preview-container .wordchat-toggle-btn { position: absolute !important; }';
            container.appendChild(style);

            window.WordChatVars = previewVars;

            const script = document.createElement('script');
            script.src = '<?php echo esc_js(plugin_dir_url(dirname(__FILE__)) . 'js/chat.js'); ?>?preview=' + Date.now();
            container.appendChild(script);
        });

        closeBtn.addEventListener('click', function() {
            container.style.display = 'none';
            container.innerHTML = '';
            previewBtn.style.display = 'inline-block';
            closeBtn.style.display = 'none';
        });
    });

    // Handle site description form submission
    document.addEventListener('DOMContentLoaded', function() {
        const descriptionForm = document.getElementById('wordchat-site-description-form');
        if (descriptionForm) {
            descriptionForm.addEventListener('submit', function(e) {
                e.preventDefault();

                const submitBtn = this.querySelector('button[type="submit"]');
                const statusEl = document.getElementById('wordchat-site-description-status');
                const textareaEl = document.getElementById('wordchat_site_description');

                // Disable button and show loading
                submitBtn.disabled = true;
                submitBtn.textContent = '<?php echo esc_js(__('Saving...', 'wordchat-pro')); ?>';
                statusEl.style.display = 'none';

                fetch("<?php echo esc_url(WORDCHAT_API_URL . '/update-site-info'); ?>", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        site_id: "<?php echo esc_js($site_id); ?>",
                        api_key: "<?php echo esc_js($api_key); ?>",
                        domain: "<?php echo esc_js(get_site_url()); ?>",
                        site_description: textareaEl.value
                    })
                })
                .then(res => res.json())
                .then(data => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php echo esc_js(__('Save Description', 'wordchat-pro')); ?>';

                    if (data.status === 'updated') {
                        statusEl.style.display = 'block';
                        statusEl.style.color = '#10B981';
                        statusEl.innerHTML = '✓ <?php echo esc_js(__('Description saved successfully!', 'wordchat-pro')); ?>';
                    } else {
                        statusEl.style.display = 'block';
                        statusEl.style.color = '#DC2626';
                        statusEl.innerHTML = '✗ <?php echo esc_js(__('Error:', 'wordchat-pro')); ?> ' + (data.error || '<?php echo esc_js(__('Unknown error', 'wordchat-pro')); ?>');
                    }

                    // Hide message after 5 seconds
                    setTimeout(() => {
                        statusEl.style.display = 'none';
                    }, 5000);
                })
                .catch(err => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php echo esc_js(__('Save Description', 'wordchat-pro')); ?>';
                    statusEl.style.display = 'block';
                    statusEl.style.color = '#DC2626';
                    statusEl.innerHTML = '✗ <?php echo esc_js(__('Failed to save:', 'wordchat-pro')); ?> ' + err.message;
                });
            });
        }
    });
    </script>
    <?php
}

// Registration prompt for failed or incomplete registration
function wordchat_show_registration_prompt() {
    $error = get_option('wordchat_registration_error');
    $retry_count = (int) get_option('wordchat_registration_retry_count', 0);
    ?>
    <div class="wrap wordchat-admin-wrap">
        <h1><?php echo esc_html__('Word.Chat Setup', 'wordchat-pro'); ?></h1>

        <?php if ($error): ?>
            <div class="notice notice-error">
                <p>
                    <strong><?php echo esc_html__('Registration failed:', 'wordchat-pro'); ?></strong>
                    <?php echo esc_html($error); ?>
                </p>
                <?php if ($retry_count > 0): ?>
                    <p><?php printf(esc_html__('Retry attempts: %d', 'wordchat-pro'), $retry_count); ?></p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="wordchat-card">
            <h2><?php echo esc_html__('Connect to Word.Chat', 'wordchat-pro'); ?></h2>
            <p><?php echo esc_html__('Your WordPress site needs to connect to Word.Chat servers to enable the AI chatbot.', 'wordchat-pro'); ?></p>

            <p><?php echo esc_html__('This process will:', 'wordchat-pro'); ?></p>
            <ul style="list-style: disc; margin-left: 24px; margin-bottom: 24px;">
                <li><?php echo esc_html__('Register your WordPress site with Word.Chat', 'wordchat-pro'); ?></li>
                <li><?php echo esc_html__('Generate secure API credentials', 'wordchat-pro'); ?></li>
                <li><?php echo esc_html__('Enable AI chatbot functionality', 'wordchat-pro'); ?></li>
            </ul>

            <form method="post" id="wordchat-registration-form">
                <?php wp_nonce_field('wordchat_retry_registration', 'wordchat_registration_nonce'); ?>
                <p>
                    <button type="submit" name="wordchat_retry_register" class="button button-primary button-hero">
                        <?php echo $retry_count > 0 ? esc_html__('Retry Connection', 'wordchat-pro') : esc_html__('Complete Setup', 'wordchat-pro'); ?>
                    </button>
                    <span id="wordchat-registration-status" style="margin-left: 16px; display: none;">
                        <span class="spinner" style="visibility: visible; float: none; margin: 0;"></span>
                        <span><?php echo esc_html__('Connecting...', 'wordchat-pro'); ?></span>
                    </span>
                </p>
            </form>

            <p class="description">
                <?php echo esc_html__('No account creation needed. Your WordPress admin email will be used for contact purposes only.', 'wordchat-pro'); ?>
            </p>

            <?php if ($error): ?>
                <div style="margin-top: 24px; padding: 16px; background: #f9fafb; border-left: 4px solid #6b7280;">
                    <h3 style="margin-top: 0;"><?php echo esc_html__('Troubleshooting', 'wordchat-pro'); ?></h3>
                    <ul style="list-style: disc; margin-left: 24px;">
                        <li><?php echo esc_html__('Check your internet connection', 'wordchat-pro'); ?></li>
                        <li><?php echo esc_html__('Verify your WordPress site can make outbound HTTP requests', 'wordchat-pro'); ?></li>
                        <li><?php echo esc_html__('Wait a moment and try again (server may be starting up)', 'wordchat-pro'); ?></li>
                        <li><?php echo esc_html__('Contact support if the issue persists', 'wordchat-pro'); ?></li>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    document.getElementById('wordchat-registration-form').addEventListener('submit', function() {
        document.getElementById('wordchat-registration-status').style.display = 'inline-block';
        document.querySelector('button[name="wordchat_retry_register"]').disabled = true;
    });
    </script>
    <?php
}

// Handle retry registration
function wordchat_handle_retry_registration() {
    if (!isset($_POST['wordchat_retry_register'])) {
        return;
    }

    if (!isset($_POST['wordchat_registration_nonce']) ||
        !wp_verify_nonce($_POST['wordchat_registration_nonce'], 'wordchat_retry_registration')) {
        wp_die(__('Security check failed', 'wordchat-pro'));
    }

    // Increment retry count
    $retry_count = (int) get_option('wordchat_registration_retry_count', 0);
    update_option('wordchat_registration_retry_count', $retry_count + 1);

    // Attempt registration
    wordchat_register_plugin();

    // Redirect to avoid resubmission
    $redirect_url = admin_url('admin.php?page=wordchat-pro');

    // Add status parameter
    if (get_option('wordchat_site_id')) {
        $redirect_url = add_query_arg('registration', 'success', $redirect_url);
    } else {
        $redirect_url = add_query_arg('registration', 'retry_failed', $redirect_url);
    }

    wp_redirect($redirect_url);
    exit;
}
add_action('admin_init', 'wordchat_handle_retry_registration');

// Admin notices for registration status
function wordchat_admin_notices() {
    $screen = get_current_screen();
    if (!$screen || $screen->id !== 'toplevel_page_wordchat-pro') {
        return;
    }

    // Show welcome message after successful activation
    if (get_transient('wordchat_show_welcome')) {
        delete_transient('wordchat_show_welcome');
        ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <strong><?php echo esc_html__('Word.Chat activated successfully!', 'wordchat-pro'); ?></strong>
                <?php echo esc_html__('Your AI chatbot is ready. Start by customizing the widget and syncing your content below.', 'wordchat-pro'); ?>
            </p>
        </div>
        <?php
    }

    // Show registration status messages
    if (isset($_GET['registration'])) {
        $status = sanitize_text_field($_GET['registration']);

        if ($status === 'success') {
            ?>
            <div class="notice notice-success is-dismissible">
                <p>
                    <strong><?php echo esc_html__('Setup completed successfully!', 'wordchat-pro'); ?></strong>
                    <?php echo esc_html__('Your site is now connected to Word.Chat.', 'wordchat-pro'); ?>
                </p>
            </div>
            <?php
        } elseif ($status === 'retry_failed') {
            ?>
            <div class="notice notice-error is-dismissible">
                <p>
                    <strong><?php echo esc_html__('Setup failed.', 'wordchat-pro'); ?></strong>
                    <?php echo esc_html__('Please check the error details below and try again.', 'wordchat-pro'); ?>
                </p>
            </div>
            <?php
        }
    }
}
add_action('admin_notices', 'wordchat_admin_notices');

// AJAX handler for retry sync
add_action('wp_ajax_wordchat_retry_sync', 'wordchat_handle_ajax_retry');

function wordchat_handle_ajax_retry() {
    // Check capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('Insufficient permissions', 'wordchat-pro'));
        return;
    }

    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'wordchat_retry_sync')) {
        wp_send_json_error(__('Security check failed', 'wordchat-pro'));
        return;
    }

    // Get post ID
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    if (!$post_id) {
        wp_send_json_error(__('Invalid post ID', 'wordchat-pro'));
        return;
    }

    // Verify post exists
    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error(__('Post not found', 'wordchat-pro'));
        return;
    }

    // Reset status
    update_post_meta($post_id, 'wordchat_sync_status', 'pending');
    delete_post_meta($post_id, 'wordchat_sync_error');

    // Mark as synced
    update_post_meta($post_id, 'wordchat_synced', true);

    // Sync immediately (more reliable than WP Cron)
    wordchat_sync_content_now($post_id);

    // Check if sync was successful
    $sync_status = get_post_meta($post_id, 'wordchat_sync_status', true);
    if ($sync_status === 'synced') {
        wp_send_json_success(__('Sync completed successfully', 'wordchat-pro'));
    } else {
        $error = get_post_meta($post_id, 'wordchat_sync_error', true);
        wp_send_json_error($error ? $error : __('Sync failed', 'wordchat-pro'));
    }
}
