<?php
// SEO Settings UI (using design template)
if ( ! defined( 'ABSPATH' ) ) exit;
// Load saved SEO settings so form reflects persisted values
$settings = get_option('blog82ai_seo_settings', array());
?>
<div class="blog82ai-seo-settings">
    <!-- SEO Performance Overview - moved to top -->
    <div class="blog82ai-seo-performance">
        <h3>SEO Performance Overview</h3>
        <div class="blog82ai-performance-metrics">
            <div class="blog82ai-metric-item">
                <div class="blog82ai-metric-value">87%</div>
                <div class="blog82ai-metric-label">Average SEO Score</div>
                <div class="blog82ai-metric-change positive">+5% this month</div>
            </div>
            <div class="blog82ai-metric-item">
                <div class="blog82ai-metric-value">92%</div>
                <div class="blog82ai-metric-label">Yoast Green Score Rate</div>
                <div class="blog82ai-metric-change positive">+8% this month</div>
            </div>
            <div class="blog82ai-metric-item">
                <div class="blog82ai-metric-value">156</div>
                <div class="blog82ai-metric-label">Optimized Keywords</div>
                <div class="blog82ai-metric-change positive">+23 this month</div>
            </div>
            <div class="blog82ai-metric-item">
                <div class="blog82ai-metric-value">2.3s</div>
                <div class="blog82ai-metric-label">Avg. Page Load Time</div>
                <div class="blog82ai-metric-change negative">+0.2s this month</div>
            </div>
        </div>
    </div>

    <div class="page-header">
        <h2>SEO Settings</h2>
        <p>Configure SEO optimization settings for AI-generated blog posts</p>
    </div>

    <form class="blog82ai-seo-settings-form" id="seoSettingsForm">
        <!-- Global SEO Settings -->
        <div class="blog82ai-settings-section">
            <h3>Global SEO Settings</h3>
            
            <div class="blog82ai-form-group">
                <label for="default-focus-keyphrase">Default Focus Keyphrase Strategy</label>
                <select id="default-focus-keyphrase" name="default_focus_keyphrase">
                    <?php $df = $settings['default_focus_keyphrase'] ?? 'auto'; ?>
                    <option value="auto" <?php echo $df === 'auto' ? 'selected' : ''; ?>>Auto-generate based on category</option>
                    <option value="category-name" <?php echo $df === 'category-name' ? 'selected' : ''; ?>>Use category name</option>
                    <option value="manual" <?php echo $df === 'manual' ? 'selected' : ''; ?>>Require manual input</option>
                    <option value="trending" <?php echo $df === 'trending' ? 'selected' : ''; ?>>Use trending keywords</option>
                </select>
                <small>How to determine focus keyphrases when not manually specified</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="keyphrase-density">Target Keyphrase Density</label>
                <div class="blog82ai-range-input">
                    <input type="range" id="keyphrase-density" name="keyphrase_density" min="0.5" max="3.0" step="0.1" value="<?php echo esc_attr($settings['keyphrase_density'] ?? '1.5'); ?>">
                    <span class="blog82ai-range-value"><?php echo esc_html($settings['keyphrase_density'] ?? '1.5'); ?>%</span>
                </div>
                <small>Recommended: 1.0% - 2.0% for optimal SEO</small>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_meta_title" <?php echo !empty($settings['auto_meta_title']) ? 'checked' : ''; ?>>
                        Auto-generate Meta Titles
                    </label>
                    <small>Generate SEO-optimized meta titles automatically</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_meta_description" <?php echo !empty($settings['auto_meta_description']) ? 'checked' : ''; ?>>
                        Auto-generate Meta Descriptions
                    </label>
                    <small>Generate compelling meta descriptions automatically</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="meta-title-template">Meta Title Template</label>
                <input type="text" id="meta-title-template" name="meta_title_template" value="<?php echo esc_attr($settings['meta_title_template'] ?? '{title} | {site_name}'); ?>" placeholder="{title} | {site_name}">
                <small>Available variables: {title}, {category}, {keyphrase}, {site_name}</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="meta-description-template">Meta Description Template</label>
                <textarea id="meta-description-template" name="meta_description_template" rows="3" placeholder="Learn about {keyphrase} in this comprehensive guide. {excerpt}"><?php echo esc_textarea($settings['meta_description_template'] ?? '{excerpt} Discover expert insights on {keyphrase} and improve your {category} knowledge.'); ?></textarea>
                <small>Available variables: {excerpt}, {keyphrase}, {category}, {title}</small>
            </div>
        </div>

        <!-- Content Optimization -->
        <div class="blog82ai-settings-section">
            <h3>Content Optimization</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_headings" <?php echo !empty($settings['auto_headings']) ? 'checked' : ''; ?>>
                        Auto-optimize Headings (H1, H2, H3)
                    </label>
                    <small>Include focus keyphrase in headings naturally</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_internal_links" <?php echo !empty($settings['auto_internal_links']) ? 'checked' : ''; ?>>
                        Auto-add Internal Links
                    </label>
                    <small>Automatically link to related posts on your site</small>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_alt_text" <?php echo !empty($settings['auto_alt_text']) ? 'checked' : ''; ?>>
                        Auto-generate Image Alt Text
                    </label>
                    <small>Generate SEO-friendly alt text for images</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="auto_schema_markup" <?php echo !empty($settings['auto_schema_markup']) ? 'checked' : ''; ?>>
                        Add Schema Markup
                    </label>
                    <small>Include structured data for better search visibility</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="content-structure">Preferred Content Structure</label>
                <select id="content-structure" name="content_structure">
                    <?php $cs = $settings['content_structure'] ?? 'introduction-body-conclusion'; ?>
                    <option value="introduction-body-conclusion" <?php echo $cs === 'introduction-body-conclusion' ? 'selected' : ''; ?>>Introduction → Body → Conclusion</option>
                    <option value="problem-solution" <?php echo $cs === 'problem-solution' ? 'selected' : ''; ?>>Problem → Solution → Benefits</option>
                    <option value="listicle" <?php echo $cs === 'listicle' ? 'selected' : ''; ?>>Listicle Format</option>
                    <option value="how-to" <?php echo $cs === 'how-to' ? 'selected' : ''; ?>>How-to Guide Format</option>
                    <option value="comparison" <?php echo $cs === 'comparison' ? 'selected' : ''; ?>>Comparison Format</option>
                </select>
            </div>

            <div class="blog82ai-form-group">
                <label for="readability-target">Target Readability Level</label>
                <select id="readability-target" name="readability_target">
                    <?php $rt = $settings['readability_target'] ?? 'medium'; ?>
                    <option value="easy" <?php echo $rt === 'easy' ? 'selected' : ''; ?>>Easy (Grade 6-8)</option>
                    <option value="medium" <?php echo $rt === 'medium' ? 'selected' : ''; ?>>Medium (Grade 9-12)</option>
                    <option value="advanced" <?php echo $rt === 'advanced' ? 'selected' : ''; ?>>Advanced (College Level)</option>
                    <option value="expert" <?php echo $rt === 'expert' ? 'selected' : ''; ?>>Expert (Professional)</option>
                </select>
            </div>
        </div>

        <!-- Keyword Research -->
        <div class="blog82ai-settings-section">
            <h3>Keyword Research & Suggestions</h3>
            
            <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="enable_keyword_research" <?php echo !empty($settings['enable_keyword_research']) ? 'checked' : ''; ?>>
                        Enable Automatic Keyword Research
                    </label>
                <small>Research and suggest related keywords during content generation</small>
            </div>

            <div class="blog82ai-form-group">
                <label for="keyword-sources">Keyword Research Sources</label>
                <div class="blog82ai-checkbox-group">
                    <?php $ks = (array)($settings['keyword_sources'] ?? []); ?>
                    <label><input type="checkbox" name="keyword_sources[]" value="google_trends" <?php echo in_array('google_trends', $ks, true) ? 'checked' : ''; ?>> Google Trends</label>
                    <label><input type="checkbox" name="keyword_sources[]" value="related_searches" <?php echo in_array('related_searches', $ks, true) ? 'checked' : ''; ?>> Related Searches</label>
                    <label><input type="checkbox" name="keyword_sources[]" value="competitor_analysis" <?php echo in_array('competitor_analysis', $ks, true) ? 'checked' : ''; ?>> Competitor Analysis</label>
                    <label><input type="checkbox" name="keyword_sources[]" value="search_console" <?php echo in_array('search_console', $ks, true) ? 'checked' : ''; ?>> Search Console Data</label>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="long-tail-keywords">Long-tail Keyword Strategy</label>
                <select id="long-tail-keywords" name="long_tail_keywords">
                    <?php $lt = $settings['long_tail_keywords'] ?? 'moderate'; ?>
                    <option value="aggressive" <?php echo $lt === 'aggressive' ? 'selected' : ''; ?>>Aggressive (3-5 long-tail keywords)</option>
                    <option value="moderate" <?php echo $lt === 'moderate' ? 'selected' : ''; ?>>Moderate (2-3 long-tail keywords)</option>
                    <option value="conservative" <?php echo $lt === 'conservative' ? 'selected' : ''; ?>>Conservative (1-2 long-tail keywords)</option>
                    <option value="disabled" <?php echo $lt === 'disabled' ? 'selected' : ''; ?>>Disabled</option>
                </select>
            </div>
        </div>

        <!-- Yoast SEO Integration -->
        <div class="blog82ai-settings-section">
            <h3>Yoast SEO Integration</h3>
            
            <div class="blog82ai-integration-status">
                <div class="blog82ai-status-item status-success">
                    <span class="blog82ai-status-icon">✅</span>
                    <span class="blog82ai-status-text">Yoast SEO Plugin: Detected</span>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="yoast_auto_analysis" <?php echo !empty($settings['yoast_auto_analysis']) ? 'checked' : ''; ?>>
                        Auto-run Yoast SEO Analysis
                    </label>
                    <small>Automatically analyze generated content with Yoast SEO</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="yoast_auto_optimize" <?php echo !empty($settings['yoast_auto_optimize']) ? 'checked' : ''; ?>>
                        Auto-optimize Based on Yoast Suggestions
                    </label>
                    <small>Automatically apply Yoast SEO recommendations</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="yoast-score-target">Target Yoast SEO Score</label>
                <select id="yoast-score-target" name="yoast_score_target">
                    <?php $yt = $settings['yoast_score_target'] ?? 'good'; ?>
                    <option value="good" <?php echo $yt === 'good' ? 'selected' : ''; ?>>Good (Green)</option>
                    <option value="ok" <?php echo $yt === 'ok' ? 'selected' : ''; ?>>OK (Orange)</option>
                    <option value="any" <?php echo $yt === 'any' ? 'selected' : ''; ?>>Any Score</option>
                </select>
                <small>Regenerate content if it doesn't meet this score</small>
            </div>
        </div>

        <!-- Advanced SEO Features -->
        <div class="blog82ai-settings-section">
            <h3>Advanced SEO Features</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="canonical_urls" <?php echo !empty($settings['canonical_urls']) ? 'checked' : ''; ?>>
                        Auto-set Canonical URLs
                    </label>
                    <small>Prevent duplicate content issues</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="open_graph" <?php echo !empty($settings['open_graph']) ? 'checked' : ''; ?>>
                        Generate Open Graph Tags
                    </label>
                    <small>Optimize for social media sharing</small>
                </div>
            </div>

            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="twitter_cards" <?php echo !empty($settings['twitter_cards']) ? 'checked' : ''; ?>>
                        Generate Twitter Card Tags
                    </label>
                    <small>Optimize for Twitter sharing</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="breadcrumbs" <?php echo !empty($settings['breadcrumbs']) ? 'checked' : ''; ?>>
                        Add Breadcrumb Navigation
                    </label>
                    <small>Improve site navigation and SEO</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="robots-meta">Default Robots Meta Tag</label>
                <?php $rm = $settings['robots_meta'] ?? 'index,follow'; ?>
                <select id="robots-meta" name="robots_meta">
                    <option value="index,follow" <?php echo $rm === 'index,follow' ? 'selected' : ''; ?>>Index, Follow</option>
                    <option value="index,nofollow" <?php echo $rm === 'index,nofollow' ? 'selected' : ''; ?>>Index, No Follow</option>
                    <option value="noindex,follow" <?php echo $rm === 'noindex,follow' ? 'selected' : ''; ?>>No Index, Follow</option>
                    <option value="noindex,nofollow" <?php echo $rm === 'noindex,nofollow' ? 'selected' : ''; ?>>No Index, No Follow</option>
                </select>
            </div>
        </div>

        <!-- SEO Monitoring -->
        <div class="blog82ai-settings-section">
            <h3>SEO Monitoring & Reporting</h3>
            
            <div class="blog82ai-form-row">
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="seo_monitoring" <?php echo !empty($settings['seo_monitoring']) ? 'checked' : ''; ?>>
                        Enable SEO Performance Monitoring
                    </label>
                    <small>Track SEO performance of generated blogs</small>
                </div>
                <div class="blog82ai-form-group">
                    <label>
                        <input type="checkbox" name="weekly_seo_reports" <?php echo !empty($settings['weekly_seo_reports']) ? 'checked' : ''; ?>>
                        Send Weekly SEO Reports
                    </label>
                    <small>Email weekly SEO performance summaries</small>
                </div>
            </div>

            <div class="blog82ai-form-group">
                <label for="report-email">SEO Report Email</label>
                <input type="email" id="report-email" name="report_email" placeholder="admin@yoursite.com" value="<?php echo esc_attr($settings['report_email'] ?? get_option('admin_email')); ?>">
                <small>Email address to receive SEO reports</small>
            </div>
        </div>

        <!-- Custom SEO Rules -->
        <div class="blog82ai-settings-section">
            <h3>Custom SEO Rules</h3>
            
            <div class="blog82ai-custom-rules">
                <div class="blog82ai-rule-header">
                    <h4>Category-Specific Rules</h4>
                    <button type="button" class="button button-small" onclick="addCategoryRule()">Add Rule</button>
                </div>
                <div class="blog82ai-rules-list" id="categoryRules">
                    <?php
                    $existing_rules = $settings['category_rules'] ?? [];
                    if (empty($existing_rules)) {
                        // Render one empty default rule
                        $existing_rules = [
                            [
                                'category' => 'technology',
                                'keyphrase_suffix' => 'tutorial',
                                'title_prefix' => 'Complete Guide:'
                            ]
                        ];
                    }

                    foreach ($existing_rules as $idx => $r) {
                        $cat = esc_attr($r['category'] ?? 'technology');
                        $suffix = esc_attr($r['keyphrase_suffix'] ?? '');
                        $prefix = esc_attr($r['title_prefix'] ?? '');
                    ?>
                    <div class="blog82ai-rule">
                        <select name="category_rules[<?php echo $idx; ?>][category]">
                            <option value="technology" <?php echo $cat === 'technology' ? 'selected' : ''; ?>>Technology</option>
                            <option value="programming" <?php echo $cat === 'programming' ? 'selected' : ''; ?>>Programming</option>
                            <option value="web-development" <?php echo $cat === 'web-development' ? 'selected' : ''; ?>>Web Development</option>
                            <option value="ai-ml" <?php echo $cat === 'ai-ml' ? 'selected' : ''; ?>>AI &amp; Machine Learning</option>
                            <option value="business" <?php echo $cat === 'business' ? 'selected' : ''; ?>>Business</option>
                            <option value="marketing" <?php echo $cat === 'marketing' ? 'selected' : ''; ?>>Marketing</option>
                        </select>
                        <input type="text" name="category_rules[<?php echo $idx; ?>][keyphrase_suffix]" placeholder="Keyphrase suffix" value="<?php echo $suffix; ?>">
                        <input type="text" name="category_rules[<?php echo $idx; ?>][title_prefix]" placeholder="Title prefix" value="<?php echo $prefix; ?>">
                        <button type="button" class="button button-small" onclick="removeRule(this)">Remove</button>
                    </div>
                    <?php } ?>
                </div>
            </div>
        </div>

        <div class="blog82ai-form-actions">
            <button type="button" class="button" onclick="resetToDefaults()">Reset to Defaults</button>
            <button type="button" class="button button-secondary" onclick="testSeoSettings()">Test Settings</button>
            <button type="submit" class="button button-primary">Save SEO Settings</button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Range input value display
    const rangeInputs = document.querySelectorAll('input[type="range"]');
    rangeInputs.forEach(input => {
        const valueDisplay = input.nextElementSibling;
        input.addEventListener('input', function() {
            valueDisplay.textContent = this.value + '%';
        });
    });

    // Form submission
    document.getElementById('seoSettingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Show loading state
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = 'Saving...';
        submitBtn.disabled = true;
        
            const formData = new FormData(this);
            formData.append('action', 'blog82ai_save_seo_settings');
            formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_seo_settings"); ?>');

            fetch(admin_url_ajax(), {
                method: 'POST',
                body: formData
            })
            .then(resp => resp.json())
            .then(data => {
                if (data && data.success) {
                    if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showSuccess) {
                        Blog82AI_Modal.showSuccess('Saved', 'SEO settings saved successfully!', true);
                    } else {
                        alert('SEO settings saved successfully!');
                    }
                } else {
                    const errMsg = (data && data.data) ? data.data : 'Unknown error';
                    if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showError) {
                        Blog82AI_Modal.showError('Save Failed', errMsg);
                    } else {
                        alert('Failed to save SEO settings: ' + errMsg);
                    }
                }
            })
            .catch(err => {
                console.error('SEO settings save error', err);
                if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showError) {
                    Blog82AI_Modal.showError('Save Error', 'Error saving SEO settings. See console for details.');
                } else {
                    alert('Error saving SEO settings. See console for details.');
                }
            })
            .finally(() => {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            });
    });
    // small helper to get admin-ajax URL (works in admin pages)
    // NOTE: moved to global scope so other global functions can call it
 });

