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

// Get current settings
$ai_magic_api_key = get_option('ai_magic_api_key', '');
$ai_magic_model = get_option('ai_magic_model', 'gpt-3.5-turbo');
$ai_magic_writing_language = get_option('ai_magic_writing_language', 'en');
$ai_magic_writing_style = get_option('ai_magic_writing_style', 'informative');
$ai_magic_writing_tone = get_option('ai_magic_writing_tone', 'professional');
$ai_magic_active_provider = get_option('ai_magic_active_provider', 'openai');

// Provider-specific configs
$provider_config = [
    'openai' => [
        'name' => 'OpenAI',
        'desc' => 'Industry standard GPT models',
        'logo_bg' => '#10a37f',
        'logo_svg' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z" fill="#ffffff"/></svg>',
        'logo_text' => '',
        'link' => 'https://platform.openai.com/api-keys',
        'placeholder' => 'sk-proj-...'
    ],
    'anthropic' => [
        'name' => 'Anthropic',
        'desc' => 'High-level reasoning & coding',
        'logo_bg' => '#d97757',
        'logo_svg' => '',
        'logo_text' => 'A',
        'link' => 'https://console.anthropic.com/settings/keys',
        'placeholder' => 'sk-ant-...'
    ],
    'google' => [
        'name' => 'Google AI',
        'desc' => 'Fast & multimodal models',
        'logo_bg' => '#4285f4',
        'logo_svg' => '',
        'logo_text' => 'G',
        'link' => 'https://aistudio.google.com/app/apikey',
        'placeholder' => 'AIza...'
    ],
    'openrouter' => [
        'name' => 'OpenRouter',
        'desc' => 'Aggregator for top open models',
        'logo_bg' => '#6366f1',
        'logo_svg' => '',
        'logo_text' => 'O',
        'link' => 'https://openrouter.ai/keys',
        'placeholder' => 'sk-or-...'
    ]
];

// Provider-specific settings
$providers = ['openai', 'anthropic', 'google', 'openrouter'];
$provider_settings = [];
foreach ($providers as $provider) {
    $provider_settings[$provider] = [
        'active' => get_option("ai_magic_{$provider}_active", $provider === 'openai' ? 'yes' : 'no'),
        'language' => get_option("ai_magic_{$provider}_language", 'en'),
        'style' => get_option("ai_magic_{$provider}_style", 'informative'),
        'tone' => get_option("ai_magic_{$provider}_tone", 'professional')
    ];
}

// Model pricing and info (Updated December 2025)
$models = [
    'recommended' => [
        [
            'id' => 'gpt-4o-mini',
            'name' => 'GPT-4o Mini',
            'description' => 'Best value - Fast and affordable',
            'cost_per_article' => '$0.01 - $0.03',
            'cost_input' => '$0.00015/1K',
            'cost_output' => '$0.0006/1K',
            'speed' => 'Very Fast',
            'quality' => 'Excellent',
            'context_window' => '128K',
            'badge' => 'Recommended',
            'badge_color' => '#10b981'
        ],
        [
            'id' => 'gpt-4o',
            'name' => 'GPT-4o',
            'description' => 'Most advanced, multimodal flagship model',
            'cost_per_article' => '$0.05 - $0.15',
            'cost_input' => '$0.0025/1K',
            'cost_output' => '$0.01/1K',
            'speed' => 'Fast',
            'quality' => 'Best',
            'context_window' => '128K',
            'badge' => 'Flagship',
            'badge_color' => '#8b5cf6'
        ],
        [
            'id' => 'o3-mini',
            'name' => 'o3 Mini',
            'description' => 'Latest reasoning model - Cost effective',
            'cost_per_article' => '$0.02 - $0.06',
            'cost_input' => '$0.0011/1K',
            'cost_output' => '$0.0044/1K',
            'speed' => 'Fast',
            'quality' => 'Excellent',
            'context_window' => '128K',
            'badge' => 'New',
            'badge_color' => '#06b6d4'
        ]
    ],
    'premium' => [
        [
            'id' => 'gpt-5',
            'name' => 'GPT-5',
            'description' => 'Next-gen reasoning and AGI capabilities',
            'cost_per_article' => '$0.20 - $0.60',
            'cost_input' => '$0.03/1K',
            'cost_output' => '$0.12/1K',
            'speed' => 'Moderate',
            'quality' => 'Ultimate',
            'context_window' => '256K',
            'badge' => 'AGI',
            'badge_color' => '#000000'
        ],
        [
            'id' => 'gpt-4-turbo',
            'name' => 'GPT-4 Turbo',
            'description' => 'Advanced reasoning and creativity',
            'cost_per_article' => '$0.10 - $0.30',
            'cost_input' => '$0.01/1K',
            'cost_output' => '$0.03/1K',
            'speed' => 'Fast',
            'quality' => 'Superior',
            'context_window' => '128K',
            'badge' => 'Premium',
            'badge_color' => '#8b5cf6'
        ],
        [
            'id' => 'o1-preview',
            'name' => 'o1 Preview',
            'description' => 'Advanced reasoning for complex tasks',
            'cost_per_article' => '$0.15 - $0.45',
            'cost_input' => '$0.015/1K',
            'cost_output' => '$0.06/1K',
            'speed' => 'Moderate',
            'quality' => 'Superior',
            'context_window' => '128K',
            'badge' => 'Reasoning',
            'badge_color' => '#ef4444'
        ],
        [
            'id' => 'o1-mini',
            'name' => 'o1 Mini',
            'description' => 'Fast reasoning for coding and math',
            'cost_per_article' => '$0.03 - $0.10',
            'cost_input' => '$0.003/1K',
            'cost_output' => '$0.012/1K',
            'speed' => 'Fast',
            'quality' => 'Excellent',
            'context_window' => '128K',
            'badge' => 'Reasoning',
            'badge_color' => '#f97316'
        ]
    ]
];

// Anthropic Models (Updated December 2025)
$anthropic_models = [
    [
        'id' => 'claude-4-5-opus',
        'name' => 'Claude 4.5 Opus',
        'description' => 'Unmatched reasoning and creative writing',
        'cost_per_article' => '$0.25 - $0.75',
        'cost_input' => '$0.025/1K',
        'cost_output' => '$0.10/1K',
        'speed' => 'Moderate',
        'quality' => 'Ultimate',
        'context_window' => '500K',
        'badge' => 'New',
        'badge_color' => '#d97757'
    ],
    [
        'id' => 'claude-3-5-sonnet-20241022',
        'name' => 'Claude 3.5 Sonnet',
        'description' => 'Excellent reasoning and coding',
        'cost_per_article' => '$0.03 - $0.10',
        'cost_input' => '$0.003/1K',
        'cost_output' => '$0.015/1K',
        'speed' => 'Fast',
        'quality' => 'Superior',
        'context_window' => '200K',
        'badge' => 'Recommended',
        'badge_color' => '#d97757'
    ],
    [
        'id' => 'claude-3-5-haiku-20241022',
        'name' => 'Claude 3.5 Haiku',
        'description' => 'Fast and cost-effective',
        'cost_per_article' => '$0.01 - $0.03',
        'cost_input' => '$0.0008/1K',
        'cost_output' => '$0.004/1K',
        'speed' => 'Very Fast',
        'quality' => 'Excellent',
        'context_window' => '200K',
        'badge' => 'Economic',
        'badge_color' => '#10b981'
    ],
    [
        'id' => 'claude-3-opus-20240229',
        'name' => 'Claude 3 Opus',
        'description' => 'Most capable Claude model',
        'cost_per_article' => '$0.15 - $0.50',
        'cost_input' => '$0.015/1K',
        'cost_output' => '$0.075/1K',
        'speed' => 'Moderate',
        'quality' => 'Best',
        'context_window' => '200K',
        'badge' => 'Pro',
        'badge_color' => '#8b5cf6'
    ]
];

// Google Models (Updated December 2025)
$google_models = [
    [
        'id' => 'gemini-3-0-pro',
        'name' => 'Gemini 3.0 Pro',
        'description' => 'Next generation multimodal reasoning',
        'cost_per_article' => '$0.05 - $0.15',
        'cost_input' => '$0.005/1K',
        'cost_output' => '$0.02/1K',
        'speed' => 'Fast',
        'quality' => 'Ultimate',
        'context_window' => '5M',
        'badge' => 'New',
        'badge_color' => '#4285f4'
    ],
    [
        'id' => 'gemini-2.0-flash-exp',
        'name' => 'Gemini 2.0 Flash',
        'description' => 'Latest experimental model - Free trial',
        'cost_per_article' => 'Free (Trial)',
        'cost_input' => 'Free',
        'cost_output' => 'Free',
        'speed' => 'Very Fast',
        'quality' => 'Excellent',
        'context_window' => '1M',
        'badge' => 'New',
        'badge_color' => '#06b6d4'
    ],
    [
        'id' => 'gemini-1.5-pro',
        'name' => 'Gemini 1.5 Pro',
        'description' => 'Advanced multimodal capabilities',
        'cost_per_article' => '$0.02 - $0.06',
        'cost_input' => '$0.00125/1K',
        'cost_output' => '$0.005/1K',
        'speed' => 'Fast',
        'quality' => 'Superior',
        'context_window' => '2M',
        'badge' => 'Pro',
        'badge_color' => '#4285f4'
    ],
    [
        'id' => 'gemini-1.5-flash',
        'name' => 'Gemini 1.5 Flash',
        'description' => 'Fast and cost-effective',
        'cost_per_article' => '$0.005 - $0.02',
        'cost_input' => '$0.000075/1K',
        'cost_output' => '$0.0003/1K',
        'speed' => 'Very Fast',
        'quality' => 'Excellent',
        'context_window' => '1M',
        'badge' => 'Economic',
        'badge_color' => '#10b981'
    ]
];

