<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Admin UI for theme-wide AI wizard with page selection and real-time progress.
 *
 * @since 2.2.0
 */
class AI_Magic_Theme_Wizard_Admin
{

    /**
     * Transient key for stop flag.
     */
    const STOP_TRANSIENT = 'ai_magic_wizard_stop';

    public function __construct()
    {
        add_action('admin_menu', array($this, 'register_menu'), 20);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));

        // AJAX handlers
        add_action('wp_ajax_ai_magic_wizard_get_pages', array($this, 'ajax_get_pages'));
        add_action('wp_ajax_ai_magic_wizard_process_page', array($this, 'ajax_process_page'));
        add_action('wp_ajax_ai_magic_wizard_stop', array($this, 'ajax_stop'));
        add_action('wp_ajax_ai_magic_wizard_check_stop', array($this, 'ajax_check_stop'));
        add_action('wp_ajax_ai_magic_wizard_clear_stop', array($this, 'ajax_clear_stop'));
        add_action('wp_ajax_ai_magic_wizard_save_state', array($this, 'ajax_save_state'));
    }

    /**
     * Register submenu page.
     */
    public function register_menu()
    {
        add_submenu_page(
            'ai-magic-settings',
            __('Theme Wizard', 'ai-magic-settings'),
            __('Theme Wizard', 'ai-magic-settings'),
            'manage_options',
            'ai-magic-theme-wizard',
            array($this, 'render_page')
        );
    }

    /**
     * Enqueue CSS and JS for wizard page.
     */
    public function enqueue_assets($hook)
    {
        if (strpos($hook, 'ai-magic-theme-wizard') === false) {
            return;
        }

        wp_enqueue_style(
            'ai-magic-theme-wizard',
            plugin_dir_url(__FILE__) . 'css/ai-magic-theme-wizard.css',
            array(),
            AI_MAGIC_VERSION
        );

        wp_enqueue_script(
            'ai-magic-theme-wizard',
            plugin_dir_url(__FILE__) . 'js/ai-magic-theme-wizard.js',
            array('jquery'),
            AI_MAGIC_VERSION,
            true
        );

        wp_localize_script('ai-magic-theme-wizard', 'aiMagicWizard', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ai_magic_wizard_nonce'),
            'savedState' => get_option('ai_magic_wizard_state', array()),
            'providerModels' => array(
                'openai' => AI_Magic_Provider_Manager::get_available_models('openai'),
                'anthropic' => AI_Magic_Provider_Manager::get_available_models('anthropic'),
                'google' => AI_Magic_Provider_Manager::get_available_models('google'),
                'openrouter' => AI_Magic_Provider_Manager::get_available_models('openrouter'),
            ),
            'i18n' => array(
                'promptRequired' => __('Please enter client/project information.', 'ai-magic-settings'),
                'selectPages' => __('Please select at least one page.', 'ai-magic-settings'),
                'loading' => __('Loading pages...', 'ai-magic-settings'),
                'noPages' => __('No pages found.', 'ai-magic-settings'),
                'networkError' => __('Network error. Please try again.', 'ai-magic-settings'),
                'processError' => __('Failed to process this item.', 'ai-magic-settings'),
                'stopping' => __('Stopping...', 'ai-magic-settings'),
                'stop' => __('Stop', 'ai-magic-settings'),
                'stopped' => __('Wizard Stopped', 'ai-magic-settings'),
                'stoppedMessage' => __('Wizard stopped. Some items may have been updated.', 'ai-magic-settings'),
                'completed' => __('Wizard Completed!', 'ai-magic-settings'),
                'completedMessage' => __('All selected pages have been updated with AI.', 'ai-magic-settings'),
                'itemsProcessed' => __('Pages Processed', 'ai-magic-settings'),
                'totalCost' => __('Total Cost', 'ai-magic-settings'),
                'customNameLabel' => __('Custom name for page (optional)', 'ai-magic-settings'),
                'customNamePlaceholder' => __('E.g., About Us, Contact, Services...', 'ai-magic-settings'),
                'before' => __('Before', 'ai-magic-settings'),
                'after' => __('After', 'ai-magic-settings'),
                'error' => __('Error', 'ai-magic-settings'),
                'showChanges' => __('Show Changes', 'ai-magic-settings'),
                'runAgain' => __('Run Again', 'ai-magic-settings'),
                'selectAll' => __('Select All', 'ai-magic-settings'),
                'deselectAll' => __('Deselect All', 'ai-magic-settings'),
            )
        ));
    }

    /**
     * Render wizard page - Single page layout (no steps).
     */
    public function render_page()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have permission to access this page.', 'ai-magic-settings'));
        }
        ?>
        <div class="ai-magic-wizard-wrap">
            <div class="ai-magic-wizard-header">
                <span class="dashicons dashicons-admin-customizer"></span>
                <h1><?php esc_html_e('AI Magic Theme Wizard', 'ai-magic-settings'); ?></h1>
            </div>

            <form id="ai-magic-wizard-form">
                <!-- Section 1: Client Info -->
                <div class="ai-magic-card" style="margin-bottom: 20px;">
                    <div class="ai-magic-card-header">
                        <h2><?php esc_html_e('Client / Project Information', 'ai-magic-settings'); ?></h2>
                    </div>
                    <p style="color: #6b7280; margin-bottom: 16px;">
                        <?php esc_html_e('Describe the client: company name, industry, services, location, target audience, tone, language, etc.', 'ai-magic-settings'); ?>
                    </p>

                    <!-- Prompt Examples -->
                    <div class="ai-magic-prompt-examples">
                        <label><?php esc_html_e('Quick Start Examples:', 'ai-magic-settings'); ?></label>
                        <div class="ai-magic-example-chips">
                            <button type="button" class="ai-magic-example-chip"
                                data-prompt="TechPro Solutions is a software development company based in San Francisco. We specialize in custom web and mobile applications for startups and enterprises. Our services include: UI/UX design, full-stack development, cloud solutions, and DevOps consulting. Target audience: Tech startups and mid-size companies. Tone: Professional, innovative, and approachable. Language: English.">
                                💻 Tech Company
                            </button>
                            <button type="button" class="ai-magic-example-chip"
                                data-prompt="Fresh & Healthy is an organic restaurant located in downtown Chicago. We serve farm-to-table cuisine with locally sourced ingredients. Our menu features vegan, vegetarian, and gluten-free options. Target audience: Health-conscious food lovers aged 25-45. Tone: Warm, inviting, and eco-friendly. Language: English.">
                                🍽️ Restaurant
                            </button>
                            <button type="button" class="ai-magic-example-chip"
                                data-prompt="CloudFit Gym is a modern fitness center in Los Angeles. We offer personal training, group classes, yoga, CrossFit, and nutrition coaching. Open 24/7 with state-of-the-art equipment. Target audience: Fitness enthusiasts aged 20-50. Tone: Energetic, motivational, and supportive. Language: English.">
                                💪 Fitness
                            </button>
                            <button type="button" class="ai-magic-example-chip"
                                data-prompt="Smith & Associates is a law firm in New York specializing in corporate law, real estate, and intellectual property. We have 20+ years of experience serving Fortune 500 companies and startups. Target audience: Business owners and corporations. Tone: Professional, trustworthy, and authoritative. Language: English.">
                                ⚖️ Law Firm
                            </button>
                            <!-- More Examples Toggle -->
                            <details class="ai-magic-more-examples-toggle" id="ai-magic-more-examples">
                                <summary>
                                    <span class="dashicons dashicons-plus-alt2"></span>
                                    +20 <?php esc_html_e('more', 'ai-magic-settings'); ?>
                                </summary>
                                <div class="ai-magic-example-chips">
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="Bright Minds Academy is a private K-12 school in Boston. We offer personalized education with small class sizes, STEM programs, arts, and athletics. Target audience: Parents of school-age children. Tone: Caring, educational, and inspiring. Language: English.">📚
                                        Education</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="GreenHome Realty is a real estate agency in Miami specializing in residential and commercial properties. Target audience: Home buyers, sellers, and investors. Tone: Professional, helpful, and trustworthy. Language: English.">🏠
                                        Real Estate</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="HealthFirst Medical Center is a multi-specialty clinic in Seattle offering primary care, pediatrics, cardiology services. Target audience: Families and individuals seeking quality healthcare. Tone: Compassionate, professional, and reassuring. Language: English.">🏥
                                        Healthcare</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="StyleMe Boutique is a women's fashion store in London. We curate trendy and affordable clothing, accessories, and jewelry. Target audience: Fashion-forward women aged 18-40. Tone: Trendy, fun, and empowering. Language: English.">👗
                                        Fashion</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="Wanderlust Travel Agency specializes in luxury and adventure travel experiences worldwide. Target audience: Affluent travelers and adventure seekers. Tone: Exciting, luxurious, and knowledgeable. Language: English.">✈️
                                        Travel Agency</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="AutoCare Pro is a full-service auto repair shop in Dallas providing oil changes, brake repairs, engine diagnostics. Target audience: Vehicle owners needing reliable auto service. Tone: Honest, reliable, and expert. Language: English.">🚗
                                        Auto Repair</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="PetPals Veterinary Clinic provides comprehensive care for dogs, cats, and exotic pets in Denver. Target audience: Pet owners who treat pets as family. Tone: Caring, friendly, and professional. Language: English.">🐾
                                        Veterinary</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="Serenity Spa & Wellness offers massage therapy, facials, body treatments in a peaceful environment. Target audience: Stressed professionals seeking relaxation. Tone: Calming, luxurious, and rejuvenating. Language: English.">💆
                                        Spa & Wellness</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="BuildRight Construction is a residential and commercial construction company in Atlanta. Target audience: Homeowners and businesses needing construction services. Tone: Reliable, skilled, and professional. Language: English.">🏗️
                                        Construction</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="SnapShot Photography specializes in wedding, portrait, and event photography in San Diego. Target audience: Couples, families, and event planners. Tone: Creative, passionate, and personable. Language: English.">📸
                                        Photography</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="TechGadget Store is an electronics retailer selling smartphones, laptops, gaming consoles in Austin. Target audience: Tech enthusiasts and everyday consumers. Tone: Knowledgeable, helpful, and competitive. Language: English.">📱
                                        Electronics</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="GreenThumb Landscaping provides lawn care, garden design, tree trimming services in Phoenix. Target audience: Homeowners with yards needing maintenance. Tone: Nature-loving, reliable, and creative. Language: English.">🌳
                                        Landscaping</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="Elite Dental Care is a family dentistry practice offering cleanings, whitening, implants in Chicago. Target audience: Families and individuals seeking dental care. Tone: Caring, professional, and modern. Language: English.">🦷
                                        Dental Care</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="CyberSecure IT provides cybersecurity consulting, network security for businesses in Washington DC. Target audience: Small to medium businesses concerned about security. Tone: Expert, trustworthy, and proactive. Language: English.">🔒
                                        Cybersecurity</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="Fresh Bakery & Café serves artisan breads, pastries, coffee in Portland. All items baked fresh daily with organic ingredients. Target audience: Food lovers seeking quality baked goods. Tone: Warm, artisanal, and welcoming. Language: English.">🥐
                                        Bakery & Café</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="QuickShip Logistics offers freight shipping, warehousing, and supply chain solutions nationwide. Target audience: E-commerce and retail businesses. Tone: Efficient, reliable, and professional. Language: English.">📦
                                        Logistics</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="HomeGuard Insurance Agency provides home, auto, life insurance policies in Texas. Target audience: Homeowners and families. Tone: Protective, trustworthy, and helpful. Language: English.">🛡️
                                        Insurance</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="CleanPro Cleaning Services offers residential and commercial cleaning in Miami. Eco-friendly products and thorough attention to detail. Target audience: Busy professionals and property managers. Tone: Meticulous, trustworthy, and eco-conscious. Language: English.">🧹
                                        Cleaning</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="GameZone Arcade & Entertainment is a family entertainment center with arcade games, VR experiences, laser tag in Orlando. Target audience: Families with children and teenagers. Tone: Fun, exciting, and family-friendly. Language: English.">🎮
                                        Entertainment</button>
                                    <button type="button" class="ai-magic-example-chip"
                                        data-prompt="GreenEnergy Solar installs residential and commercial solar panels in California. Save money on electricity while helping the environment. Target audience: Environmentally conscious homeowners. Tone: Sustainable, innovative, and cost-saving. Language: English.">☀️
                                        Solar Energy</button>
                                </div>
                            </details>
                        </div>
                    </div>

                    <!-- Settings Grid: Provider, Model, Language -->
                    <div class="ai-magic-settings-grid">
                        <div class="ai-magic-field">
                            <label for="ai-magic-provider"><?php esc_html_e('AI Provider', 'ai-magic-settings'); ?></label>
                            <select name="provider" id="ai-magic-provider" class="ai-magic-select">
                                <?php
                                $active_providers = AI_Magic_Provider_Manager::get_active_providers();
                                $default_provider = AI_Magic_Provider_Manager::get_default_provider();
                                $providers = AI_Magic_Provider_Manager::get_providers();

                                foreach ($active_providers as $provider_id):
                                    $provider = isset($providers[$provider_id]) ? $providers[$provider_id] : null;
                                    if (!$provider)
                                        continue;
                                    $selected = ($provider_id === $default_provider) ? 'selected' : '';
                                    ?>
                                    <option value="<?php echo esc_attr($provider_id); ?>" <?php echo $selected; ?>>
                                        <?php echo esc_html($provider['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="ai-magic-field">
                            <label for="ai-magic-model"><?php esc_html_e('Model', 'ai-magic-settings'); ?></label>
                            <select name="model" id="ai-magic-model" class="ai-magic-select">
                                <?php
                                $first_provider = !empty($active_providers) ? $active_providers[0] : 'openai';
                                if ($default_provider)
                                    $first_provider = $default_provider;
                                $models = AI_Magic_Provider_Manager::get_available_models($first_provider);
                                $provider_settings = AI_Magic_Provider_Manager::get_provider_settings($first_provider);
                                $current_model = isset($provider_settings['model']) ? $provider_settings['model'] : '';

                                foreach ($models as $model):
                                    $selected = ($model['id'] === $current_model) ? 'selected' : '';
                                    $recommended = isset($model['recommended']) && $model['recommended'] ? ' ⭐' : '';
                                    ?>
                                    <option value="<?php echo esc_attr($model['id']); ?>" <?php echo $selected; ?>>
                                        <?php echo esc_html($model['name'] . $recommended); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="ai-magic-field">
                            <label for="ai-magic-language"><?php esc_html_e('Output Language', 'ai-magic-settings'); ?></label>
                            <select name="language" id="ai-magic-language" class="ai-magic-select">
                                <?php
                                // Get default language from provider settings
                                $default_provider = AI_Magic_Provider_Manager::get_default_provider();
                                $default_language = get_option("ai_magic_{$default_provider}_language", 'en');

                                $languages = array(
                                    'en' => '🇬🇧 English',
                                    'tr' => '🇹🇷 Türkçe',
                                    'de' => '🇩🇪 Deutsch',
                                    'fr' => '🇫🇷 Français',
                                    'es' => '🇪🇸 Español',
                                    'it' => '🇮🇹 Italiano',
                                    'pt' => '🇵🇹 Português',
                                    'nl' => '🇳🇱 Nederlands',
                                    'ru' => '🇷🇺 Русский',
                                    'zh' => '🇨🇳 中文',
                                    'ja' => '🇯🇵 日本語',
                                    'ko' => '🇰🇷 한국어',
                                    'ar' => '🇸🇦 العربية',
                                );

                                foreach ($languages as $code => $label):
                                    $selected = ($code === $default_language) ? 'selected' : '';
                                    ?>
                                    <option value="<?php echo esc_attr($code); ?>" <?php echo $selected; ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <textarea name="prompt" id="ai-magic-prompt-textarea" class="ai-magic-textarea"
                        placeholder="<?php esc_attr_e('Example: XYZ Digital Agency, a modern web design company based in New York. Offers e-commerce solutions for SMBs. Tone: Professional yet friendly. Language: English.', 'ai-magic-settings'); ?>"
                        required></textarea>
                </div>

                <!-- Section 2: Page Selection -->
                <div class="ai-magic-card" style="margin-bottom: 20px;">
                    <div class="ai-magic-card-header">
                        <h2><?php esc_html_e('Page Selection', 'ai-magic-settings'); ?></h2>
                    </div>
                    <p style="color: #6b7280; margin-bottom: 16px;">
                        <?php esc_html_e('Select the pages you want to update and optionally give them custom names.', 'ai-magic-settings'); ?>
                    </p>

                    <div class="ai-magic-page-list">
                        <div class="ai-magic-page-list-header">
                            <span class="ai-magic-selected-count">
                                <span class="dashicons dashicons-yes"></span>
                                <span id="ai-magic-selected-count">0</span>
                                <?php esc_html_e('pages selected', 'ai-magic-settings'); ?>
                            </span>
                            <div class="ai-magic-page-list-actions">
                                <button type="button" id="ai-magic-toggle-groups"
                                    title="<?php esc_attr_e('Expand/Collapse All', 'ai-magic-settings'); ?>">
                                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                                </button>
                                <button type="button"
                                    id="ai-magic-select-all"><?php esc_html_e('Select All', 'ai-magic-settings'); ?></button>
                                <button type="button"
                                    id="ai-magic-deselect-all"><?php esc_html_e('Deselect All', 'ai-magic-settings'); ?></button>
                            </div>
                        </div>
                        <div id="ai-magic-page-list-content">
                            <div style="padding: 20px; text-align: center; color: #666;">
                                <span class="spinner is-active" style="float: none;"></span>
                                <?php esc_html_e('Loading pages...', 'ai-magic-settings'); ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Run Button -->
                <div class="ai-magic-card" style="margin-bottom: 20px;">
                    <div style="display: flex; justify-content: center; gap: 16px;">
                        <button type="button" id="ai-magic-wizard-run"
                            class="ai-magic-btn ai-magic-btn-primary ai-magic-btn-large" disabled>
                            <span class="dashicons dashicons-controls-play"></span>
                            <?php esc_html_e('Run Wizard', 'ai-magic-settings'); ?>
                        </button>
                    </div>
                </div>

                <!-- Progress Section (hidden initially) -->
                <div id="ai-magic-progress-section" class="ai-magic-card" style="display: none;">
                    <div class="ai-magic-progress-header">
                        <h2 style="margin: 0;"><?php esc_html_e('Processing...', 'ai-magic-settings'); ?></h2>
                        <div class="ai-magic-progress-stats">
                            <div class="ai-magic-stat">
                                <div class="ai-magic-stat-value" id="ai-magic-stats-processed">0 / 0</div>
                                <div class="ai-magic-stat-label"><?php esc_html_e('Pages', 'ai-magic-settings'); ?></div>
                            </div>
                            <div class="ai-magic-stat">
                                <div class="ai-magic-stat-value cost" id="ai-magic-stats-cost">$0.0000</div>
                                <div class="ai-magic-stat-label"><?php esc_html_e('Cost', 'ai-magic-settings'); ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="ai-magic-progress-bar-container">
                        <div class="ai-magic-progress-bar" id="ai-magic-progress-bar"></div>
                    </div>

                    <div class="ai-magic-current-item" id="ai-magic-current-item">
                        <span class="spinner is-active"></span>
                        <div class="ai-magic-current-item-text">
                            <div class="ai-magic-current-item-label"><?php esc_html_e('Processing', 'ai-magic-settings'); ?>
                            </div>
                            <div class="ai-magic-current-item-name">-</div>
                        </div>
                        <button type="button" id="ai-magic-wizard-stop" class="ai-magic-btn ai-magic-btn-danger">
                            <span class="dashicons dashicons-controls-pause"></span>
                            <?php esc_html_e('Stop', 'ai-magic-settings'); ?>
                        </button>
                    </div>

                    <div class="ai-magic-log" id="ai-magic-log"></div>
                </div>
            </form>
        </div>
        <?php
    }

    /**
     * AJAX: Get all pages for selection.
     */
    public function ajax_get_pages()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied.', 'ai-magic-settings')));
        }

        $pages = array();
        $post_types = array('post', 'page');

        // Add public custom post types
        $cpts = get_post_types(array('public' => true, '_builtin' => false), 'names');
        if (is_array($cpts)) {
            $post_types = array_merge($post_types, $cpts);
        }

        foreach ($post_types as $pt) {
            // Skip AI Magic Log post type
            if ($pt === 'ai_magic_logs') {
                continue;
            }

            $posts = get_posts(array(
                'post_type' => $pt,
                'posts_per_page' => -1,
                'post_status' => 'publish',
                'orderby' => 'title',
                'order' => 'ASC',
            ));

            foreach ($posts as $post) {
                $post_type_obj = get_post_type_object($pt);
                $pages[] = array(
                    'id' => $post->ID,
                    'title' => $post->post_title ?: __('(Untitled)', 'ai-magic-settings'),
                    'post_type' => $post_type_obj ? $post_type_obj->labels->singular_name : $pt,
                    'date' => get_the_date('d.m.Y', $post->ID),
                );
            }
        }

        // Clear any previous stop flag
        delete_transient(self::STOP_TRANSIENT);

        wp_send_json_success(array('pages' => $pages));
    }

    /**
     * AJAX: Process a single page.
     */
    public function ajax_process_page()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied.', 'ai-magic-settings')));
        }

        $page_id = isset($_POST['page_id']) ? absint($_POST['page_id']) : 0;
        $custom_name = isset($_POST['custom_name']) ? sanitize_text_field($_POST['custom_name']) : '';
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        $language = isset($_POST['language']) ? sanitize_text_field($_POST['language']) : 'English';
        $provider_id = isset($_POST['provider']) ? sanitize_text_field($_POST['provider']) : '';
        $model_id = isset($_POST['model']) ? sanitize_text_field($_POST['model']) : '';

        if (!$page_id || !$prompt) {
            wp_send_json_error(array('message' => __('Invalid request.', 'ai-magic-settings')));
        }

        // Check stop flag
        if (get_transient(self::STOP_TRANSIENT)) {
            wp_send_json_error(array('message' => __('Wizard stopped by user.', 'ai-magic-settings')));
        }

        // Get provider
        if (!class_exists('AI_Magic_Provider_Manager')) {
            wp_send_json_error(array('message' => __('Provider manager not found.', 'ai-magic-settings')));
        }

        // Use provided provider or fall back to default
        if (empty($provider_id)) {
            $provider_id = AI_Magic_Provider_Manager::get_default_provider();
        }
        $provider = AI_Magic_Provider_Manager::get_provider_instance($provider_id);

        // If model is specified, set it on the provider
        if (!empty($model_id) && $provider && method_exists($provider, 'setModel')) {
            $provider->setModel($model_id);
        }

        if (!$provider || !method_exists($provider, 'generateText')) {
            wp_send_json_error(array('message' => __('AI provider not configured.', 'ai-magic-settings')));
        }

        $total_cost = 0;
        $old_text = '';
        $new_text = '';

        try {
            $ai = new AI_Magic_Layout_AI($provider);
            $editor = AI_Magic_Editor_Detector::detect_editor($page_id);

            // Enhance prompt with custom name and language
            // CRITICAL: Put language instruction FIRST and make it very explicit
            // Map language codes to full names for AI
            $language_names = array(
                'en' => 'English',
                'tr' => 'Turkish',
                'de' => 'German',
                'fr' => 'French',
                'es' => 'Spanish',
                'it' => 'Italian',
                'pt' => 'Portuguese',
                'nl' => 'Dutch',
                'ru' => 'Russian',
                'zh' => 'Chinese',
                'ja' => 'Japanese',
                'ko' => 'Korean',
                'ar' => 'Arabic',
            );
            $language_name = isset($language_names[$language]) ? $language_names[$language] : $language;

            $enhanced_prompt = "[LANGUAGE INSTRUCTION - MUST FOLLOW]\n";
            $enhanced_prompt .= "You MUST write ALL content in " . $language_name . " language ONLY.\n";
            $enhanced_prompt .= "Do NOT use any other language. Every word must be in " . $language_name . ".\n";
            $enhanced_prompt .= "If the input is in a different language, still output in " . $language_name . ".\n\n";

            $enhanced_prompt .= "[CLIENT INFORMATION]\n";
            $enhanced_prompt .= $prompt . "\n\n";

            if (!empty($custom_name)) {
                $enhanced_prompt .= "[PAGE DETAILS]\n";
                $enhanced_prompt .= "Page name: " . $custom_name . "\n";
                $enhanced_prompt .= "Generate content appropriate for this page name and purpose.\n";
            }

            if ($editor === 'elementor') {
                $processor = new AI_Magic_Elementor_Processor();
                $elements = $processor->get_raw_data($page_id);

                if (!empty($elements)) {
                    $texts = array();
                    $texts = $processor->extract_texts($elements, $texts);

                    if (!empty($texts)) {
                        // Get first text for before/after display
                        $first_text = reset($texts);
                        $old_text = isset($first_text['value']) ? mb_substr($first_text['value'], 0, 100) : '';

                        $new_values = $ai->rewrite_texts($texts, $enhanced_prompt, $custom_name);
                        $total_cost = $ai->get_last_cost();

                        if (!empty($new_values)) {
                            $first_new = reset($new_values);
                            $new_text = mb_substr($first_new, 0, 100);

                            $processor->apply_new_texts($texts, $new_values);
                            $processor->save_raw_data($page_id, $elements);
                        }
                    }
                }

            } elseif ($editor === 'gutenberg') {
                $processor = new AI_Magic_Gutenberg_Processor();
                $content = $processor->get_content($page_id);
                $texts = $processor->extract_paragraphs($content);

                if (!empty($texts)) {
                    $first_text = reset($texts);
                    $old_text = is_array($first_text) ? mb_substr($first_text['value'] ?? '', 0, 100) : mb_substr($first_text, 0, 100);

                    $new_values = $ai->rewrite_texts($texts, $enhanced_prompt, $custom_name);
                    $total_cost = $ai->get_last_cost();

                    if (!empty($new_values)) {
                        $first_new = reset($new_values);
                        $new_text = mb_substr($first_new, 0, 100);

                        $new_content = $processor->apply_new_paragraphs($content, $texts, $new_values);
                        $processor->save_content($page_id, $new_content);
                    }
                }

            } elseif ($editor === 'wpbakery') {
                $processor = new AI_Magic_WPBakery_Processor();
                $content = $processor->get_content($page_id);
                $texts = $processor->extract_vc_texts($content);

                if (!empty($texts)) {
                    $first_text = reset($texts);
                    $old_text = is_array($first_text) ? mb_substr($first_text['value'] ?? '', 0, 100) : mb_substr($first_text, 0, 100);

                    $new_values = $ai->rewrite_texts($texts, $enhanced_prompt, $custom_name);
                    $total_cost = $ai->get_last_cost();

                    if (!empty($new_values)) {
                        $first_new = reset($new_values);
                        $new_text = mb_substr($first_new, 0, 100);

                        $new_content = $processor->apply_new_vc_texts($content, $texts, $new_values);
                        $processor->save_content($page_id, $new_content);
                    }
                }
            } else {
                // Classic editor - use Classic Processor for HTML preservation
                $processor = new AI_Magic_Classic_Processor();
                $content = $processor->get_content($page_id);

                if (!empty($content)) {
                    $texts = $processor->extract_texts($content);

                    if (!empty($texts)) {
                        $first_text = reset($texts);
                        $old_text = is_array($first_text) ? mb_substr($first_text['value'] ?? '', 0, 100) : mb_substr($first_text, 0, 100);

                        $new_values = $ai->rewrite_texts($texts, $enhanced_prompt, $custom_name);
                        $total_cost = $ai->get_last_cost();

                        if (!empty($new_values)) {
                            $first_new = reset($new_values);
                            $new_text = mb_substr($first_new, 0, 100);

                            $new_content = $processor->apply_new_texts($content, $texts, $new_values);
                            $processor->save_content($page_id, $new_content);

                            // Store for history
                            $result = array(
                                'success' => true,
                                'new_text' => $new_content,
                                'tokens_used' => 0,
                                'generation_time' => 0,
                            );
                        }
                    } else {
                        // Fallback: If no extractable texts, use single rewrite with HTML preservation
                        $old_text = mb_substr($content, 0, 100);

                        $result = $ai->rewrite_text_single($content, $enhanced_prompt, $custom_name);
                        $total_cost = $result['cost'];

                        if ($result['success']) {
                            $new_text = mb_substr($result['new_text'], 0, 100);

                            wp_update_post(array(
                                'ID' => $page_id,
                                'post_content' => $result['new_text'],
                            ));
                        }
                    }
                }
            }

            // Update post title if custom name provided
            if (!empty($custom_name)) {
                wp_update_post(array(
                    'ID' => $page_id,
                    'post_title' => $custom_name,
                ));
            }

            // Save to Generation History with correct title
            $post = get_post($page_id);
            $final_title = !empty($custom_name) ? $custom_name : ($post ? $post->post_title : 'Untitled');
            Ai_Magic_History::save(array(
                'post_id' => $page_id,
                'title' => $final_title,
                'prompt' => $enhanced_prompt,
                'content' => $result['new_text'],
                'model' => $model_id,
                'tokens_used' => isset($result['tokens_used']) ? $result['tokens_used'] : 0,
                'generation_time' => isset($result['generation_time']) ? $result['generation_time'] : 0,
                'cost' => $total_cost,
            ));

            wp_send_json_success(array(
                'old_text' => $old_text,
                'new_text' => $new_text,
                'cost' => $total_cost,
                'edit_url' => get_edit_post_link($page_id, 'raw'),
                'view_url' => get_permalink($page_id),
            ));

        } catch (Exception $e) {
            wp_send_json_error(array('message' => $e->getMessage()));
        }
    }

    /**
     * AJAX: Set stop flag.
     */
    public function ajax_stop()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error();
        }

        set_transient(self::STOP_TRANSIENT, true, 300);
        wp_send_json_success();
    }

    /**
     * AJAX: Check stop flag.
     */
    public function ajax_check_stop()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error();
        }

        $stopped = (bool) get_transient(self::STOP_TRANSIENT);
        wp_send_json_success(array('stopped' => $stopped));
    }

    /**
     * AJAX: Clear stop flag.
     */
    public function ajax_clear_stop()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error();
        }

        delete_transient(self::STOP_TRANSIENT);
        wp_send_json_success();
    }

    /**
     * AJAX: Save wizard state.
     */
    public function ajax_save_state()
    {
        check_ajax_referer('ai_magic_wizard_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied.', 'ai-magic-settings')));
        }

        $state = isset($_POST['state']) ? $_POST['state'] : array();

        // Sanitize state data
        $clean_state = array();
        if (isset($state['step'])) {
            $clean_state['step'] = intval($state['step']);
        }
        if (isset($state['prompt'])) {
            $clean_state['prompt'] = sanitize_textarea_field($state['prompt']);
        }
        if (isset($state['language'])) {
            $clean_state['language'] = sanitize_text_field($state['language']);
        }
        if (isset($state['selectedPages'])) {
            $clean_state['selectedPages'] = $this->sanitize_selected_pages($state['selectedPages']);
        }

        update_option('ai_magic_wizard_state', $clean_state);

        wp_send_json_success();
    }

    /**
     * Sanitize selected pages array.
     */
    private function sanitize_selected_pages($pages)
    {
        if (!is_array($pages)) {
            return array();
        }

        $clean = array();
        foreach ($pages as $id => $data) {
            $clean[intval($id)] = array(
                'id' => intval($data['id']),
                'customName' => isset($data['customName']) ? sanitize_text_field($data['customName']) : ''
            );
        }
        return $clean;
    }
}