// global helper to get admin-ajax URL (works in admin pages)
function admin_url_ajax() {
    if (typeof ajaxurl !== 'undefined') return ajaxurl;
    return '<?php echo admin_url("admin-ajax.php"); ?>';
}


function addCategoryRule() {
    const rulesContainer = document.getElementById('categoryRules');
    const ruleCount = rulesContainer.children.length;
    
    const newRule = document.createElement('div');
    newRule.className = 'blog82ai-rule';
    newRule.innerHTML = `
        <select name="category_rules[${ruleCount}][category]">
            <option value="technology">Technology</option>
            <option value="programming">Programming</option>
            <option value="web-development">Web Development</option>
            <option value="ai-ml">AI & Machine Learning</option>
            <option value="business">Business</option>
            <option value="marketing">Marketing</option>
        </select>
        <input type="text" name="category_rules[${ruleCount}][keyphrase_suffix]" placeholder="Keyphrase suffix">
        <input type="text" name="category_rules[${ruleCount}][title_prefix]" placeholder="Title prefix">
        <button type="button" class="button button-small" onclick="removeRule(this)">Remove</button>
    `;
    
    rulesContainer.appendChild(newRule);
}

function removeRule(button) {
    button.parentElement.remove();
}

function resetToDefaults() {
    if (confirm('Reset all SEO settings to default values? This action cannot be undone.')) {
        // Reset form to defaults
        document.getElementById('seoSettingsForm').reset();
        // Reset range slider display
        const rangeInput = document.getElementById('keyphrase-density');
        rangeInput.nextElementSibling.textContent = '1.5%';
        if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showMessage) {
            Blog82AI_Modal.showMessage('Reset', 'SEO settings reset to defaults.', '✅', true, true);
        } else {
            alert('SEO settings reset to defaults.');
        }
    }
}