// Languages
$languages = [
    'en' => ['name' => 'English', 'flag' => '🇬🇧'],
    'tr' => ['name' => 'Turkish', 'flag' => '🇹🇷'],
    'es' => ['name' => 'Spanish', 'flag' => '🇪🇸'],
    'fr' => ['name' => 'French', 'flag' => '🇫🇷'],
    'de' => ['name' => 'German', 'flag' => '🇩🇪'],
    'it' => ['name' => 'Italian', 'flag' => '🇮🇹'],
    'pt' => ['name' => 'Portuguese', 'flag' => '🇵🇹'],
    'nl' => ['name' => 'Dutch', 'flag' => '🇳🇱'],
    'ru' => ['name' => 'Russian', 'flag' => '🇷🇺'],
    'ja' => ['name' => 'Japanese', 'flag' => '🇯🇵'],
    'zh' => ['name' => 'Chinese', 'flag' => '🇨🇳'],
    'ar' => ['name' => 'Arabic', 'flag' => '🇸🇦']
];

// Styles
$styles = [
    'informative' => ['name' => 'Informative', 'icon' => '📚', 'desc' => 'Educational and factual'],
    'creative' => ['name' => 'Creative', 'icon' => '🎨', 'desc' => 'Imaginative and unique'],
    'persuasive' => ['name' => 'Persuasive', 'icon' => '💡', 'desc' => 'Convincing and compelling'],
    'descriptive' => ['name' => 'Descriptive', 'icon' => '🖼️', 'desc' => 'Detailed and vivid'],
    'narrative' => ['name' => 'Narrative', 'icon' => '📖', 'desc' => 'Story-driven']
];

// Tones
$tones = [
    'professional' => ['name' => 'Professional', 'icon' => '💼'],
    'casual' => ['name' => 'Casual', 'icon' => '😊'],
    'friendly' => ['name' => 'Friendly', 'icon' => '🤝'],
    'formal' => ['name' => 'Formal', 'icon' => '🎩'],
    'enthusiastic' => ['name' => 'Enthusiastic', 'icon' => '🎉']
];


?>
<script>
    var aiMagicSettings = {
        settingsNonce: "<?php echo esc_js(wp_create_nonce('ai_magic_settings_nonce')); ?>",
        generateNonce: "<?php echo esc_js(wp_create_nonce('ai_magic_generate_nonce')); ?>"
    };
</script>


<div class="ai-magic-modern-settings">
    <!-- Modern Minimalist Header -->
    <div class="ai-magic-settings-header-minimal">
        <div class="header-content">
            <h1>Settings</h1>
            <p>AI Magic configuration & preferences</p>
        </div>
        <button type="button" id="ai-magic-save-settings" class="ai-magic-btn-save">
            <span class="dashicons dashicons-saved"></span> Save Changes
        </button>
    </div>

    <div id="ai-magic-message"></div>

    <form id="ai-magic-settings-form">
        <?php wp_nonce_field('ai_magic_settings_nonce', 'ai_magic_nonce'); ?>

        <!-- Global Settings -->
        <div class="ai-magic-settings-section" style="margin-bottom: 30px;">
            <div class="ai-magic-section-header">
                <h2>🌐 Global AI Settings</h2>
                <p>Choose your primary AI provider and general writing preferences</p>
            </div>

            <div class="ai-magic-card">
                <div class="ai-magic-form-group">
                    <label><?php esc_html_e('Primary AI Provider', 'ai_magic'); ?></label>
                    <p class="description">
                        <?php esc_html_e('This provider will be used as the default for content generation across the site.', 'ai_magic'); ?>
                    </p>
                    <select name="ai_magic_active_provider" id="ai_magic_active_provider" class="ai-magic-input"
                        style="max-width: 400px; margin-top: 10px;">
                        <?php
                        foreach ($provider_config as $key => $config):
                            $is_active = $provider_settings[$key]['active'] === 'yes';
                            ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($ai_magic_active_provider, $key); ?>>
                                <?php echo esc_html($config['name']); ?>
                                <?php echo $is_active ? '' : '(' . __('Disabled', 'ai_magic') . ')'; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- AI Providers & Preferences -->
        <div class="ai-magic-settings-section">
            <div class="ai-magic-section-header">
                <h2>🤖 AI Providers &amp; Preferences</h2>
                <p>Configure your AI providers and their specific writing styles</p>
            </div>

            <div class="ai-magic-providers-grid">
                <?php
                foreach ($provider_config as $key => $config):
                    $settings = $provider_settings[$key];
                    // Get provider-specific advanced settings
                    $provider_model = get_option("ai_magic_{$key}_model", '');
                    $provider_max_tokens = get_option("ai_magic_{$key}_max_tokens", 4000);
                    $provider_temperature = get_option("ai_magic_{$key}_temperature", 0.7);
                    ?>
                    <div class="ai-magic-provider-card <?php echo $settings['active'] === 'yes' ? 'active' : ''; ?>">
                        <div class="ai-magic-provider-header">
                            <div class="ai-magic-provider-logo"
                                style="background: <?php echo $config['logo_bg']; ?>; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 20px; color: #fff;">
                                <?php echo $config['logo_svg'] ? $config['logo_svg'] : $config['logo_text']; ?>
                            </div>
                            <div style="flex-grow: 1;">
                                <h3><?php echo $config['name']; ?></h3>
                                <small><?php echo $config['desc']; ?></small>
                            </div>
                            <div class="ai-magic-toggle">
                                <label class="switch">
                                    <input type="checkbox" name="ai_magic_<?php echo $key; ?>_active" value="yes" <?php checked($settings['active'], 'yes'); ?> class="ai-magic-provider-toggle">
                                    <span class="slider round"></span>
                                </label>
                            </div>
                        </div>

                        <div class="ai-magic-form-group">
                            <label>API Key</label>
                            <div class="ai-magic-input-wrapper-slim">
                                <input type="password" name="ai_magic_api_key_<?php echo $key; ?>"
                                    id="ai_magic_api_key_<?php echo $key; ?>"
                                    value="<?php echo esc_attr(get_option('ai_magic_api_key_' . $key, '')); ?>"
                                    placeholder="<?php echo $config['placeholder']; ?>" class="ai-magic-input">
                                <button type="button" class="ai-magic-btn-test-icon" data-provider="<?php echo $key; ?>"
                                    title="Test Connection">
                                    <span class="dashicons dashicons-yes-alt"></span>
                                </button>
                            </div>
                            <div id="ai-magic-test-result-<?php echo $key; ?>" style="margin-top: 8px; display: none;">
                            </div>
                            <small>
                                <a href="<?php echo $config['link']; ?>" target="_blank">Get API Key →</a>
                            </small>
                        </div>

                        <!-- Provider Specific Preferences -->
                        <div class="ai-magic-provider-prefs"
                            style="<?php echo $settings['active'] === 'yes' ? '' : 'display:none;'; ?>">
                            <hr style="margin: 15px 0; border: 0; border-top: 1px solid #eee;">



                            <!-- User-Friendly Controls -->
                            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-top: 15px;">
                                <div class="ai-magic-form-group">
                                    <label><?php esc_html_e('Content Length', 'ai_magic'); ?></label>
                                    <select class="ai-magic-input ai-magic-length-select"
                                        data-provider="<?php echo $key; ?>">
                                        <option value="short"><?php esc_html_e('Short (~500 words)', 'ai_magic'); ?>
                                        </option>
                                        <option value="medium"><?php esc_html_e('Medium (~1500 words)', 'ai_magic'); ?>
                                        </option>
                                        <option value="long"><?php esc_html_e('Long (~3000 words)', 'ai_magic'); ?></option>
                                        <option value="custom"><?php esc_html_e('Custom', 'ai_magic'); ?></option>
                                    </select>
                                </div>

                                <div class="ai-magic-form-group">
                                    <label><?php esc_html_e('Creativity Level', 'ai_magic'); ?></label>
                                    <select class="ai-magic-input ai-magic-creativity-select"
                                        data-provider="<?php echo $key; ?>">
                                        <option value="precise"><?php esc_html_e('Precise (Fact-based)', 'ai_magic'); ?>
                                        </option>
                                        <option value="balanced"><?php esc_html_e('Balanced (Standard)', 'ai_magic'); ?>
                                        </option>
                                        <option value="creative"><?php esc_html_e('Creative (Engaging)', 'ai_magic'); ?>
                                        </option>
                                        <option value="custom"><?php esc_html_e('Custom', 'ai_magic'); ?></option>
                                    </select>
                                </div>
                            </div>

                            <!-- Advanced Settings Toggle -->
                            <div style="margin-top: 5px; margin-bottom: 15px; text-align: right;">
                                <a href="#" class="ai-magic-toggle-advanced" data-provider="<?php echo $key; ?>"
                                    style="font-size: 12px; text-decoration: none; color: #666;">
                                    <span class="dashicons dashicons-arrow-right-alt2"
                                        style="font-size: 14px; line-height: 1.3;"></span>
                                    <?php esc_html_e('Advanced Settings (Tokens & Temperature)', 'ai_magic'); ?>
                                </a>
                            </div>

                            <!-- Advanced Settings Grid (Hidden) -->
                            <div id="ai-magic-advanced-<?php echo $key; ?>" class="ai-magic-advanced-settings"
                                style="display: none; grid-template-columns: repeat(2, 1fr); gap: 15px; background: #f9f9f9; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                                <div class="ai-magic-form-group" style="margin-bottom: 0;">
                                    <label>Max Tokens</label>
                                    <input type="number" name="ai_magic_<?php echo $key; ?>_max_tokens"
                                        id="ai_magic_<?php echo $key; ?>_max_tokens"
                                        value="<?php echo esc_attr($provider_max_tokens); ?>"
                                        placeholder="<?php echo $key === 'openai' ? '4000' : ($key === 'anthropic' ? '4096' : '2048'); ?>"
                                        class="ai-magic-input ai-magic-token-input" data-provider="<?php echo $key; ?>"
                                        min="100" max="128000">
                                </div>

                                <div class="ai-magic-form-group" style="margin-bottom: 0;">
                                    <label>Temperature (0-2)</label>
                                    <input type="number" name="ai_magic_<?php echo $key; ?>_temperature"
                                        id="ai_magic_<?php echo $key; ?>_temperature"
                                        value="<?php echo esc_attr($provider_temperature); ?>"
                                        placeholder="<?php echo $key === 'openai' ? '0.7' : ($key === 'anthropic' ? '0.5' : '0.9'); ?>"
                                        class="ai-magic-input ai-magic-temp-input" data-provider="<?php echo $key; ?>"
                                        min="0" max="2" step="0.1">
                                </div>
                            </div>

                            <hr style="margin: 15px 0; border: 0; border-top: 1px solid #eee;">

                            <div class="ai-magic-form-group">
                                <label>Default Language</label>
                                <select name="ai_magic_<?php echo $key; ?>_language" class="ai-magic-input">
                                    <?php foreach ($languages as $code => $lang): ?>
                                        <option value="<?php echo esc_attr($code); ?>" <?php selected($settings['language'], $code); ?>>
                                            <?php echo $lang['flag'] . ' ' . $lang['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="ai-magic-form-group">
                                <label>Writing Style</label>
                                <select name="ai_magic_<?php echo $key; ?>_style" class="ai-magic-input">
                                    <?php foreach ($styles as $code => $style): ?>
                                        <option value="<?php echo esc_attr($code); ?>" <?php selected($settings['style'], $code); ?>>
                                            <?php echo $style['icon'] . ' ' . $style['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="ai-magic-form-group">
                                <label>Tone</label>
                                <select name="ai_magic_<?php echo $key; ?>_tone" class="ai-magic-input">
                                    <?php foreach ($tones as $code => $tone): ?>
                                        <option value="<?php echo esc_attr($code); ?>" <?php selected($settings['tone'], $code); ?>>
                                            <?php echo $tone['icon'] . ' ' . $tone['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="ai-magic-info-box">
                <span class="dashicons dashicons-info"></span>
                <div>
                    <strong>Tip:</strong> Each provider has its own model, temperature, and token settings. Configure
                    them independently for optimal results. For example, use lower temperature for factual content and
                    higher for creative writing.
                </div>
            </div>
        </div>

        <!-- Model Selection -->
        <div class="ai-magic-settings-section">
            <div class="ai-magic-section-header">
                <h2>🤖 AI Model</h2>
                <p>Choose the model that fits your needs and budget</p>
            </div>

            <!-- Provider Selection for Models -->
            <div class="ai-magic-provider-tabs" style="margin-bottom: 30px;">
                <button type="button"
                    class="ai-magic-provider-tab <?php echo $ai_magic_active_provider === 'openai' ? 'active' : ''; ?>"
                    data-provider="openai">
                    <span
                        style="display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; background: #2271b1; border-radius: 5px; color: white; font-weight: bold; font-size: 13px; margin-right: 8px;">O</span>
                    OpenAI
                </button>
                <button type="button"
                    class="ai-magic-provider-tab <?php echo $ai_magic_active_provider === 'anthropic' ? 'active' : ''; ?>"
                    data-provider="anthropic">
                    <span
                        style="display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; background: #d97706; border-radius: 5px; color: white; font-weight: bold; font-size: 13px; margin-right: 8px;">A</span>
                    Anthropic
                </button>
                <button type="button"
                    class="ai-magic-provider-tab <?php echo $ai_magic_active_provider === 'google' ? 'active' : ''; ?>"
                    data-provider="google">
                    <span
                        style="display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; background: #059669; border-radius: 5px; color: white; font-weight: bold; font-size: 13px; margin-right: 8px;">G</span>
                    Google AI
                </button>
                <button type="button"
                    class="ai-magic-provider-tab <?php echo $ai_magic_active_provider === 'openrouter' ? 'active' : ''; ?>"
                    data-provider="openrouter">
                    <span
                        style="display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; background: #6366f1; border-radius: 5px; color: white; font-weight: bold; font-size: 13px; margin-right: 8px;">O</span>
                    OpenRouter
                </button>
            </div>

            <!-- OpenAI Models -->
            <?php $openai_selected_model = get_option('ai_magic_openai_model', $ai_magic_model); ?>
            <div id="ai-magic-models-openai"
                class="ai-magic-provider-models-container <?php echo $ai_magic_active_provider === 'openai' ? 'active' : ''; ?>">
                <!-- Recommended Models -->
                <div class="ai-magic-model-category">
                    <h3>Recommended (OpenAI)</h3>
                    <div class="ai-magic-model-grid">
                        <?php foreach ($models['recommended'] as $model): ?>
                            <label
                                class="ai-magic-model-card <?php echo $openai_selected_model === $model['id'] ? 'selected' : ''; ?>">
                                <input type="radio" name="ai_magic_openai_model"
                                    value="<?php echo esc_attr($model['id']); ?>" <?php checked(get_option('ai_magic_openai_model', $ai_magic_model), $model['id']); ?>
                                    class="ai-magic-provider-model-input" data-provider="openai">
                                <div class="ai-magic-model-badge" style="background: <?php echo $model['badge_color']; ?>">
                                    <?php echo $model['badge']; ?>
                                </div>
                                <div class="ai-magic-model-info">
                                    <h4><?php echo $model['name']; ?></h4>
                                    <p><?php echo $model['description']; ?></p>
                                    <div class="ai-magic-model-stats">
                                        <div class="stat">
                                            <span class="label">Cost/Article</span>
                                            <span class="value"><?php echo $model['cost_per_article']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Speed</span>
                                            <span class="value"><?php echo $model['speed']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Quality</span>
                                            <span class="value"><?php echo $model['quality']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Context</span>
                                            <span
                                                class="value"><?php echo isset($model['context_window']) ? $model['context_window'] : 'N/A'; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Premium Models -->
                <div class="ai-magic-model-category">
                    <h3>💎 Premium (OpenAI)</h3>
                    <div class="ai-magic-model-grid">
                        <?php foreach ($models['premium'] as $model): ?>
                            <label
                                class="ai-magic-model-card <?php echo $openai_selected_model === $model['id'] ? 'selected' : ''; ?>">
                                <input type="radio" name="ai_magic_openai_model"
                                    value="<?php echo esc_attr($model['id']); ?>" <?php checked(get_option('ai_magic_openai_model', $ai_magic_model), $model['id']); ?>
                                    class="ai-magic-provider-model-input" data-provider="openai">
                                <div class="ai-magic-model-badge" style="background: <?php echo $model['badge_color']; ?>">
                                    <?php echo $model['badge']; ?>
                                </div>
                                <div class="ai-magic-model-info">
                                    <h4><?php echo $model['name']; ?></h4>
                                    <p><?php echo $model['description']; ?></p>
                                    <div class="ai-magic-model-stats">
                                        <div class="stat">
                                            <span class="label">Cost/Article</span>
                                            <span class="value"><?php echo $model['cost_per_article']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Speed</span>
                                            <span class="value"><?php echo $model['speed']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Quality</span>
                                            <span class="value"><?php echo $model['quality']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Context</span>
                                            <span
                                                class="value"><?php echo isset($model['context_window']) ? $model['context_window'] : 'N/A'; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>


                </div>

                <!-- OpenAI Custom Model -->
                <div class="ai-magic-model-category" style="margin-top: 20px;">
                    <h3>⚙️ Custom OpenAI Model</h3>
                    <div class="ai-magic-card">
                        <div class="ai-magic-form-group">
                            <label>
                                <input type="radio" name="ai_magic_openai_model" value="custom" <?php checked(get_option('ai_magic_openai_model', ''), 'custom'); ?>
                                    id="ai-magic-openai-custom-radio">
                                Use Custom Model ID
                            </label>
                            <div style="position: relative; margin-top: 12px;">
                                <input type="text" id="ai_magic_openai_custom_model" name="ai_magic_openai_custom_model"
                                    value="<?php echo esc_attr(get_option('ai_magic_openai_custom_model', '')); ?>"
                                    placeholder="e.g., gpt-4-turbo-preview, gpt-4o-2024-08-06"
                                    class="ai-magic-input ai-magic-openai-autocomplete" autocomplete="off">
                                <div id="ai-magic-openai-suggestions" class="ai-magic-autocomplete-dropdown"
                                    style="display: none;"></div>
                            </div>
                            <small>
                                Enter any model ID from <a href="https://platform.openai.com/docs/models"
                                    target="_blank">OpenAI Models</a>
                            </small>
                        </div>
                    </div>
                </div>
            </div> <!-- End OpenAI Models -->

            <!-- Anthropic Models -->
            <?php $anthropic_selected_model = get_option('ai_magic_anthropic_model', ''); ?>
            <div id="ai-magic-models-anthropic"
                class="ai-magic-provider-models-container <?php echo $ai_magic_active_provider === 'anthropic' ? 'active' : ''; ?>">
                <div class="ai-magic-model-category">
                    <h3>Anthropic Models</h3>
                    <div class="ai-magic-model-grid">
                        <?php foreach ($anthropic_models as $model): ?>
                            <label
                                class="ai-magic-model-card <?php echo $anthropic_selected_model === $model['id'] ? 'selected' : ''; ?>">
                                <input type="radio" name="ai_magic_anthropic_model"
                                    value="<?php echo esc_attr($model['id']); ?>" <?php checked(get_option('ai_magic_anthropic_model', ''), $model['id']); ?>
                                    class="ai-magic-provider-model-input" data-provider="anthropic">
                                <div class="ai-magic-model-badge" style="background: <?php echo $model['badge_color']; ?>">
                                    <?php echo $model['badge']; ?>
                                </div>
                                <div class="ai-magic-model-info">
                                    <h4><?php echo $model['name']; ?></h4>
                                    <p><?php echo $model['description']; ?></p>
                                    <div class="ai-magic-model-stats">
                                        <div class="stat">
                                            <span class="label">Cost/Article</span>
                                            <span class="value"><?php echo $model['cost_per_article']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Speed</span>
                                            <span class="value"><?php echo $model['speed']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Quality</span>
                                            <span class="value"><?php echo $model['quality']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Context</span>
                                            <span class="value"><?php echo $model['context_window']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Anthropic Custom Model -->
                <div class="ai-magic-model-category" style="margin-top: 20px;">
                    <h3>⚙️ Custom Anthropic Model</h3>
                    <div class="ai-magic-card">
                        <div class="ai-magic-form-group">
                            <label>
                                <input type="radio" name="ai_magic_anthropic_model" value="custom" <?php checked(get_option('ai_magic_anthropic_model', ''), 'custom'); ?>
                                    id="ai-magic-anthropic-custom-radio">
                                Use Custom Model ID
                            </label>
                            <div style="position: relative; margin-top: 12px;">
                                <input type="text" id="ai_magic_anthropic_custom_model"
                                    name="ai_magic_anthropic_custom_model"
                                    value="<?php echo esc_attr(get_option('ai_magic_anthropic_custom_model', '')); ?>"
                                    placeholder="e.g., claude-3-opus-20240229, claude-3-5-sonnet-20240620"
                                    class="ai-magic-input ai-magic-anthropic-autocomplete" autocomplete="off">
                                <div id="ai-magic-anthropic-suggestions" class="ai-magic-autocomplete-dropdown"
                                    style="display: none;"></div>
                            </div>
                            <small>
                                Enter any model ID from <a href="https://docs.anthropic.com/claude/docs/models-overview"
                                    target="_blank">Claude Models Overview</a>
                            </small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Google Models -->
            <?php $google_selected_model = get_option('ai_magic_google_model', ''); ?>
            <div id="ai-magic-models-google"
                class="ai-magic-provider-models-container <?php echo $ai_magic_active_provider === 'google' ? 'active' : ''; ?>">
                <div class="ai-magic-model-category">
                    <h3>Google Models</h3>
                    <div class="ai-magic-model-grid">
                        <?php foreach ($google_models as $model): ?>
                            <label
                                class="ai-magic-model-card <?php echo $google_selected_model === $model['id'] ? 'selected' : ''; ?>">
                                <input type="radio" name="ai_magic_google_model"
                                    value="<?php echo esc_attr($model['id']); ?>" <?php checked(get_option('ai_magic_google_model', ''), $model['id']); ?>
                                    class="ai-magic-provider-model-input" data-provider="google">
                                <div class="ai-magic-model-badge" style="background: <?php echo $model['badge_color']; ?>">
                                    <?php echo $model['badge']; ?>
                                </div>
                                <div class="ai-magic-model-info">
                                    <h4><?php echo $model['name']; ?></h4>
                                    <p><?php echo $model['description']; ?></p>
                                    <div class="ai-magic-model-stats">
                                        <div class="stat">
                                            <span class="label">Cost/Article</span>
                                            <span class="value"><?php echo $model['cost_per_article']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Speed</span>
                                            <span class="value"><?php echo $model['speed']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Quality</span>
                                            <span class="value"><?php echo $model['quality']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Context</span>
                                            <span class="value"><?php echo $model['context_window']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>
                        <?php endforeach; ?>

                    </div>

                    <!-- Google Custom Model -->
                    <div class="ai-magic-model-category" style="margin-top: 20px;">
                        <h3>Custom Google AI Model</h3>
                        <div class="ai-magic-card">
                            <div class="ai-magic-form-group">
                                <label>
                                    <input type="radio" name="ai_magic_google_model" value="custom" <?php checked(get_option('ai_magic_google_model', ''), 'custom'); ?>
                                        id="ai-magic-google-custom-radio">
                                    Use Custom Model ID
                                </label>
                                <div style="position: relative; margin-top: 12px;">
                                    <input type="text" id="ai_magic_google_custom_model"
                                        name="ai_magic_google_custom_model"
                                        value="<?php echo esc_attr(get_option('ai_magic_google_custom_model', '')); ?>"
                                        placeholder="e.g., gemini-1.5-pro, gemini-1.5-flash"
                                        class="ai-magic-input ai-magic-google-autocomplete" autocomplete="off">
                                    <div id="ai-magic-google-suggestions" class="ai-magic-autocomplete-dropdown"
                                        style="display: none;"></div>
                                </div>
                                <small>
                                    Enter any model ID from <a href="https://ai.google.dev/models/gemini"
                                        target="_blank">Google AI Models</a>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- OpenRouter Models -->
            <?php
            $openrouter_selected_model = get_option('ai_magic_openrouter_model', 'openai/gpt-4o');
            $openrouter_models = [
                [
                    'id' => 'openai/gpt-4o',
                    'name' => 'GPT-4o (via OpenRouter)',
                    'description' => 'OpenAI\'s latest flagship model',
                    'cost_per_article' => '$0.05 - $0.15',
                    'speed' => 'Fast',
                    'quality' => 'Best',
                    'context_window' => '128K',
                    'badge' => 'Popular',
                    'badge_color' => '#10a37f'
                ],
                [
                    'id' => 'anthropic/claude-3.5-sonnet',
                    'name' => 'Claude 3.5 Sonnet',
                    'description' => 'Excellent reasoning and coding',
                    'cost_per_article' => '$0.03 - $0.10',
                    'speed' => 'Fast',
                    'quality' => 'Superior',
                    'context_window' => '200K',
                    'badge' => 'Popular',
                    'badge_color' => '#d97757'
                ],
                [
                    'id' => 'google/gemini-2.0-flash-exp:free',
                    'name' => 'Gemini 2.0 Flash (Free)',
                    'description' => 'Free experimental model',
                    'cost_per_article' => 'Free',
                    'speed' => 'Very Fast',
                    'quality' => 'Excellent',
                    'context_window' => '1M',
                    'badge' => 'Free',
                    'badge_color' => '#10b981'
                ],
                [
                    'id' => 'meta-llama/llama-3.3-70b-instruct',
                    'name' => 'Llama 3.3 70B',
                    'description' => 'Meta\'s latest open model',
                    'cost_per_article' => '$0.02 - $0.06',
                    'speed' => 'Fast',
                    'quality' => 'Excellent',
                    'context_window' => '128K',
                    'badge' => 'Open Source',
                    'badge_color' => '#3b82f6'
                ],
                [
                    'id' => 'mistralai/mistral-large',
                    'name' => 'Mistral Large',
                    'description' => 'Powerful multilingual model',
                    'cost_per_article' => '$0.04 - $0.12',
                    'speed' => 'Fast',
                    'quality' => 'Superior',
                    'context_window' => '128K',
                    'badge' => 'Multilingual',
                    'badge_color' => '#f97316'
                ],
                [
                    'id' => 'deepseek/deepseek-chat',
                    'name' => 'DeepSeek Chat',
                    'description' => 'Cost-effective reasoning model',
                    'cost_per_article' => '$0.01 - $0.03',
                    'speed' => 'Fast',
                    'quality' => 'Excellent',
                    'context_window' => '64K',
                    'badge' => 'Economic',
                    'badge_color' => '#06b6d4'
                ],
                [
                    'id' => 'qwen/qwen-2.5-72b-instruct',
                    'name' => 'Qwen 2.5 72B',
                    'description' => 'Alibaba\'s powerful model',
                    'cost_per_article' => '$0.02 - $0.06',
                    'speed' => 'Fast',
                    'quality' => 'Excellent',
                    'context_window' => '128K',
                    'badge' => 'Multilingual',
                    'badge_color' => '#8b5cf6'
                ],
                [
                    'id' => 'nousresearch/hermes-3-llama-3.1-405b:free',
                    'name' => 'Hermes 3 405B (Free)',
                    'description' => 'Largest free model available',
                    'cost_per_article' => 'Free',
                    'speed' => 'Moderate',
                    'quality' => 'Superior',
                    'context_window' => '128K',
                    'badge' => 'Free',
                    'badge_color' => '#10b981'
                ]
            ];
            ?>
            <div id="ai-magic-models-openrouter"
                class="ai-magic-provider-models-container <?php echo $ai_magic_active_provider === 'openrouter' ? 'active' : ''; ?>">
                <div class="ai-magic-model-category">
                    <h3>OpenRouter Models (400+ Available)</h3>
                    <p style="color: #666; margin-bottom: 20px;">Access all major AI models through a single API. <a
                            href="https://openrouter.ai/models" target="_blank">Browse all models →</a></p>
                    <div class="ai-magic-model-grid">
                        <?php foreach ($openrouter_models as $model): ?>
                            <label
                                class="ai-magic-model-card <?php echo $openrouter_selected_model === $model['id'] ? 'selected' : ''; ?>">
                                <input type="radio" name="ai_magic_openrouter_model"
                                    value="<?php echo esc_attr($model['id']); ?>" <?php checked(get_option('ai_magic_openrouter_model', 'openai/gpt-4o'), $model['id']); ?>
                                    class="ai-magic-provider-model-input" data-provider="openrouter">
                                <div class="ai-magic-model-badge" style="background: <?php echo $model['badge_color']; ?>">
                                    <?php echo $model['badge']; ?>
                                </div>
                                <div class="ai-magic-model-info">
                                    <h4><?php echo $model['name']; ?></h4>
                                    <p><?php echo $model['description']; ?></p>
                                    <div class="ai-magic-model-stats">
                                        <div class="stat">
                                            <span class="label">Cost/Article</span>
                                            <span class="value"><?php echo $model['cost_per_article']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Speed</span>
                                            <span class="value"><?php echo $model['speed']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Quality</span>
                                            <span class="value"><?php echo $model['quality']; ?></span>
                                        </div>
                                        <div class="stat">
                                            <span class="label">Context</span>
                                            <span class="value"><?php echo $model['context_window']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                        <div style="margin-top: 20px; display: flex; align-items: center; gap: 10px;">
                            <button type="button" class="ai-magic-btn-secondary ai-magic-fetch-models-btn"
                                data-provider="openrouter">
                                <span class="dashicons dashicons-update"></span> Fetch All Models
                            </button>
                            <small style="color: #666;">Fetch latest models from OpenRouter API</small>
                        </div>
                        <div id="ai-magic-dynamic-models-openrouter" class="ai-magic-model-grid"
                            style="margin-top: 20px; display: grid;">
                            <!-- Dynamically fetched models will appear here -->
                        </div>
                    </div>

                </div>
                <!-- OpenRouter Custom Model with Autocomplete -->
                <div class="ai-magic-model-category" style="margin-top: 20px;">
                    <h3>⚙️ Custom OpenRouter Model</h3>
                    <div class="ai-magic-card">
                        <div class="ai-magic-form-group">
                            <label>
                                <input type="radio" name="ai_magic_openrouter_model" value="custom" <?php checked($openrouter_selected_model, 'custom'); ?>
                                    id="ai-magic-openrouter-custom-radio">
                                Use Custom Model ID
                            </label>
                            <div style="position: relative; margin-top: 12px;">
                                <input type="text" id="ai_magic_openrouter_custom_model"
                                    name="ai_magic_openrouter_custom_model"
                                    value="<?php echo esc_attr(get_option('ai_magic_openrouter_custom_model', '')); ?>"
                                    placeholder="e.g., openai/gpt-4o, anthropic/claude-3.5-sonnet"
                                    class="ai-magic-input ai-magic-openrouter-autocomplete" autocomplete="off">
                                <div id="ai-magic-openrouter-suggestions" class="ai-magic-autocomplete-dropdown"
                                    style="display: none;"></div>
                            </div>
                            <small>
                                Enter any model ID from <a href="https://openrouter.ai/models"
                                    target="_blank">OpenRouter Models</a>.
                                Format: provider/model-name (e.g., meta-llama/llama-3.3-70b-instruct)
                            </small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Provider-specific Cost Estimate Info Boxes -->
            <div id="ai-magic-cost-info-openai"
                class="ai-magic-info-box ai-magic-cost-info <?php echo $ai_magic_active_provider === 'openai' ? 'active' : ''; ?>"
                style="<?php echo $ai_magic_active_provider === 'openai' ? '' : 'display: none;'; ?>">
                <span class="dashicons dashicons-info"></span>
                <div>
                    <strong>Cost Estimate:</strong> Based on ~1000 word article.
                    Actual costs may vary based on article length and complexity.
                    <a href="https://openai.com/pricing" target="_blank">View OpenAI pricing</a>
                </div>
            </div>
            <div id="ai-magic-cost-info-anthropic"
                class="ai-magic-info-box ai-magic-cost-info <?php echo $ai_magic_active_provider === 'anthropic' ? 'active' : ''; ?>"
                style="<?php echo $ai_magic_active_provider === 'anthropic' ? '' : 'display: none;'; ?>">
                <span class="dashicons dashicons-info"></span>
                <div>
                    <strong>Cost Estimate:</strong> Based on ~1000 word article.
                    Claude models offer competitive pricing with excellent quality.
                    <a href="https://www.anthropic.com/pricing" target="_blank">View Anthropic pricing</a>
                </div>
            </div>
            <div id="ai-magic-cost-info-google"
                class="ai-magic-info-box ai-magic-cost-info <?php echo $ai_magic_active_provider === 'google' ? 'active' : ''; ?>"
                style="<?php echo $ai_magic_active_provider === 'google' ? '' : 'display: none;'; ?>">
                <span class="dashicons dashicons-info"></span>
                <div>
                    <strong>Cost Estimate:</strong> Based on ~1000 word article.
                    Gemini Flash offers free tier, Pro has competitive rates.
                    <a href="https://ai.google.dev/pricing" target="_blank">View Google AI pricing</a>
                </div>
            </div>
            <div id="ai-magic-cost-info-openrouter"
                class="ai-magic-info-box ai-magic-cost-info <?php echo $ai_magic_active_provider === 'openrouter' ? 'active' : ''; ?>"
                style="<?php echo $ai_magic_active_provider === 'openrouter' ? '' : 'display: none;'; ?>">
                <span class="dashicons dashicons-info"></span>
                <div>
                    <strong>Cost Estimate:</strong> Based on ~1000 word article.
                    OpenRouter offers unified billing for 400+ models including free options.
                    <a href="https://openrouter.ai/models" target="_blank">View OpenRouter models & pricing</a>
                </div>
            </div>
        </div>
        <br>
        <hr>
        <br>
        <!-- Company Context Profile -->
        <?php
        // Load context class if not already loaded
        if (!class_exists('AI_Magic_Context')) {
            require_once plugin_dir_path(dirname(__FILE__)) . '../includes/class-ai-magic-context.php';
        }
        $base_prompt = AI_Magic_Context::get_base_prompt();
        $has_base_prompt = AI_Magic_Context::has_base_prompt();
        ?>
        <div class="ai-magic-settings-section">
            <div class="ai-magic-section-header">
                <h2><?php esc_html_e('Company Context Profile', 'ai_magic'); ?></h2>
                <p><?php esc_html_e('Define global context that will be automatically included in all AI prompts', 'ai_magic'); ?>
                </p>
            </div>

            <div class="ai-magic-card">
                <div class="ai-magic-context-status <?php echo $has_base_prompt ? 'active' : 'inactive'; ?>">
                    <span class="status-indicator"></span>
                    <span class="status-text">
                        <?php echo $has_base_prompt
                            ? esc_html__('Context Active', 'ai_magic')
                            : esc_html__('No Context Configured', 'ai_magic'); ?>
                    </span>
                    <?php if ($has_base_prompt): ?>
                        <span class="character-count"><?php echo strlen($base_prompt); ?>
                            <?php esc_html_e('characters', 'ai_magic'); ?></span>
                    <?php endif; ?>
                </div>

                <div class="ai-magic-form-group">
                    <label for="ai_magic_base_prompt">
                        <?php esc_html_e('Base Prompt / Company Information', 'ai_magic'); ?>
                        <span class="ai-magic-tooltip"
                            title="<?php esc_attr_e('This context will be automatically prepended to all AI prompts. Include company details, brand voice, and general instructions.', 'ai_magic'); ?>">
                            <span class="dashicons dashicons-info"></span>
                        </span>
                    </label>
                    <textarea id="ai_magic_base_prompt" name="ai_magic_base_prompt"
                        class="ai-magic-input ai-magic-textarea-large" rows="8"
                        placeholder="<?php esc_attr_e('Example: 
Company Name: ABC Construction Inc.
Industry: Construction / Building Services
Location: New York, NY, USA
Phone: +1 (212) 555-1234
Services: Concrete cutting, demolition, renovation
Brand Voice: Professional, reliable, experienced
Additional Instructions: Always mention 25 years of experience. Use formal but friendly tone.', 'ai_magic'); ?>"><?php echo esc_textarea($base_prompt); ?></textarea>
                    <div class="ai-magic-textarea-footer">
                        <small><?php esc_html_e('This information will be included in every content generation request.', 'ai_magic'); ?></small>
                        <span class="ai-magic-char-counter">
                            <span id="base-prompt-char-count"><?php echo strlen($base_prompt); ?></span>
                            <?php esc_html_e('characters', 'ai_magic'); ?>
                        </span>
                    </div>
                </div>

                <div class="ai-magic-info-box" style="margin-top: 15px;">
                    <span class="dashicons dashicons-lightbulb"></span>
                    <div>
                        <strong><?php esc_html_e('Tip:', 'ai_magic'); ?></strong>
                        <?php esc_html_e('Include company name, industry, contact info, brand voice, and any standard instructions. This way you won\'t need to repeat this info for each page.', 'ai_magic'); ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Save Button (Bottom) -->
        <div class="ai-magic-settings-footer">
            <button type="button" id="ai-magic-save-settings-bottom" class="ai-magic-btn-save">
                <span class="dashicons dashicons-saved"></span> Save Changes
            </button>
        </div>
    </form>
</div>

<style>
    .ai-magic-modern-settings {
        max-width: 1200px;
        margin: 20px auto;
        padding: 0 20px;
    }

    /* Header */
    /* Modern Minimalist Header */
    .ai-magic-settings-header-minimal {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        padding: 20px 0;
        border-bottom: 1px solid #f0f0f0;
    }

    .ai-magic-settings-header-minimal h1 {
        margin: 0;
        font-size: 22px;
        font-weight: 600;
        color: #111;
        letter-spacing: -0.01em;
    }

    .ai-magic-settings-header-minimal p {
        margin: 4px 0 0;
        color: #666;
        font-size: 13px;
    }

    .ai-magic-btn-save {
        background: #111;
        color: #fff;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s ease;
    }

    .ai-magic-btn-save:hover {
        background: #333;
        transform: translateY(-1px);
    }

    .ai-magic-btn-save .dashicons {
        font-size: 18px;
        width: 18px;
        height: 18px;
    }

    .ai-magic-settings-footer {
        margin-top: 40px;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;
        display: flex;
        justify-content: flex-end;
    }

    .ai-magic-btn-secondary {
        background: #fff;
        color: #374151;
        border: 1px solid #d1d5db;
        padding: 6px 14px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 6px;
        transition: all 0.2s;
    }

    .ai-magic-btn-secondary:hover {
        background: #f9fafb;
        border-color: #9ca3af;
    }

    .ai-magic-btn-secondary .dashicons {
        font-size: 16px;
        width: 16px;
        height: 16px;
    }

    /* Slim Input & Minimal Test Icon */
    .ai-magic-input-wrapper-slim {
        display: flex;
        gap: 0;
        align-items: center;
        margin-top: 6px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        overflow: hidden;
        background: #fff;
        height: 32px;
        /* Significantly reduced height */
        transition: border-color 0.2s;
    }

    .ai-magic-input-wrapper-slim:focus-within {
        border-color: #2271b1;
    }

    .ai-magic-input-wrapper-slim .ai-magic-input {
        flex: 1;
        border: none !important;
        border-radius: 0 !important;
        margin-bottom: 0 !important;
        box-shadow: none !important;
        height: 100% !important;
        font-size: 13px !important;
        padding: 0 12px !important;
    }

    .ai-magic-btn-test-icon {
        background: #f9fafb;
        border: none;
        border-left: 1px solid #d1d5db;
        width: 38px;
        height: 32px;
        color: #64748b;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        padding: 0;
        flex-shrink: 0;
    }

    .ai-magic-btn-test-icon:hover {
        background: #f1f5f9;
        color: #2271b1;
    }

    .ai-magic-btn-test-icon .dashicons {
        font-size: 16px;
        width: 16px;
        height: 16px;
    }

    .ai-magic-btn-test-icon.success .dashicons {
        color: #16a34a;
    }

    .ai-magic-btn-test-icon.error .dashicons {
        color: #dc2626;
    }

    /* Provider Tabs */
    .ai-magic-provider-tabs {
        display: flex;
        gap: 12px;
        border-bottom: 2px solid #e5e7eb;
        padding-bottom: 0;
    }

    .ai-magic-provider-tab {
        background: transparent;
        border: none;
        border-bottom: 3px solid transparent;
        padding: 12px 24px;
        font-size: 15px;
        font-weight: 500;
        color: #6b7280;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        position: relative;
        bottom: -2px;
    }

    .ai-magic-provider-tab:hover {
        color: #1f2937;
        background: #f9fafb;
    }

    .ai-magic-provider-tab.active {
        color: #2271b1;
        border-bottom-color: #2271b1;
        font-weight: 600;
    }

    .ai-magic-provider-tab svg {
        flex-shrink: 0;
    }

    /* Model Container Visibility */
    .ai-magic-provider-models-container {
        display: none;
    }

    /* Show only OpenAI by default */
    /* Show only OpenAI by default - HANDLED BY CLASS NOW */
    /* #ai-magic-models-openai { display: block; } REMOVED */

    /* JavaScript will toggle these classes */
    .ai-magic-provider-models-container.active {
        display: block !important;
    }

    /* Sections */
    .ai-magic-settings-section {
        margin-bottom: 40px;
    }

    .ai-magic-section-header {
        margin-bottom: 20px;
    }

    .ai-magic-section-header h2 {
        margin: 0 0 6px 0;
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
    }

    .ai-magic-section-header p {
        margin: 0;
        color: #6b7280;
        font-size: 14px;
    }

    /* Cards */
    .ai-magic-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 24px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    }

    /* Form Groups */
    .ai-magic-form-group {
        margin-bottom: 24px;
    }

    .ai-magic-form-group:last-child {
        margin-bottom: 0;
    }

    .ai-magic-form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #374151;
        font-size: 14px;
    }

    .ai-magic-input {
        width: 100%;
        height: 32px;
        padding: 0 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 13px;
        background-color: #fff;
        color: #374151;
        transition: all 0.2s;
    }

    select.ai-magic-input {
        height: 32px !important;
        line-height: 1 !important;
        padding-top: 0 !important;
        padding-bottom: 0 !important;
    }

    textarea.ai-magic-input {
        height: auto !important;
        padding: 12px !important;
    }

    .ai-magic-input:focus {
        outline: none;
        border-color: #2271b1;
        box-shadow: 0 0 0 2px rgba(34, 113, 177, 0.1);
    }

    .ai-magic-form-group small {
        display: block;
        margin-top: 6px;
        color: #6b7280;
        font-size: 13px;
    }

    .ai-magic-form-group small a {
        color: #2271b1;
        text-decoration: none;
    }

    .ai-magic-form-group small a:hover {
        text-decoration: underline;
    }

    /* Company Context Profile */
    .ai-magic-context-status {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 16px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-size: 14px;
        font-weight: 500;
    }

    .ai-magic-context-status.active {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
        border: 1px solid #10b981;
    }

    .ai-magic-context-status.inactive {
        background: #f9fafb;
        border: 1px solid #e5e7eb;
        color: #6b7280;
    }

    .ai-magic-context-status .status-indicator {
        width: 10px;
        height: 10px;
        border-radius: 50%;
    }

    .ai-magic-context-status.active .status-indicator {
        background: #10b981;
        box-shadow: 0 0 8px rgba(16, 185, 129, 0.5);
    }

    .ai-magic-context-status.inactive .status-indicator {
        background: #9ca3af;
    }

    .ai-magic-context-status .status-text {
        flex: 1;
    }

    .ai-magic-context-status .character-count {
        font-size: 12px;
        color: #6b7280;
        background: #fff;
        padding: 4px 10px;
        border-radius: 12px;
    }

    .ai-magic-textarea-large {
        min-height: 180px;
        resize: vertical;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        line-height: 1.6;
    }

    .ai-magic-textarea-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
    }

    .ai-magic-char-counter {
        font-size: 12px;
        color: #6b7280;
        background: #f3f4f6;
        padding: 4px 12px;
        border-radius: 12px;
    }

    .ai-magic-tooltip {
        display: inline-flex;
        align-items: center;
        margin-left: 6px;
        color: #6b7280;
        cursor: help;
    }

    .ai-magic-tooltip .dashicons {
        font-size: 16px;
        width: 16px;
        height: 16px;
    }

    /* Base Prompt Indicator for other pages */
    .ai-magic-base-prompt-indicator {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 10px;
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
        border: 1px solid #10b981;
        border-radius: 6px;
        font-size: 12px;
        color: #047857;
        cursor: help;
        position: relative;
    }

    .ai-magic-base-prompt-indicator.inactive {
        background: #f9fafb;
        border-color: #e5e7eb;
        color: #6b7280;
    }

    .ai-magic-base-prompt-indicator .indicator-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #10b981;
    }

    .ai-magic-base-prompt-indicator.inactive .indicator-dot {
        background: #9ca3af;
    }

    .ai-magic-base-prompt-indicator .tooltip-content {
        display: none;
        position: absolute;
        bottom: calc(100% + 8px);
        left: 50%;
        transform: translateX(-50%);
        background: #1f2937;
        color: #fff;
        padding: 12px 16px;
        border-radius: 8px;
        font-size: 13px;
        line-height: 1.5;
        width: 300px;
        max-width: 90vw;
        z-index: 1000;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        white-space: pre-wrap;
    }

    .ai-magic-base-prompt-indicator .tooltip-content::after {
        content: '';
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        border: 8px solid transparent;
        border-top-color: #1f2937;
    }

    .ai-magic-base-prompt-indicator:hover .tooltip-content {
        display: block;
    }

    /* Provider Cards */
    .ai-magic-providers-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 16px;
    }

    @media (max-width: 1200px) {
        .ai-magic-providers-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 768px) {
        .ai-magic-providers-grid {
            grid-template-columns: 1fr;
        }
    }

    .ai-magic-provider-card {
        background: #fff;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 20px;
        transition: all 0.2s;
    }

    .ai-magic-provider-card:hover {
        border-color: #2271b1;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }

    .ai-magic-provider-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 16px;
    }

    .ai-magic-provider-logo {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f6fc;
    }

    .ai-magic-provider-header h3 {
        margin: 0 0 2px 0;
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
    }

    .ai-magic-provider-header small {
        display: block;
        color: #6b7280;
        font-size: 12px;
    }

    .ai-magic-provider-card .ai-magic-input {
        margin-bottom: 8px;
    }

    .ai-magic-provider-card small {
        display: block;
        font-size: 12px;
    }

    .ai-magic-provider-card small a {
        color: #2271b1;
        text-decoration: none;
        font-weight: 600;
    }

    .ai-magic-provider-card small a:hover {
        text-decoration: underline;
    }

    /* Model Cards */
    .ai-magic-model-category {
        margin-bottom: 30px;
    }

    .ai-magic-model-category h3 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
        color: #374151;
    }

    .ai-magic-model-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 16px;
    }

    .ai-magic-model-card {
        position: relative;
        background: #fff;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 15px;
        cursor: pointer;
        transition: all 0.2s;
        display: block;
    }

    .ai-magic-model-card:hover {
        border-color: #2271b1;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }

    .ai-magic-model-card.selected {
        border-color: #2271b1;
        background: #f0f6fc;
    }

    .ai-magic-model-card input[type="radio"] {
        position: absolute;
        opacity: 0;
    }

    .ai-magic-model-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 10px;
        font-weight: 700;
        color: #fff;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 8px;
    }

    .ai-magic-model-info h4 {
        margin: 0 0 4px 0;
        font-size: 15px;
        font-weight: 600;
        color: #1f2937;
    }

    .ai-magic-model-info p {
        margin: 0 0 12px 0;
        color: #6b7280;
        font-size: 12px;
    }

    .ai-magic-model-stats {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 8px;
    }

    .ai-magic-model-stats .stat {
        text-align: center;
    }

    .ai-magic-model-stats .label {
        display: block;
        font-size: 10px;
        color: #9ca3af;
        margin-bottom: 2px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .ai-magic-model-stats .value {
        display: block;
        font-size: 12px;
        font-weight: 600;
        color: #1f2937;
    }

    .ai-magic-model-check {
        position: absolute;
        top: 12px;
        right: 12px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #2271b1;
        display: none;
        align-items: center;
        justify-content: center;
        color: #fff;
    }

    .ai-magic-model-card.selected .ai-magic-model-check {
        display: flex;
    }

    .ai-magic-model-check .dashicons {
        font-size: 14px;
        width: 14px;
        height: 14px;
    }

    /* Info Box */
    .ai-magic-info-box {
        background: #eff6ff;
        border: 1px solid #bfdbfe;
        border-radius: 6px;
        padding: 12px 16px;
        display: flex;
        gap: 12px;
        margin-top: 16px;
        font-size: 13px;
        color: #1e40af;
    }

    .ai-magic-info-box .dashicons {
        flex-shrink: 0;
        font-size: 20px;
        width: 20px;
        height: 20px;
    }

    .ai-magic-info-box a {
        color: #1e40af;
        font-weight: 600;
        text-decoration: none;
    }

    .ai-magic-info-box a:hover {
        text-decoration: underline;
    }

    /* Option Grid */
    .ai-magic-option-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
        gap: 12px;
    }

    .ai-magic-option-card {
        position: relative;
        background: #fff;
        border: 2px solid #e5e7eb;
        border-radius: 6px;
        padding: 12px;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .ai-magic-option-card:hover {
        border-color: #2271b1;
    }

    .ai-magic-option-card.selected {
        border-color: #2271b1;
        background: #f0f6fc;
    }

    .ai-magic-option-card input[type="radio"] {
        position: absolute;
        opacity: 0;
    }

    .ai-magic-option-card .option-icon {
        font-size: 24px;
        flex-shrink: 0;
    }

    .ai-magic-option-card .option-name {
        font-size: 13px;
        font-weight: 600;
        color: #1f2937;
    }

    .ai-magic-option-card small {
        display: block;
        font-size: 11px;
        color: #6b7280;
        margin-top: 2px;
    }

    /* Footer */
    .ai-magic-settings-footer {
        text-align: center;
        padding-top: 20px;
        border-top: 2px solid #e5e7eb;
    }

    /* Message */
    #ai-magic-message {
        margin-bottom: 20px;
    }

    #ai-magic-message.success {
        background: #d1fae5;
        border: 1px solid #6ee7b7;
        color: #065f46;
        padding: 12px 16px;
        border-radius: 6px;
    }

    #ai-magic-message.error {
        background: #fee2e2;
        border: 1px solid #fca5a5;
        color: #991b1b;
        padding: 12px 16px;
        border-radius: 6px;
    }