function testSeoSettings() {
    // Gather form data and submit to test endpoint
    const form = document.getElementById('seoSettingsForm');
    if (!form) {
        alert('Form not found');
        return;
    }

    const submitBtn = form.querySelector('button[onclick="testSeoSettings()"]') || document.querySelector('button.button');
    const originalText = submitBtn ? submitBtn.textContent : null;
    if (submitBtn) { submitBtn.textContent = 'Testing...'; submitBtn.disabled = true; }

    const formData = new FormData(form);
    formData.append('action', 'blog82ai_test_seo_settings');
    formData.append('_wpnonce', '<?php echo wp_create_nonce("blog82ai_seo_settings"); ?>');

    // Show plugin loading modal if available, otherwise create/show an inline fallback modal
    function ensureInlineModals() {
        if (document.getElementById('blog82ai-inline-loading-modal')) return;
        const inlineHTML = `
            <div id="blog82ai-inline-loading-modal" style="display:none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 11000;">
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; width: 360px; text-align: center; box-shadow: 0 8px 32px rgba(0,0,0,0.3);">
                    <div style="font-size:48px; margin-bottom:12px;">⏳</div>
                    <div id="blog82ai-inline-loading-text" style="font-size:16px;color:#333;margin-bottom:6px;">Running SEO tests...</div>
                    <div style="margin-top:12px; width: 100%; height: 6px; background: #f0f0f0; border-radius: 3px; overflow: hidden;"><div style="width:100%;height:100%;background: linear-gradient(90deg,#0073aa,#00a0d2);animation:progressBar 1.5s linear infinite"></div></div>
                </div>
            </div>
            <div id="blog82ai-inline-message-modal" style="display:none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 11001;">
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 24px; border-radius: 8px; width: 420px; max-width: 94%; text-align: left; box-shadow: 0 8px 32px rgba(0,0,0,0.3);">
                    <h3 id="blog82ai-inline-message-title" style="margin:0 0 12px 0; color:#333;">Message</h3>
                    <div id="blog82ai-inline-message-body" style="color:#444; font-size:14px; line-height:1.5;">...</div>
                    <div style="text-align:right; margin-top:14px;"><button type="button" id="blog82ai-inline-message-close" style="padding:8px 14px; background:#0073aa;color:#fff;border-radius:4px;border:0;cursor:pointer;">OK</button></div>
                </div>
            </div>
            <style>@keyframes progressBar{0%{transform:translateX(-100%);}100%{transform:translateX(100%);}}</style>
        `;
        document.body.insertAdjacentHTML('beforeend', inlineHTML);
        document.getElementById('blog82ai-inline-message-close').addEventListener('click', function(){ document.getElementById('blog82ai-inline-message-modal').style.display='none'; });
    }

    const pluginModalAvailable = (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showLoading);
    if (pluginModalAvailable) {
        Blog82AI_Modal.showLoading('Running SEO tests...');
    } else {
        ensureInlineModals();
        document.getElementById('blog82ai-inline-loading-text').textContent = 'Running SEO tests...';
        document.getElementById('blog82ai-inline-loading-modal').style.display = 'block';
    }

    fetch(admin_url_ajax(), {
        method: 'POST',
        body: formData
    })
    .then(resp => resp.json())
    .then(data => {
        if (!data) {
            if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showError) {
                Blog82AI_Modal.showError('SEO Test Error', 'No response from server');
            } else {
                alert('No response from server');
            }
            return;
        }
        if (!data.success) {
            const errMsg = data.data || 'Unknown error';
            if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showError) {
                Blog82AI_Modal.showError('SEO Test Failed', errMsg);
            } else {
                alert('Test failed: ' + errMsg);
            }
            return;
        }

        const checks = data.data.checks || [];
        // Build HTML list of checks
        const msgHtml = checks.map(c => {
            const status = (c.status || 'info').toUpperCase();
            const color = status === 'OK' ? 'green' : (status === 'WARN' ? 'orange' : 'red');
            return `<div style="text-align:left; margin:6px 0;"><strong style=\"color:${color};\">[${status}]</strong> ${c.message}</div>`;
        }).join('');

        if (pluginModalAvailable && typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showMessage) {
            // Show results modal and inject HTML into message body
            Blog82AI_Modal.showMessage('SEO Settings Test Results', '');
            const textEl = document.getElementById('blog82ai-message-text');
            if (textEl) {
                textEl.innerHTML = msgHtml;
            }
        } else {
            // Show inline fallback message modal
            ensureInlineModals();
            document.getElementById('blog82ai-inline-message-title').textContent = 'SEO Settings Test Results';
            document.getElementById('blog82ai-inline-message-body').innerHTML = msgHtml;
            document.getElementById('blog82ai-inline-loading-modal').style.display = 'none';
            document.getElementById('blog82ai-inline-message-modal').style.display = 'block';
        }
    })
    .catch(err => {
        console.error('Test settings error', err);
        if (typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.showError) {
            Blog82AI_Modal.showError('SEO Test Error', 'Error running test. See console for details.');
        } else {
            alert('Error running test. See console for details.');
        }
    })
    .finally(() => {
        if (pluginModalAvailable && typeof Blog82AI_Modal !== 'undefined' && Blog82AI_Modal.closeLoading) {
            Blog82AI_Modal.closeLoading();
        } else {
            const lm = document.getElementById('blog82ai-inline-loading-modal'); if (lm) lm.style.display = 'none';
        }
        if (submitBtn) { submitBtn.textContent = originalText; submitBtn.disabled = false; }
    });
}
</script>