</style>

<script>
    jQuery(document).ready(function ($) {
        const aiMagicSettings = {
            settingsNonce: '<?php echo wp_create_nonce("ai_magic_settings_nonce"); ?>'
        };

        // Save settings
        $('#ai-magic-save-settings, #ai-magic-save-settings-bottom').on('click', function () {
            const $btn = $(this);
            const originalText = $btn.html();

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Saving...');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: $('#ai-magic-settings-form').serialize() + '&action=ai_magic_save_settings',
                success: function (response) {
                    if (response.success) {
                        $('#ai-magic-message')
                            .removeClass('error')
                            .addClass('success')
                            .html('✅ Settings saved successfully!')
                            .show();
                    } else {
                        $('#ai-magic-message')
                            .removeClass('success')
                            .addClass('error')
                            .html('❌ ' + response.data)
                            .show();
                    }

                    $btn.prop('disabled', false).html(originalText);

                    // Scroll to message
                    $('html, body').animate({
                        scrollTop: $('#ai-magic-message').offset().top - 100
                    }, 300);

                    // Hide message after 3 seconds
                    setTimeout(function () {
                        $('#ai-magic-message').fadeOut();
                    }, 3000);
                },
                error: function () {
                    $('#ai-magic-message')
                        .removeClass('success')
                        .addClass('error')
                        .html('❌ An error occurred. Please try again.')
                        .show();

                    $btn.prop('disabled', false).html(originalText);
                }
            });
        });

        // Model card selection
        $('.ai-magic-model-card input[type="radio"]').on('change', function () {
            $('.ai-magic-model-card').removeClass('selected');
            $(this).closest('.ai-magic-model-card').addClass('selected');
        });

        // Option card selection
        $('.ai-magic-option-card input[type="radio"]').on('change', function () {
            const name = $(this).attr('name');
            $('input[name="' + name + '"]').closest('.ai-magic-option-card').removeClass('selected');
            $(this).closest('.ai-magic-option-card').addClass('selected');
        });

        // Custom model input
        $('#ai_magic_custom_model').on('focus', function () {
            $('#ai-magic-custom-model-radio').prop('checked', true).trigger('change');
        });

        // Provider Toggle
        $('.ai-magic-provider-toggle').on('change', function () {
            const $card = $(this).closest('.ai-magic-provider-card');
            const $prefs = $card.find('.ai-magic-provider-prefs');

            if ($(this).is(':checked')) {
                $card.addClass('active');
                $prefs.slideDown();
            } else {
                $card.removeClass('active');
                $prefs.slideUp();
            }
        });

        // Fetch Models button
        $('.ai-magic-fetch-models-btn').on('click', function () {
            const $btn = $(this);
            const provider = $btn.data('provider');
            const originalText = $btn.html();
            const $list = $('#ai-magic-dynamic-models-' + provider);

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Fetching...');
            $list.html('<div style="text-align: center; padding: 20px;"><span class="dashicons dashicons-update spin"></span> Loading models...</div>');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ai_magic_get_models',
                    provider: provider,
                    api_key: $('#ai_magic_api_key_' + provider).val(),
                    nonce: aiMagicSettings.settingsNonce
                },
                success: function (response) {
                    $btn.prop('disabled', false).html(originalText);

                    if (response.success) {
                        let html = '';
                        if (Array.isArray(response.data) && response.data.length > 0) {
                            response.data.forEach(function (model) {
                                // Check if model is object or string
                                const modelId = typeof model === 'string' ? model : model.id;
                                const modelName = typeof model === 'string' ? model : (model.name || model.id);

                                html += `
                            <label class="ai-magic-model-card">
                                <input 
                                    type="radio" 
                                    name="ai_magic_${provider}_model" 
                                    value="${modelId}"
                                >
                                <div class="ai-magic-model-info">
                                    <h4>${modelName}</h4>
                                    <p>${modelId}</p>
                                </div>
                                <div class="ai-magic-model-check">
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </label>`;
                            });
                        } else {
                            html = '<div style="grid-column: 1 / -1; padding: 15px; background: #fff3cd; border: 1px solid #ffeeba; border-radius: 4px; color: #856404;">No models found for this provider.</div>';
                        }
                        $list.html(html);
                    } else {
                        $list.html('<div style="grid-column: 1 / -1; padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; color: #721c24;">Error: ' + (response.data || 'Failed to fetch models') + '</div>');
                    }
                },
                error: function () {
                    $btn.prop('disabled', false).html(originalText);
                    $list.html('<div style="grid-column: 1 / -1; padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; color: #721c24;">AJAX error occurred.</div>');
                }
            });
        });

        // Provider Tab Selection Logic
        var $providerTabs = $('.ai-magic-provider-tab');
        if ($providerTabs.length > 0) {
            $providerTabs.on('click', function () {
                var $tab = $(this);
                var selectedProvider = $tab.data('provider');

                // Update active tab button
                $providerTabs.removeClass('active');
                $tab.addClass('active');

                // Update Model Containers
                $('.ai-magic-provider-models-container').removeClass('active');
                $('#ai-magic-models-' + selectedProvider).addClass('active');

                // Update Cost Info Boxes
                $('.ai-magic-cost-info').hide().removeClass('active');
                $('#ai-magic-cost-info-' + selectedProvider).show().addClass('active');
            });

            // Sync Primary Provider Dropdown with Tabs
            $('#ai_magic_active_provider').on('change', function () {
                var selectedProvider = $(this).val();

                // Switch to the selected provider's tab
                $providerTabs.filter('[data-provider="' + selectedProvider + '"]').trigger('click');
            });

            // Trigger click on already active tab to ensure correct initial state
            // (especially for cost info visibility)
            $providerTabs.filter('.active').trigger('click');
        }

        // Provider Card Expand/Collapse Logic
        $('.ai-magic-provider-header').on('click', function (e) {
            // Don't toggle if clicking the switch or its children
            if ($(e.target).closest('.switch').length) return;

            const card = $(this).closest('.ai-magic-provider-card');
            const prefs = card.find('.ai-magic-provider-prefs');
            const isActive = card.hasClass('active');

            // Toggle visibility
            prefs.slideToggle();

            // Note: We don't toggle the 'active' class here because that's controlled by the checkbox
            // The 'active' class controls the styling (border color, etc.)
        });

        // Ensure prefs are visible if provider is active on load
        $('.ai-magic-provider-card.active .ai-magic-provider-prefs').show();

        // Adjust scroll position for sticky header
        const headerHeight = $('.ai-magic-settings-header-minimal').outerHeight() + 20;

        // Handle anchor links or specific section navigation
        $('a[href^="#"]').on('click', function (e) {
            const target = $(this.getAttribute('href'));
            if (target.length) {
                e.preventDefault();
                $('html, body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 500);
            }
        });
        // Ensure prefs are visible if provider is active on load
        $('.ai-magic-provider-card.active .ai-magic-provider-prefs').show();

        // --- New Settings Abstraction Logic ---

        // Toggle Advanced Settings
        $('.ai-magic-toggle-advanced').on('click', function (e) {
            e.preventDefault();
            const provider = $(this).data('provider');
            $('#ai-magic-advanced-' + provider).slideToggle();
        });

        // Creativity Level Logic
        $('.ai-magic-creativity-select').on('change', function () {
            const val = $(this).val();
            const provider = $(this).data('provider');
            const input = $('#ai_magic_' + provider + '_temperature');

            let temp = '';
            if (val === 'precise') temp = 0.2;
            else if (val === 'balanced') temp = 0.7;
            else if (val === 'creative') temp = 1.2;

            if (temp !== '') {
                input.val(temp);
            }
        });

        // Content Length Logic
        $('.ai-magic-length-select').on('change', function () {
            const val = $(this).val();
            const provider = $(this).data('provider');
            const input = $('#ai_magic_' + provider + '_max_tokens');

            let tokens = '';
            if (val === 'short') tokens = 500;
            else if (val === 'medium') tokens = 1500;
            else if (val === 'long') tokens = 3000;

            if (tokens !== '') {
                input.val(tokens);
            }
        });

        // Sync Raw Inputs back to Selectors (if manual edit)
        $('.ai-magic-temp-input').on('input change', function () {
            const provider = $(this).data('provider');
            const val = parseFloat($(this).val());
            const select = $('.ai-magic-creativity-select[data-provider="' + provider + '"]');

            if (val === 0.2) select.val('precise');
            else if (val === 0.7) select.val('balanced');
            else if (val === 1.2) select.val('creative');
            else select.val('custom');
        });

        $('.ai-magic-token-input').on('input change', function () {
            const provider = $(this).data('provider');
            const val = parseInt($(this).val());
            const select = $('.ai-magic-length-select[data-provider="' + provider + '"]');

            if (val === 500) select.val('short');
            else if (val === 1500) select.val('medium');
            else if (val === 3000) select.val('long');
            else select.val('custom');
        });

        // Initialize Selectors on Load
        $('.ai-magic-temp-input').trigger('change');
        $('.ai-magic-token-input').trigger('change');

        // Base Prompt Character Counter
        $('#ai_magic_base_prompt').on('input', function () {
            const charCount = $(this).val().length;
            $('#base-prompt-char-count').text(charCount);

            // Update status indicator
            const $statusContainer = $('.ai-magic-context-status');
            const $statusText = $statusContainer.find('.status-text');
            const $charCounter = $statusContainer.find('.character-count');

            if (charCount > 0) {
                $statusContainer.removeClass('inactive').addClass('active');
                $statusText.text('<?php echo esc_js(__('Context Active', 'ai_magic')); ?>');
                if ($charCounter.length === 0) {
                    $statusContainer.append('<span class="character-count">' + charCount + ' <?php echo esc_js(__('characters', 'ai_magic')); ?></span>');
                } else {
                    $charCounter.text(charCount + ' <?php echo esc_js(__('characters', 'ai_magic')); ?>');
                }
            } else {
                $statusContainer.removeClass('active').addClass('inactive');
                $statusText.text('<?php echo esc_js(__('No Context Configured', 'ai_magic')); ?>');
                $charCounter.remove();
            }
        });

        // API Key Test Button
        $('.ai-magic-btn-test').on('click', function () {
            var $btn = $(this);
            var provider = $btn.data('provider');
            var $input = $('#ai_magic_api_key_' + provider);
            var apiKey = $input.val();
            var $result = $('#ai-magic-test-result-' + provider);

            if (!apiKey) {
                $result.html('<span style="color: #dc2626;">⚠️ Please enter an API key first</span>').show();
                return;
            }

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: rotation 1s infinite linear;"></span> Testing...');

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'ai_magic_test_api_key',
                    provider: provider,
                    api_key: apiKey,
                    nonce: aiMagicSettings.settingsNonce
                },
                success: function (response) {
                    if (response.success) {
                        $result.html('<span style="color: #16a34a;">✅ ' + response.data.message + '</span>').show();
                        $btn.css('background', '#dcfce7').css('border-color', '#16a34a');
                    } else {
                        $result.html('<span style="color: #dc2626;">❌ ' + response.data.message + '</span>').show();
                        $btn.css('background', '#fef2f2').css('border-color', '#dc2626');
                    }
                },
                error: function () {
                    $result.html('<span style="color: #dc2626;">❌ Connection error</span>').show();
                },
                complete: function () {
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Test');
                }
            });
        });

        // Autocomplete Data
        var openaiModels = [
            'gpt-4o', 'gpt-4o-mini', 'o1-preview', 'o1-mini', 'gpt-4-turbo', 'gpt-4-turbo-preview',
            'gpt-4-0125-preview', 'gpt-4-1106-preview', 'gpt-4', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0125',
            'gpt-4o-2024-05-13', 'gpt-4o-2024-08-06'
        ];

        var openrouterModels = [
            'openai/gpt-4o', 'openai/gpt-4o-mini', 'openai/gpt-4-turbo', 'openai/o1-preview', 'openai/o1-mini',
            'anthropic/claude-3.5-sonnet', 'anthropic/claude-3-opus', 'anthropic/claude-3-haiku',
            'google/gemini-pro-1.5', 'google/gemini-flash-1.5', 'google/gemini-2.0-flash-exp:free',
            'meta-llama/llama-3.3-70b-instruct', 'meta-llama/llama-3.1-405b-instruct', 'meta-llama/llama-3.1-70b-instruct',
            'mistralai/mistral-large', 'mistralai/mixtral-8x22b-instruct', 'mistralai/mistral-7b-instruct',
            'deepseek/deepseek-chat', 'deepseek/deepseek-coder',
            'qwen/qwen-2.5-72b-instruct', 'qwen/qwen-2.5-coder-32b-instruct',
            'nousresearch/hermes-3-llama-3.1-405b:free', 'meta-llama/llama-3.2-3b-instruct:free',
            'cohere/command-r-plus', 'perplexity/llama-3.1-sonar-huge-128k-online'
        ];

        // Autocomplete Logic Function
        function setupAutocomplete(inputSelector, suggestionSelector, models, radioSelector) {
            $(document).on('focus click keyup', inputSelector, function () {
                var input = $(this).val().toLowerCase();
                var $dropdown = $(suggestionSelector);

                // Show all models if input is empty, otherwise filter
                var matches = input.length < 1
                    ? models
                    : models.filter(function (model) {
                        return model.toLowerCase().includes(input);
                    });

                if (matches.length > 0) {
                    var html = matches.slice(0, 15).map(function (model) {
                        return '<div class="ai-magic-autocomplete-item" data-input="' + inputSelector + '" data-suggestion="' + suggestionSelector + '" data-radio="' + radioSelector + '" style="padding: 10px 12px; cursor: pointer; border-bottom: 1px solid #f0f0f0; transition: background 0.2s;">' + model + '</div>';
                    }).join('');
                    $dropdown.html(html).show();
                } else {
                    $dropdown.hide();
                }
            });
        }

        // Initialize Autocomplete for all providers
        setupAutocomplete('#ai_magic_openai_custom_model', '#ai-magic-openai-suggestions', openaiModels, '#ai-magic-openai-custom-radio');
        setupAutocomplete('#ai_magic_openrouter_custom_model', '#ai-magic-openrouter-suggestions', openrouterModels, '#ai-magic-openrouter-custom-radio');

        // Add Anthropic and Google AI models for autocomplete
        var anthropicModels = ['claude-3-5-sonnet-20241022', 'claude-3-5-sonnet-20240620', 'claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307'];
        var googleModels = ['gemini-2.0-flash-exp', 'gemini-1.5-pro', 'gemini-1.5-flash', 'gemini-1.0-pro'];

        setupAutocomplete('#ai_magic_anthropic_custom_model', '#ai-magic-anthropic-suggestions', anthropicModels, '#ai-magic-anthropic-custom-radio');
        setupAutocomplete('#ai_magic_google_custom_model', '#ai-magic-google-suggestions', googleModels, '#ai-magic-google-custom-radio');

        // Handle Item Clicks
        $(document).on('click', '.ai-magic-autocomplete-item', function () {
            var model = $(this).text();
            var inputSelector = $(this).data('input');
            var suggestionSelector = $(this).data('suggestion');
            var radioSelector = $(this).data('radio');

            $(inputSelector).val(model);
            $(suggestionSelector).hide();
            $(radioSelector).prop('checked', true);
        });

        // Close on Outside Click
        $(document).on('click', function (e) {
            if (!$(e.target).closest('.ai-magic-input, .ai-magic-autocomplete-dropdown').length) {
                $('.ai-magic-autocomplete-dropdown').hide();
            }
        });

    });
</script>

<style>
    /* Autocomplete dropdown styles */
    .ai-magic-autocomplete-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #ddd;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        z-index: 1000;
        max-height: 300px;
        overflow-y: auto;
        margin-top: 2px;
    }

    .ai-magic-model-card {
        transition: all 0.3s ease;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    .ai-magic-model-card:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .ai-magic-provider-model-input {
        margin-right: 10px !important;
    }

    .ai-magic-autocomplete-item:hover {
        background: #f0f7ff;
        color: #2271b1;
    }

    .ai-magic-autocomplete-item {
        font-size: 13px;
        color: #444;
    }

    /* Spinning animation for test button */
    @keyframes rotation {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
</style>