<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}
?>

<div class="aysa-dashboard-wrapper">
    <div class="aysa-dashboard-container">
        <!-- Page Title -->
        <div class="aysa-dashboard-header">
            <div class="aysa-dashboard-title">
                <h1>Aysa.ai - Technical Optimization</h1>
                <p>Improve technical aspects of your website for better SEO performance</p>
            </div>
            <div class="aysa-dashboard-user">
                <?php 
                // Use the credits component
                if (class_exists('Aysa_Credits_Component')) {
                    Aysa_Credits_Component::display();
                } else {
                    echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
                }
                ?>
                <!-- <span id="aysa-user-name">User</span> -->
            </div>
        </div>

        <div class="aysa-panel" style="margin-bottom: 16px;">
            <div style="display:flex;gap:10px;align-items:center;justify-content:flex-end;flex-wrap:wrap;">
                <button type="button" id="aysa-download-pagespeed-pdf" class="button" onclick="if(window.aysaRequestPageSpeedDetailedReport){window.aysaRequestPageSpeedDetailedReport(this);} return false;">Download AI Report</button>
                <button type="button" id="aysa-email-pagespeed-pdf" class="button" onclick="if(window.aysaEmailPageSpeedDetailedReport){window.aysaEmailPageSpeedDetailedReport(this);} return false;">Send AI Report</button>
                <button type="button" id="aysa-regenerate-pagespeed-pdf" class="button button-primary" onclick="if(window.aysaRequestPageSpeedDetailedReport){window.aysaRequestPageSpeedDetailedReport(this,{forceRegenerate:true});} return false;">Refresh AI Report</button>
            </div>
        </div>

        <!-- Technical Optimization Sections -->
        <div class="aysa-technical-tabs">
            <div class="aysa-tab-buttons">
                <button class="aysa-tab-btn active" data-target="site-audit">Site Audit</button>
                <button class="aysa-tab-btn" data-target="speed">Google Page Speed</button>
                <button class="aysa-tab-btn" data-target="sitemap">Sitemap + Robots</button>
                <button class="aysa-tab-btn" data-target="errors">Errors</button>
                <button class="aysa-tab-btn" data-target="schema">Schema Markup</button>
                <button class="aysa-tab-btn" data-target="internal-linking">Internal Linking</button>
                <button class="aysa-tab-btn" data-target="agentmarkup">AgentMarkup</button>
            </div>
        </div>

        <div class="aysa-tab-content" id="agentmarkup-content">
            <section class="aysa-panel aysa-agentmarkup" aria-labelledby="aysa-agentmarkup-title">
                <div class="aysa-agentmarkup__intro">
                    <div>
                        <p class="aysa-agentmarkup__eyebrow">Evidence-first AI discoverability</p>
                        <h2 id="aysa-agentmarkup-title" class="aysa-section-title">AYSA AgentMarkup Checker</h2>
                        <p>Run a bounded, read-only check of your homepage, one internal page and key machine-readable signals. The verified AYSA website is used automatically and no website changes are made.</p>
                    </div>
                    <p class="aysa-agentmarkup__license">Independent AYSA implementation inspired by the MIT-licensed <a href="https://github.com/agentmarkup/agentmarkup" target="_blank" rel="noopener noreferrer">AgentMarkup project</a>.</p>
                </div>

                <form id="aysa-agentmarkup-form" class="aysa-agentmarkup__form" aria-busy="false" novalidate>
                    <label for="aysa-agentmarkup-url">Verified website</label>
                    <div class="aysa-agentmarkup__submit-row">
                        <input id="aysa-agentmarkup-url" name="url" type="url" value="<?php echo esc_attr(home_url('/')); ?>" readonly required aria-describedby="aysa-agentmarkup-authorization" />
                        <button id="aysa-agentmarkup-submit" type="submit" class="aysa-btn aysa-btn-primary">Run check</button>
                    </div>
                    <p id="aysa-agentmarkup-authorization" class="aysa-agentmarkup__authorization">Authorization comes from the current AYSA project and verified WordPress site. This diagnostic reads public resources only.</p>
                </form>

                <div id="aysa-agentmarkup-status" class="aysa-agentmarkup__status" role="status" aria-live="polite"></div>

                <div id="aysa-agentmarkup-results" class="aysa-agentmarkup__results" tabindex="-1" hidden>
                    <div class="aysa-agentmarkup__result-head">
                        <div>
                            <span class="aysa-agentmarkup__label">Normalized origin</span>
                            <strong id="aysa-agentmarkup-origin"></strong>
                        </div>
                        <div id="aysa-agentmarkup-counts" class="aysa-agentmarkup__counts" aria-label="Finding totals"></div>
                    </div>
                    <div id="aysa-agentmarkup-groups" class="aysa-agentmarkup__groups"></div>
                    <details class="aysa-agentmarkup__sampled">
                        <summary>Sampled public resources</summary>
                        <ul id="aysa-agentmarkup-sampled-list"></ul>
                    </details>
                </div>
            </section>
        </div>

        <!-- Google Page Speed Section -->
        <div class="aysa-tab-content" id="speed-content">
            <!-- Mesaj AI unificat pentru Website Speed -->
            <!-- AI Message commented out -->
            <!--
            <div class="aysa-global-intro-text" style="background-color:#e6f7ea;display:flex;align-items:center;gap:20px;padding:15px 20px;border-radius:8px;border:1px solid #d1dde5;margin-bottom:20px;max-width:90%;margin-left:auto;margin-right:auto;">
                <img src="<?php echo esc_url((defined('AYSA_PLUGIN_URL') ? AYSA_PLUGIN_URL : plugin_dir_url(dirname(__FILE__, 2))) . 'assets/images/aysa-eyes.png'); ?>" alt="Aysa Eyes" class="aysa-eyes-img" style="width:67px;height:auto;display:block;margin:0;background:#e6f7ea;" />
                <div class="aysa-chat-message aysa-ai-message" style="background-color:#e1f0ff;color:#333;border-bottom-left-radius:0;text-align:center;display:inline-block;width:100%;">
                    <p id="aysa-dynamic-text-speed-intro" style="margin:0;font-size:1.2rem;font-weight:600;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;"></p>
                </div>
            </div>
            -->
            <script type="text/javascript">
                document.addEventListener('DOMContentLoaded', function() {
                    const speedText = "Comprehensive performance analysis and optimization recommendations.\nGenerates detailed technical audit reports for development teams";
                    const speedElem = document.getElementById('aysa-dynamic-text-speed-intro');
                    let idx = 0;
                    function typeWriterSpeed() {
                        if (speedElem && idx < speedText.length) {
                            speedElem.innerHTML += speedText.charAt(idx);
                            idx++;
                            setTimeout(typeWriterSpeed, 30);
                        }
                    }
                    if (speedElem) {
                        speedElem.innerHTML = '';
                        typeWriterSpeed();
                    }
                });
            </script>

            <div class="aysa-panel aysa-site-audit-inline-notice">
                <h2 class="aysa-section-title">Site Audit</h2>
                <p class="aysa-site-audit-subtitle">Full technical crawl moved to dedicated <strong>Site Audit</strong> tab for Overview, Issues, Crawled Pages, and Statistics.</p>
            </div>

            <div class="aysa-panel">
                <h2 class="aysa-section-title">Google Page Speed Optimization</h2>
                
                <div class="aysa-checklist" id="optimization-checklist">
                    <!-- Opportunities will be populated here dynamically -->
                    <div class="aysa-checklist-item aysa-loading-item" id="optimization-loading" style="display: none;">
                        <div class="aysa-loader-small"></div>
                        <div class="aysa-checklist-loading-text">Loading optimization data...</div>
                    </div>
                    <div id="optimization-data" style="display: none;">
                        <!-- Optimization data will be loaded here -->
                    </div>
                </div>
            </div>
            
            <div class="aysa-panel">
                <h2 class="aysa-section-title">Google Page Speed Insights</h2>
                
                <div class="aysa-pagespeed-metrics">
                    <div class="aysa-pagespeed-desktop">
                        <h3 class="aysa-subsection-title">Desktop Results</h3>
                        <table class="aysa-metrics-table">
                            <thead>
                                <tr>
                                    <th>Metric</th>
                                    <th>Value</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="desktop-metrics-tbody">
                                <tr id="desktop-metrics-loading" style="display: none;">
                                    <td colspan="3">
                                        <div class="aysa-table-loading">
                                            <div class="aysa-loader-small"></div>
                                            <span>Loading metrics...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- Running Test button removed as per task requirements -->
                <!--
                <div class="aysa-test-actions">
                    <button id="aysa-run-pagespeed" class="aysa-btn aysa-btn-primary">Run PageSpeed Test</button>
                </div>
                -->
            </div>

            <div class="aysa-panel">
                <h2 class="aysa-section-title">Speed Conclusion</h2>
                <div id="aysa-pagespeed-conclusion" class="aysa-site-audit-message info">
                    Running analysis...
                </div>
            </div>
        </div>

        <div class="aysa-tab-content" id="sitemap-content">
            <div class="aysa-panel aysa-sitemap-robots-panel">
                <h2 class="aysa-section-title">Sitemap + Robots</h2>
                <p class="aysa-site-audit-subtitle">Audit and manage crawl directives safely. Data is cached locally and refreshed only when requested.</p>

                <div class="aysa-site-audit-controls">
                    <button type="button" id="aysa-sitemap-refresh" class="aysa-btn aysa-btn-primary">Run Audit</button>
                    <button type="button" id="aysa-sitemap-generate" class="aysa-btn aysa-btn-secondary">Generate AYSA Sitemap</button>
                    <button type="button" id="aysa-robots-save" class="aysa-btn aysa-btn-secondary">Save robots.txt</button>
                    <button type="button" id="aysa-robots-restore" class="aysa-btn aysa-btn-outline">Restore Recommended</button>
                    <span id="aysa-sitemap-cache-status" class="aysa-site-audit-status-badge is-idle">not loaded</span>
                </div>

                <div id="aysa-sitemap-message" class="aysa-site-audit-message info" style="display:none;"></div>

                <div class="aysa-site-audit-kpis">
                    <div class="aysa-site-audit-kpi">
                        <span class="label">Robots Health</span>
                        <strong id="aysa-robots-health">-</strong>
                    </div>
                    <div class="aysa-site-audit-kpi">
                        <span class="label">Sitemap Health</span>
                        <strong id="aysa-sitemap-health">-</strong>
                    </div>
                    <div class="aysa-site-audit-kpi">
                        <span class="label">Primary Sitemap</span>
                        <strong id="aysa-sitemap-primary-url">-</strong>
                    </div>
                    <div class="aysa-site-audit-kpi">
                        <span class="label">Sitemap Mode</span>
                        <strong id="aysa-sitemap-mode">-</strong>
                    </div>
                    <div class="aysa-site-audit-kpi">
                        <span class="label">robots.txt Source</span>
                        <strong id="aysa-robots-source">-</strong>
                    </div>
                    <div class="aysa-site-audit-kpi">
                        <span class="label">Active Providers</span>
                        <strong id="aysa-sitemap-providers">-</strong>
                    </div>
                </div>

                <div class="aysa-site-audit-grid">
                    <div class="aysa-site-audit-card">
                        <h4>SEO Checks</h4>
                        <div class="aysa-site-audit-table-wrap">
                            <table class="aysa-metrics-table">
                                <thead>
                                    <tr>
                                        <th>Check</th>
                                        <th>Status</th>
                                        <th>Details</th>
                                    </tr>
                                </thead>
                                <tbody id="aysa-sitemap-checks-body">
                                    <tr><td colspan="3">Run audit to load checks.</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="aysa-site-audit-card">
                        <h4>Detected Sitemap Endpoints</h4>
                        <div class="aysa-site-audit-table-wrap">
                            <table class="aysa-metrics-table">
                                <thead>
                                    <tr>
                                        <th>URL</th>
                                        <th>Provider</th>
                                        <th>Status</th>
                                        <th>Entries</th>
                                    </tr>
                                </thead>
                                <tbody id="aysa-sitemap-urls-body">
                                    <tr><td colspan="4">Run audit to load endpoints.</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="aysa-panel" style="margin-top:12px;">
                    <h3 class="aysa-subsection-title">robots.txt Editor</h3>
                    <p style="margin-top:-6px;color:#566882;">Safe defaults are provided. Keep `Sitemap:` visible for search engines.</p>
                    <textarea id="aysa-robots-editor" class="aysa-textarea" rows="14" style="width:100%;font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;" placeholder="User-agent: *&#10;Disallow:"></textarea>
                </div>
            </div>
        </div>

        <!-- Removed Crawling & Indexing, Site Structure, Internal Linking and Structure Data sections as requested -->
        <!-- Site Structure Section (removed) -->
        <div id="structure-content" style="display:none">
            <!-- Mesaj AI unificat pentru Site Structure -->
            <!-- AI Message commented out -->
            <!--
            <div class="aysa-global-intro-text" style="background-color:#e6f7ea;display:flex;align-items:center;gap:20px;padding:15px 20px;border-radius:8px;border:1px solid #d1dde5;margin-bottom:20px;max-width:90%;margin-left:auto;margin-right:auto;">
                <img src="<?php echo esc_url((defined('AYSA_PLUGIN_URL') ? AYSA_PLUGIN_URL : plugin_dir_url(dirname(__FILE__, 2))) . 'assets/images/aysa-eyes.png'); ?>" alt="Aysa Eyes" class="aysa-eyes-img" style="width:67px;height:auto;display:block;margin:0;background:#e6f7ea;" />
                <div class="aysa-chat-message aysa-ai-message" style="background-color:#e1f0ff;color:#333;border-bottom-left-radius:0;text-align:center;display:inline-block;width:100%;">
                    <p id="aysa-dynamic-text-structure-intro" style="margin:0;font-size:1.2rem;font-weight:600;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;"></p>
                </div>
            </div>
            -->
            <script type="text/javascript">
                document.addEventListener('DOMContentLoaded', function() {
                    const structureText = "Intelligent site architecture analysis and optimization\nAutomated sitemap generation and search engine submission\nComprehensive site structure and navigation assessment";
                    const structureElem = document.getElementById('aysa-dynamic-text-structure-intro');
                    let idx = 0;
                    function typeWriterStructure() {
                        if (structureElem && idx < structureText.length) {
                            structureElem.innerHTML += structureText.charAt(idx);
                            idx++;
                            setTimeout(typeWriterStructure, 30);
                        }
                    }
                    if (structureElem) {
                        structureElem.innerHTML = '';
                        typeWriterStructure();
                    }
                });
            </script>
            
            
            <div style="display:none">
                
                <div class="aysa-info-box">
                    <div class="aysa-info-icon"><span class="dashicons dashicons-lightbulb"></span></div>
                    <div class="aysa-info-content">
                        <p><strong>What are Content Silos?</strong> Content siloing is an SEO technique that involves organizing your website content into distinct thematic categories. This helps search engines understand the topic expertise of your site.</p>
                    </div>
                </div>
                
                <div class="aysa-silo-visualization">
                    <div class="aysa-placeholder-silos">
                        <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/content-silos-placeholder.png'); ?>" alt="Content Silos Visualization" onerror="this.src='data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 width%3D%22400%22 height%3D%22200%22%3E%3Crect width%3D%22400%22 height%3D%22200%22 fill%3D%22%23f1f3f4%22%3E%3C%2Frect%3E%3Ctext x%3D%22150%22 y%3D%22100%22 font-family%3D%22sans-serif%22 font-size%3D%2214%22 fill%3D%22%235f6368%22%3EContent Silos Visualization%3C%2Ftext%3E%3C%2Fsvg%3E'">
                    </div>
                </div>
                
                <div class="aysa-silo-stats">
                    <div class="aysa-stat-box">
                        <div class="aysa-stat-value">5</div>
                        <div class="aysa-stat-label">Main Topic Silos</div>
                    </div>
                    <div class="aysa-stat-box">
                        <div class="aysa-stat-value">32</div>
                        <div class="aysa-stat-label">Subtopics</div>
                    </div>
                    <div class="aysa-stat-box">
                        <div class="aysa-stat-value">68%</div>
                        <div class="aysa-stat-label">Silo Strength</div>
                    </div>
                    <div class="aysa-stat-box">
                        <div class="aysa-stat-value">12</div>
                        <div class="aysa-stat-label">Orphaned Content</div>
                    </div>
                </div>
                
                <div class="aysa-table-heading">
                    <h3 class="aysa-subsection-title">Content Silo Analysis</h3>
                </div>
                
                <div class="aysa-table-responsive">
                    <table class="aysa-data-table">
                        <thead>
                            <tr>
                                <th>Topic Silo</th>
                                <th>Content Count</th>
                                <th>Internal Links</th>
                                <th>Health Score</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>SEO Techniques</td>
                                <td>24</td>
                                <td>87</td>
                                <td><span class="aysa-status-label good">Good (92%)</span></td>
                                <td>
                                    <div class="aysa-action-buttons">
                                        <a href="#" class="aysa-btn-small">View Silo</a>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>Content Marketing</td>
                                <td>18</td>
                                <td>64</td>
                                <td><span class="aysa-status-label good">Good (85%)</span></td>
                                <td>
                                    <div class="aysa-action-buttons">
                                        <a href="#" class="aysa-btn-small">View Silo</a>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>Technical SEO</td>
                                <td>12</td>
                                <td>42</td>
                                <td><span class="aysa-status-label average">Average (74%)</span></td>
                                <td>
                                    <div class="aysa-action-buttons">
                                        <a href="#" class="aysa-btn-small">View Silo</a>
                                        <a href="#" class="aysa-btn-small">Improve</a>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>Link Building</td>
                                <td>9</td>
                                <td>28</td>
                                <td><span class="aysa-status-label poor">Poor (58%)</span></td>
                                <td>
                                    <div class="aysa-action-buttons">
                                        <a href="#" class="aysa-btn-small">View Silo</a>
                                        <a href="#" class="aysa-btn-small">Improve</a>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>Analytics & Reporting</td>
                                <td>7</td>
                                <td>22</td>
                                <td><span class="aysa-status-label poor">Poor (42%)</span></td>
                                <td>
                                    <div class="aysa-action-buttons">
                                        <a href="#" class="aysa-btn-small">View Silo</a>
                                        <a href="#" class="aysa-btn-small">Improve</a>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="aysa-tab-content active" id="site-audit-content">
            <div class="postbox">
                <div class="inside">
                    <h2 class="title">Site Audit</h2>
                    <p class="description">Complete technical crawl, issue inventory, and page-level diagnostics for the current website.</p>

                    <p>
                        <button type="button" id="aysa-site-audit-run" class="button button-primary">Run Full Site Audit</button>
                        <button type="button" id="aysa-site-audit-refresh" class="button">Refresh Status</button>
                        <span id="aysa-site-audit-status-badge" class="button button-secondary" aria-disabled="true">idle</span>
                    </p>

                    <div id="aysa-site-audit-message" class="notice inline" style="display:none;"></div>

                    <table class="widefat striped" style="margin-bottom:16px;">
                        <tbody>
                            <tr>
                                <th scope="row">Target</th>
                                <td id="aysa-site-audit-target">-</td>
                                <th scope="row">Job ID</th>
                                <td id="aysa-site-audit-job">-</td>
                                <th scope="row">Last Update</th>
                                <td id="aysa-site-audit-updated">-</td>
                            </tr>
                            <tr>
                                <th scope="row">Mode</th>
                                <td id="aysa-site-audit-mode">baseline_full</td>
                                <th scope="row">Version</th>
                                <td id="aysa-site-audit-version">-</td>
                                <th scope="row">History</th>
                                <td id="aysa-site-audit-history">0 runs</td>
                            </tr>
                        </tbody>
                    </table>

                    <table class="widefat striped" id="aysa-site-audit-kpis" style="margin-bottom:16px;">
                        <thead>
                            <tr>
                                <th>Pages Crawled</th>
                                <th>Site Health</th>
                                <th>Errors</th>
                                <th>Warnings</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td id="aysa-site-audit-pages-crawled">0</td>
                                <td id="aysa-site-audit-site-health">0%</td>
                                <td id="aysa-site-audit-errors">0</td>
                                <td id="aysa-site-audit-warnings">0</td>
                            </tr>
                        </tbody>
                    </table>

                    <nav class="nav-tab-wrapper wp-clearfix" aria-label="Site Audit Sections">
                        <button type="button" class="nav-tab nav-tab-active aysa-site-audit-subtab-btn" data-site-audit-subtab="overview">Overview</button>
                        <button type="button" class="nav-tab aysa-site-audit-subtab-btn" data-site-audit-subtab="issues">Issues</button>
                        <button type="button" class="nav-tab aysa-site-audit-subtab-btn" data-site-audit-subtab="pages">Crawled Pages</button>
                        <button type="button" class="nav-tab aysa-site-audit-subtab-btn" data-site-audit-subtab="stats">Statistics</button>
                    </nav>

                    <div class="aysa-site-audit-subtab-content is-active" id="aysa-site-audit-subtab-overview">
                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Executive Summary</h3>
                                <p><strong>Status:</strong> <span id="aysa-site-audit-conclusion-status" class="button button-secondary" aria-disabled="true">idle</span></p>
                                <p id="aysa-site-audit-conclusion-summary">No baseline conclusion available yet.</p>
                                <table class="widefat striped" style="margin-bottom:16px;">
                                    <tbody>
                                        <tr>
                                            <th scope="row" style="width:180px;">Main Problem</th>
                                            <td id="aysa-site-audit-main-problem">Run a full audit to identify the main issue.</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Why It Matters</th>
                                            <td id="aysa-site-audit-business-impact">The plugin will explain the business impact after the crawl finishes.</td>
                                        </tr>
                                    </tbody>
                                </table>
                                <div class="aysa-site-audit-overview-columns">
                                    <div>
                                        <h4 style="margin-bottom:8px;">What To Do First</h4>
                                        <ol id="aysa-site-audit-conclusion-actions">
                                            <li>Once the crawl finishes, the plugin will summarize the first remediation actions here.</li>
                                        </ol>
                                    </div>
                                    <div>
                                        <h4 style="margin-bottom:8px;">Audit Context</h4>
                                        <ul id="aysa-site-audit-conclusion-context">
                                            <li>Mode: baseline_full</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Recommended Actions</h3>
                                <div id="aysa-site-audit-recommended-actions-list">
                                    <p>No preparation bundles available yet.</p>
                                </div>
                            </div>
                        </div>

                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Technical Summary</h3>
                                <table class="widefat striped">
                                    <thead>
                                        <tr>
                                            <th>Status Codes</th>
                                            <th>Indexability</th>
                                            <th>Crawl Depth</th>
                                            <th>Internal Links</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td><ul id="aysa-site-audit-status-codes"><li>2xx: 0</li><li>3xx: 0</li><li>4xx: 0</li><li>5xx: 0</li></ul></td>
                                            <td><ul id="aysa-site-audit-indexability"><li>Indexable: 0</li><li>Non-indexable: 0</li></ul></td>
                                            <td><ul id="aysa-site-audit-depth"><li>Pages over depth 3: 0</li></ul></td>
                                            <td><ul id="aysa-site-audit-links"><li>Pages with &lt;=1 inlink: 0</li></ul></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="aysa-site-audit-subtab-content" id="aysa-site-audit-subtab-issues">
                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Top Problems</h3>
                                <div id="aysa-site-audit-top-problems-list">
                                    <p>No prioritized issues available yet.</p>
                                </div>
                            </div>
                        </div>

                        <div class="tablenav top aysa-site-audit-issues-toolbar">
                            <div class="alignleft actions">
                                <input type="search" id="aysa-site-audit-issues-search" class="regular-text" placeholder="Search problems or URLs">
                            </div>
                            <div class="alignleft actions" id="aysa-site-audit-severity-filters">
                                <label for="aysa-site-audit-severity-select" class="screen-reader-text">Severity</label>
                                <select id="aysa-site-audit-severity-select">
                                    <option value="all">All severities</option>
                                </select>
                            </div>
                            <div class="alignleft actions" id="aysa-site-audit-category-filters">
                                <label for="aysa-site-audit-category-select" class="screen-reader-text">Category</label>
                                <select id="aysa-site-audit-category-select">
                                    <option value="all">All categories</option>
                                </select>
                            </div>
                            <div class="alignleft actions">
                                <button type="button" class="button" id="aysa-site-audit-issues-reset">Reset filters</button>
                            </div>
                            <div class="alignleft actions">
                                <span id="aysa-site-audit-issues-count" class="description">All issues</span>
                            </div>
                            <br class="clear">
                        </div>

                        <div id="aysa-site-audit-issues-groups">
                            <p>No issues loaded yet.</p>
                        </div>
                    </div>

                    <div class="aysa-site-audit-subtab-content" id="aysa-site-audit-subtab-pages">
                        <div class="tablenav top">
                            <div class="alignleft actions">
                                <input type="search" id="aysa-site-audit-pages-search" class="regular-text" placeholder="Search crawled pages">
                            </div>
                            <div class="alignleft actions" id="aysa-site-audit-page-type-filters">
                                <button type="button" class="button button-secondary is-active" data-filter-type="page-type" data-filter-value="all">Everywhere</button>
                            </div>
                            <br class="clear">
                        </div>

                        <table class="widefat striped">
                            <thead>
                                <tr>
                                    <th>URL</th>
                                    <th>Title</th>
                                    <th>Status Code</th>
                                    <th>Issues</th>
                                    <th>Page Type</th>
                                    <th>Depth</th>
                                    <th>Inlinks</th>
                                </tr>
                            </thead>
                            <tbody id="aysa-site-audit-pages-body">
                                <tr><td colspan="7">No crawled pages loaded yet.</td></tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="aysa-site-audit-subtab-content" id="aysa-site-audit-subtab-stats">
                        <div id="aysa-site-audit-stats-cards">
                            <p>Run a full audit to generate crawl statistics.</p>
                        </div>

                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Export Coverage</h3>
                                <ul id="aysa-site-audit-export-coverage">
                                    <li>Internal: 0</li>
                                    <li>Titles: 0</li>
                                    <li>Meta: 0</li>
                                    <li>H1: 0</li>
                                </ul>
                            </div>
                        </div>

                        <div class="postbox">
                            <div class="inside">
                                <h3 style="margin-top:0;">Generated Files</h3>
                                <table class="widefat striped" id="aysa-site-audit-results-table">
                                    <thead>
                                        <tr>
                                            <th>File</th>
                                            <th>Rows</th>
                                            <th>Size</th>
                                            <th>Updated</th>
                                        </tr>
                                    </thead>
                                    <tbody id="aysa-site-audit-results-body">
                                        <tr><td colspan="4">No audit files generated yet.</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="aysa-site-audit-issue-modal" class="aysa-site-audit-modal" style="display:none;">
            <div class="aysa-site-audit-modal-backdrop"></div>
            <div class="aysa-site-audit-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="aysa-site-audit-modal-title">
                <div class="aysa-site-audit-modal-header">
                    <h3 id="aysa-site-audit-modal-title">Issue Details</h3>
                    <button type="button" class="aysa-site-audit-modal-close" id="aysa-site-audit-modal-close" aria-label="Close">×</button>
                </div>
                <div class="aysa-site-audit-modal-meta">
                    <span id="aysa-site-audit-modal-severity" class="aysa-issue-severity-notice">notice</span>
                    <strong id="aysa-site-audit-modal-affected">0 affected pages</strong>
                    <span id="aysa-site-audit-modal-source"></span>
                </div>
                <p id="aysa-site-audit-modal-description" class="aysa-site-audit-modal-description"></p>
                <div class="aysa-site-audit-modal-table-wrap">
                    <table class="aysa-metrics-table" id="aysa-site-audit-modal-table">
                        <thead id="aysa-site-audit-modal-table-head"></thead>
                        <tbody id="aysa-site-audit-modal-table-body"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Mobile Optimization Section -->
        <div class="aysa-tab-content" id="mobile-content">
            <!-- Mesaj AI unificat pentru Mobile Optimization -->
            <!-- AI Message commented out -->
            <!--
            <div class="aysa-global-intro-text" style="background-color:#e6f7ea;display:flex;align-items:center;gap:20px;padding:15px 20px;border-radius:8px;border:1px solid #d1dde5;margin-bottom:20px;max-width:90%;margin-left:auto;margin-right:auto;">
                <img src="<?php echo esc_url((defined('AYSA_PLUGIN_URL') ? AYSA_PLUGIN_URL : plugin_dir_url(dirname(__FILE__, 2))) . 'assets/images/aysa-eyes.png'); ?>" alt="Aysa Eyes" class="aysa-eyes-img" style="width:67px;height:auto;display:block;margin:0;background:#e6f7ea;" />
                <div class="aysa-chat-message aysa-ai-message" style="background-color:#e1f0ff;color:#333;border-bottom-left-radius:0;text-align:center;display:inline-block;width:100%;">
                    <p id="aysa-dynamic-text-mobile-intro" style="margin:0;font-size:1.2rem;font-weight:600;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;"></p>
                </div>
            </div>
            -->
            <script type="text/javascript">
                document.addEventListener('DOMContentLoaded', function() {
                    const mobileText = "Advanced mobile optimization analysis and recommendations\nResponsive design testing and performance optimization\nMobile-first indexing compatibility assessment";
                    const mobileElem = document.getElementById('aysa-dynamic-text-mobile-intro');
                    let idx = 0;
                    function typeWriterMobile() {
                        if (mobileElem && idx < mobileText.length) {
                            mobileElem.innerHTML += mobileText.charAt(idx);
                            idx++;
                            setTimeout(typeWriterMobile, 30);
                        }
                    }
                    if (mobileElem) {
                        mobileElem.innerHTML = '';
                        typeWriterMobile();
                    }
                });
            </script>
            <div class="aysa-panel">
                <h2 class="aysa-section-title">Mobile Optimization Overview</h2>
                
                <div class="aysa-mobile-overview">
                    <div class="aysa-mobile-score">
                        <div class="aysa-circle-progress">
                            <svg viewBox="0 0 36 36" class="aysa-circular-chart orange">
                                <path class="aysa-circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path>
                                <path class="aysa-circle" stroke-dasharray="60, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path>
                                <text x="18" y="20.35" class="aysa-percentage">60%</text>
                            </svg>
                            <div class="aysa-score-label">Mobile Performance</div>
                        </div>
                    </div>
                    
                    <div class="aysa-mobile-summary">
                        <div class="aysa-info-box warning">
                            <div class="aysa-info-icon"><span class="dashicons dashicons-warning"></span></div>
                            <div class="aysa-info-content">
                                <p><strong>Mobile Optimization Needs Improvement</strong></p>
                                <p>Your website requires optimization for mobile devices. Address the issues below to improve mobile experience and rankings.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Mobile PageSpeed Metrics Panel - REAL DATA -->
            <div class="aysa-panel">
                <h2 class="aysa-section-title">Mobile PageSpeed Metrics</h2>
                <table class="aysa-metrics-table" id="aysa-mobile-metrics-table">
                    <thead>
                        <tr>
                            <th>Metric</th>
                            <th>Value</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody id="mobile-metrics-tbody">
                        <tr id="mobile-metrics-loading" style="display: none;">
                            <td colspan="3">
                                <div class="aysa-table-loading">
                                    <div class="aysa-loader-small"></div>
                                    <span>Loading metrics...</span>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- Mobile PageSpeed Test button removed as per task requirements -->
                <!--
                <div class="aysa-test-actions">
                    <button id="aysa-run-mobile-pagespeed" class="aysa-btn aysa-btn-primary">Run Mobile PageSpeed Test</button>
                </div>
                -->
            </div>
            
            <div class="aysa-panel">
                <h2 class="aysa-section-title">Mobile Experience Preview</h2>
                
                <div class="aysa-mobile-test">
                    <div class="aysa-test-preview">
                        <div class="aysa-device-wrapper">
                            <div class="aysa-mobile-device">
                                <div class="aysa-mobile-screen">
                                    <div class="aysa-mobile-placeholder">
                                        <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/mobile-screen.png'); ?>" alt="Mobile Preview" onerror="this.src='data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 width%3D%22200%22 height%3D%22400%22%3E%3Crect width%3D%22200%22 height%3D%22400%22 fill%3D%22%23f1f3f4%22%3E%3C%2Frect%3E%3Ctext x%3D%2250%22 y%3D%22200%22 font-family%3D%22sans-serif%22 font-size%3D%2214%22 fill%3D%22%235f6368%22%3EMobile Preview%3C%2Ftext%3E%3C%2Fsvg%3E'">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-test-results">
                        <h3 class="aysa-subsection-title">Mobile Optimization Opportunities</h3>
                        
                        <div class="aysa-checklist" id="aysa-mobile-opportunities">
                            <div class="aysa-checklist-item aysa-loading-item" id="mobile-optimization-loading" style="display: none;">
                                <div class="aysa-loader-small"></div>
                                <div class="aysa-checklist-loading-text">Loading optimization data...</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="aysa-tab-content" id="errors-content">
            <div class="aysa-panel">
                <h2 class="aysa-section-title">Errors Hub</h2>
                <p class="aysa-site-audit-subtitle">Unified review for 404 errors, 301 redirects, and 410 rules. Suggestions combine local 404 history, site audit context, and existing redirect state.</p>

                <div class="aysa-errors-overview-grid">
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Active 404</span><strong id="aysa-errors-total-404">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Active 301</span><strong id="aysa-errors-total-301">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Active 410</span><strong id="aysa-errors-total-410">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Redirect ready</span><strong id="aysa-errors-redirect-ready">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">410 candidates</span><strong id="aysa-errors-gone-ready">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Conflicts</span><strong id="aysa-errors-conflicts">0</strong></div>
                    <div class="aysa-overview-card"><span class="aysa-overview-label">Review pending</span><strong id="aysa-errors-review-pending">0</strong></div>
                </div>

                <div class="aysa-errors-subtabs" role="tablist" aria-label="Errors sub-sections">
                    <button type="button" class="aysa-errors-subtab-btn active" data-errors-target="404">404</button>
                    <button type="button" class="aysa-errors-subtab-btn" data-errors-target="301">301</button>
                    <button type="button" class="aysa-errors-subtab-btn" data-errors-target="410">410</button>
                </div>

                <div id="aysa-errors-summary-message" class="aysa-site-audit-message info" style="display:none;"></div>

                <div class="aysa-errors-subtab-panel active" id="errors-404-panel">
                    <h3 class="aysa-subsection-title">404 Review Queue</h3>
                    <div class="aysa-404-filters">
                        <div class="aysa-filter-row">
                            <div class="aysa-search-box">
                                <input type="text" id="aysa-404-search" placeholder="Search URLs...">
                                <span class="dashicons dashicons-search"></span>
                            </div>
                            <div class="aysa-filter-group">
                                <label>Filter by:</label>
                                <select id="aysa-404-filter">
                                    <option value="all">SEO-Relevant 404 (Recommended)</option>
                                    <option value="all-raw">All 404 Sources</option>
                                    <option value="recent">Recent (Last 7 days)</option>
                                    <option value="internal-admin">Internal/Admin Noise</option>
                                    <option value="security-noise">Security Noise / Hack Attempts</option>
                                </select>
                            </div>
                            <div class="aysa-filter-actions">
                                <button id="aysa-404-refresh" class="aysa-btn aysa-btn-outline">
                                    <span class="dashicons dashicons-update"></span> Refresh
                                </button>
                                <button id="aysa-404-auto-fix" class="aysa-btn aysa-btn-primary">
                                    Auto-Fix Selected
                                </button>
                                <button id="aysa-404-auto-best" class="aysa-btn aysa-btn-outline">
                                    Auto Redirect (High Confidence)
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-table-responsive">
                        <table class="aysa-metrics-table" id="aysa-404-table">
                        <thead>
                            <tr>
                                    <th width="30"><input type="checkbox" class="aysa-select-all"></th>
                                    <th width="30"></th>
                                <th data-sort="url" class="aysa-sortable-header">404 URL</th>
                                    <th data-sort="hits" class="aysa-sortable-header">Hits</th>
                                    <th data-sort="last_hit" class="aysa-sortable-header">Date & Time</th>
                                    <th data-sort="referer" class="aysa-sortable-header">Referer</th>
                                <th>Best Match</th>
                                <th data-sort="confidence" class="aysa-sortable-header">Confidence</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody><!-- Entries will be loaded via AJAX --></tbody>
                    </table>
                    </div>
                    
                    <div class="aysa-404-pagination">
                        <div class="aysa-pagination-info">Showing <span id="aysa-404-showing">0</span> of <span id="aysa-404-total">0</span> errors <span id="aysa-404-page-info" class="aysa-page-info"></span></div>
                        <div class="aysa-pagination-controls">
                            <button class="aysa-pagination-btn" id="aysa-404-prev" disabled>
                                <span class="dashicons dashicons-arrow-left-alt2"></span> Previous
                            </button>
                            <div id="aysa-404-page-numbers" class="aysa-page-numbers"></div>
                            <button class="aysa-pagination-btn" id="aysa-404-next" disabled>
                                Next <span class="dashicons dashicons-arrow-right-alt2"></span>
                            </button>
                        </div>
                    </div>
                    
                    <div class="aysa-bulk-actions">
                        <button class="button button-primary" id="aysa-bulk-apply-redirects">Bulk Redirect<span class="aysa-credit-badge cost-medium">15 cr</span></button>
                        <button class="button" id="aysa-bulk-auto-best-redirects">Auto Apply Best Match</button>
                        <button class="button" id="aysa-bulk-mark-gone">Bulk Mark Gone<span class="aysa-credit-badge cost-low">3 cr/ea</span></button>
                        <button class="button" id="aysa-bulk-ignore">Ignore Selected</button>
                    </div>
                </div>

                <div class="aysa-errors-subtab-panel" id="errors-301-panel">
                    <h3 class="aysa-subsection-title">301 Redirect Rules</h3>
                    <div class="aysa-redirect-filters">
                        <div class="aysa-filter-row">
                            <div class="aysa-search-box">
                                <input type="text" id="aysa-redirect-search" placeholder="Search redirects...">
                                <span class="dashicons dashicons-search"></span>
                            </div>
                            <div class="aysa-filter-group">
                                <label>Filter by:</label>
                                <select id="aysa-redirect-filter">
                                    <option value="all">All Redirects</option>
                                    <option value="active">Active</option>
                                    <option value="recent">Recent (Last 7 days)</option>
                                </select>
                            </div>
                            <div class="aysa-filter-actions">
                                <button id="aysa-redirect-refresh" class="aysa-btn aysa-btn-outline">
                                    <span class="dashicons dashicons-update"></span> Refresh
                                </button>
                            </div>
                        </div>
                    </div>

                    <div id="aysa-redirects-message" class="aysa-site-audit-message info" style="display:none;"></div>

                    <div class="aysa-manual-redirect-form" style="margin-bottom:20px; padding:15px; background:#f9f9f9; border:1px solid #e0e0e0; border-radius:4px;">
                        <h3 style="margin-top:0;">Add Manual Redirect</h3>
                        <div style="display:flex; gap:10px; margin-bottom:10px;">
                            <div style="flex:1;">
                                <label for="aysa-old-url"><strong>Old URL:</strong></label>
                                <input type="text" id="aysa-old-url" class="regular-text" style="width:100%;" placeholder="e.g. /old-page or full URL">
                            </div>
                            <div style="flex:1;">
                                <label for="aysa-new-url"><strong>New URL:</strong></label>
                                <div style="display:flex; gap:5px;">
                                    <input type="text" id="aysa-new-url" class="regular-text" style="flex:1;" placeholder="e.g. /new-page or full URL">
                                    <button type="button" id="aysa-choose-page-manual" class="button button-secondary" style="white-space:nowrap;">
                                        <span class="dashicons dashicons-admin-page" style="vertical-align:middle;"></span> Choose from Pages
                                    </button>
                                </div>
                            </div>
                        </div>
                        <button id="aysa-add-manual-redirect" class="button button-primary">Create Redirect</button>
                    </div>
                    
                    <div class="aysa-table-responsive">
                        <table class="aysa-metrics-table" id="aysa-redirect-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" class="aysa-select-all"></th>
                                <th>Old URL</th>
                                <th>New URL</th>
                                <th>Status</th>
                                <th>Total Backlinks</th>
                                <th>Scope</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody><!-- Entries will be loaded via AJAX --></tbody>
                    </table>
                    </div>
                    
                    <div class="aysa-bulk-actions">
                        <button class="button" id="aysa-bulk-create-redirects">Create Redirects for Selected URLs<span class="aysa-credit-badge cost-low">7 cr/ea</span></button>
                    </div>
                </div>

                <div class="aysa-errors-subtab-panel" id="errors-410-panel">
                    <h3 class="aysa-subsection-title">410 Gone Rules</h3>
                    <div class="aysa-gone-filters">
                        <div class="aysa-filter-row">
                            <div class="aysa-search-box">
                                <input type="text" id="aysa-gone-search" placeholder="Search gone URLs...">
                                <span class="dashicons dashicons-search"></span>
                            </div>
                            <div class="aysa-filter-group">
                                <label>Filter by:</label>
                                <select id="aysa-gone-filter">
                                    <option value="all">All Gone URLs</option>
                                    <option value="recent">Recent (Last 7 days)</option>
                                    <option value="manual">Manually Added</option>
                                    <option value="auto">Auto-Generated</option>
                                </select>
                            </div>
                            <div class="aysa-filter-actions">
                                <button id="aysa-gone-refresh" class="aysa-btn aysa-btn-outline">
                                    <span class="dashicons dashicons-update"></span> Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-manual-gone-form" style="margin-bottom:20px; padding:15px; background:#f9f9f9; border:1px solid #e0e0e0; border-radius:4px;">
                        <h3 style="margin-top:0;">Mark URL as Gone (410)</h3>
                        <div style="display:flex; gap:10px; margin-bottom:10px;">
                            <div style="flex:1;">
                                <label for="aysa-gone-url"><strong>URL to mark as Gone:</strong></label>
                                <input type="text" id="aysa-gone-url" class="regular-text" style="width:100%;" placeholder="e.g. /obsolete-page or full URL">
                            </div>
                            <div style="flex:1;">
                                <label for="aysa-gone-reason"><strong>Reason:</strong></label>
                                <input type="text" id="aysa-gone-reason" class="regular-text" style="width:100%;" placeholder="Why this URL is being marked as Gone">
                            </div>
                        </div>
                        <button id="aysa-add-manual-gone" class="button button-primary">Mark as Gone</button>
                    </div>
                    
                    <div class="aysa-table-responsive">
                        <table class="aysa-metrics-table" id="aysa-gone-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" class="aysa-select-all"></th>
                                <th>URL marked as 410</th>
                                <th>Reason for Removal</th>
                                <th>Date marked</th>
                                <th>Project ID</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody><!-- Entries will be loaded via AJAX --></tbody>
                        </table>
                    </div>
                    
                    <div class="aysa-bulk-actions">
                        <button class="button" id="aysa-bulk-apply-gone">Bulk Apply Gone</button>
                        <button class="button" id="aysa-bulk-mark-gone-410">Bulk Mark Gone</button>
                    </div>
                </div>

                <div id="aysa-404-autofix-dialog" style="display:none;">
                    <div class="aysa-dialog-content">
                        <h3>Suggested Fix for <span class="aysa-404-url"></span></h3>
                        <p>We suggest redirecting to:</p>
                        <div class="aysa-suggestion-options"></div>
                        <p>Or enter a custom URL:</p>
                        <div class="aysa-custom-url-input">
                            <input type="text" id="aysa-custom-redirect" placeholder="e.g. /new-page">
                        </div>
                        <div class="aysa-dialog-actions">
                            <button class="aysa-btn aysa-btn-secondary aysa-dialog-close">Cancel</button>
                            <button class="aysa-btn aysa-btn-primary" id="aysa-apply-suggestion">Apply Redirect</button>
                            <button class="aysa-btn" id="aysa-mark-gone-dialog">Mark as Gone</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Schema Markup Section -->
        <div class="aysa-tab-content" id="schema-content">
            <?php include __DIR__ . "/aysa-technical-schema-v2.php"; ?>
        </div>

        <!-- Internal Linking Management Section -->
        <div class="aysa-tab-content" id="internal-linking-content">
            <?php include __DIR__ . "/aysa-internal-linking-v2.php"; ?>
            <div class="aysa-panel aysa-il-shell" style="display:none;">
                <input type="hidden" id="aysa-internal-linking-nonce" value="<?php echo esc_attr(wp_create_nonce('aysa_internal_linking_nonce')); ?>" />

                <div class="aysa-il-hero">
                    <div class="aysa-il-hero-copy">
                        <h2 class="aysa-section-title">Internal Linking</h2>
                        <p class="aysa-il-subtitle">Configure rules, preview impact, then apply safe internal links with full tracking.</p>
                    </div>
                    <div class="aysa-il-hero-status">
                        <span class="aysa-il-status-label">Automation status</span>
                        <span class="aysa-stat-status" id="aysa-linking-status">Disabled</span>
                    </div>
                </div>

                <div class="aysa-il-subtabs">
                    <button type="button" class="aysa-il-subtab-btn active" data-il-tab="operations-report">Operations & Report</button>
                    <button type="button" class="aysa-il-subtab-btn" data-il-tab="rules-scope">Rules & Scope</button>
                </div>

                <div class="aysa-il-subtab-panels">
                    <div class="aysa-reports-section aysa-il-reports-card aysa-il-subtab-panel active" data-il-panel="operations-report">
                        <div class="aysa-il-ops-header">
                            <h3>Operations & Reports</h3>
                            <p>Run a safe analysis before applying changes to content.</p>
                        </div>

                        <div class="aysa-report-controls aysa-il-actions">
                            <button class="aysa-btn aysa-btn-primary" id="aysa-preview-all-content">Analyze Internal Linking Opportunities</button>
                            <button class="aysa-btn aysa-btn-secondary" id="aysa-clear-protection-cache" title="Clear internal linking counters and logs">Clear Cache</button>
                        </div>
                        <div id="aysa-il-ops-inline-message" style="display:none;margin:8px 0 12px;padding:10px 12px;border-radius:8px;border:1px solid #d5e3f6;background:#f4f8ff;color:#27466f;font-size:13px;"></div>
                        <div id="aysa-il-last-run-summary" style="display:none;margin:0 0 12px;"></div>

                        <div id="aysa-internal-linking-stats" class="aysa-stats-grid aysa-il-stats">
                            <div class="aysa-stat-card">
                                <h4>Total Keywords</h4>
                                <span class="aysa-stat-number" id="aysa-total-keywords">0</span>
                            </div>
                            <div class="aysa-stat-card">
                                <h4>Total Links Added</h4>
                                <span class="aysa-stat-number" id="aysa-total-links">0</span>
                            </div>
                            <div class="aysa-stat-card">
                                <h4>Run Safety</h4>
                                <span class="aysa-il-chip">No duplicate target/keyword in same source</span>
                            </div>
                        </div>

                        <div class="aysa-reports-table aysa-il-table-wrap">
                            <h4>Keyword Link Statistics</h4>
                            <table class="aysa-table" id="aysa-keyword-stats-table">
                                <thead>
                                    <tr>
                                        <th>Keyword</th>
                                        <th>Target Page</th>
                                        <th>Source</th>
                                        <th>Links Added</th>
                                        <th>Last Placement</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="6" class="aysa-no-data">No data available. Enable internal linking and run an analysis to populate this report.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="aysa-internal-linking-settings aysa-il-settings-card aysa-il-subtab-panel" data-il-panel="rules-scope">
                        <div class="aysa-settings-header">
                            <h3>Rules & Scope</h3>
                            <div class="aysa-master-toggle">
                                <label class="aysa-switch">
                                    <input type="checkbox" id="aysa-internal-linking-enabled">
                                    <span class="aysa-slider round"></span>
                                </label>
                                <span>Enable Internal Linking</span>
                            </div>
                        </div>

                        <div class="aysa-settings-grid">
                            <div class="aysa-setting-group">
                                <label>Max links per keyword (global)</label>
                                <input type="number" id="aysa-max-links-per-keyword" min="1" max="10" value="1" readonly>
                                <small>How many times a keyword can be linked across the website.</small>
                            </div>

                            <div class="aysa-setting-group">
                                <label>Max links per entity</label>
                                <input type="number" id="aysa-max-links-per-entity" min="1" max="3" value="3" readonly>
                                <small>Base cap for article-type sources. Dynamic type/length rules still apply.</small>
                            </div>

                            <div class="aysa-setting-group">
                                <label>Matching type</label>
                                <select id="aysa-matching-type">
                                    <option value="exact">Exact match</option>
                                    <option value="partial">Partial match</option>
                                    <option value="both" selected>Both</option>
                                </select>
                            </div>

                            <div class="aysa-setting-group">
                                <label>Process source types</label>
                                <div class="aysa-checkbox-group">
                                    <label><input type="checkbox" id="aysa-process-posts" checked> Articles</label>
                                    <label><input type="checkbox" id="aysa-process-pages" checked> Pages</label>
                                    <label><input type="checkbox" id="aysa-process-categories" checked> Categories</label>
                                    <label><input type="checkbox" id="aysa-process-products" checked> Products</label>
                                </div>
                            </div>
                        </div>

                        <div class="aysa-il-rule-summary">
                            <h4>Active Execution Rules (Preset)</h4>
                            <ul>
                                <li><strong>Articles (post):</strong> maximum <strong>3</strong> internal links per source.</li>
                                <li><strong>Pages/Products:</strong> by source content length:
                                    &lt;=300 chars -> 1 link, 301-900 -> 2 links, &gt;=901 -> 3 links.
                                </li>
                                <li><strong>Safety:</strong> no duplicate target URL in the same source page.</li>
                                <li><strong>Anchor rule:</strong> no duplicate keyword combination in the same source page.</li>
                                <li><strong>Target validation:</strong> skip inactive/admin/edit URLs automatically.</li>
                            </ul>
                        </div>

                        <div class="aysa-advanced-settings">
                            <h4>Advanced Controls</h4>
                            <div class="aysa-settings-grid">
                                <div class="aysa-setting-group">
                                    <label><input type="checkbox" id="aysa-case-sensitive"> Case sensitive matching</label>
                                </div>

                                <div class="aysa-setting-group">
                                    <label><input type="checkbox" id="aysa-ignore-existing-links" checked> Ignore existing non-AYSA links</label>
                                </div>

                                <div class="aysa-setting-group">
                                    <label><input type="checkbox" id="aysa-priority-by-authority" checked> Priority by authority</label>
                                </div>

                                <div class="aysa-setting-group">
                                    <label>Exclude post IDs (comma separated)</label>
                                    <input type="text" id="aysa-excluded-post-ids" placeholder="1,2,3">
                                </div>

                                <div class="aysa-setting-group aysa-setting-group-wide">
                                    <label>Exclude URL patterns (one per line)</label>
                                    <textarea id="aysa-excluded-url-patterns" rows="8" placeholder="/cart/&#10;/checkout/&#10;/my-account/&#10;/feed/&#10;/?s=&#10;/wp-admin/&#10;.css&#10;.js"></textarea>
                                    <small>Use paths, fragments or regex-like patterns to skip sensitive areas.</small>
                                </div>
                            </div>
                        </div>

                        <div class="aysa-settings-actions">
                            <button class="aysa-btn aysa-btn-primary" id="aysa-save-internal-linking-settings">Save Settings</button>
                            <button class="aysa-btn aysa-btn-secondary" id="aysa-reset-internal-linking-settings">Restore Recommended Defaults</button>
                        </div>
                    </div>
                </div>

                <!-- Preview Modal for Content Changes -->
                <div id="aysa-preview-modal" style="display: none;">
                    <div class="aysa-modal-overlay">
                        <div class="aysa-modal-content">
                            <div class="aysa-modal-header">
                                <h3>Analyze Internal Linking Opportunities</h3>
                                <button class="aysa-modal-close" id="aysa-close-preview">&times;</button>
                            </div>
                            <div class="aysa-modal-body">
                                <div id="aysa-preview-loading" style="text-align: center; padding: 40px;">
                                    <div class="aysa-loader"></div>
                                    <p>Scanning content and simulating link placements...</p>
                                </div>
                                <div id="aysa-preview-content-container" style="display: none;">
                                    <div class="aysa-preview-summary">
                                        <h4>Summary</h4>
                                        <div class="aysa-preview-stats">
                                            <span class="aysa-stat"><strong id="aysa-preview-total-keywords">0</strong> keywords found</span>
                                            <span class="aysa-stat"><strong id="aysa-preview-total-links">0</strong> links will be created</span>
                                            <span class="aysa-stat"><strong id="aysa-preview-content-items">0</strong> content items affected</span>
                                        </div>
                                    </div>
                                    <div class="aysa-preview-details">
                                        <h4>Detailed Changes</h4>
                                        <div id="aysa-preview-changes-list"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="aysa-modal-footer">
                                <button class="aysa-btn aysa-btn-secondary" id="aysa-cancel-preview">Cancel</button>
                                <button class="aysa-btn aysa-btn-primary" id="aysa-approve-changes" style="display: none;">Approve & Apply Changes</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Link Details Modal -->
                <div id="aysa-link-details-modal" class="aysa-modal" style="display:none;">
                    <div class="aysa-modal-content">
                        <div class="aysa-modal-header">
                            <h3>Link Placement Details</h3>
                            <span class="aysa-modal-close">&times;</span>
                        </div>
                        <div class="aysa-modal-body">
                            <div id="aysa-link-placements-list"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Base Styles */
.aysa-dashboard-wrapper {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    background-color: #f8f9fa;
    padding: 20px;
    width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
}

.aysa-dashboard-container {
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Header Styles */
.aysa-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-dashboard-title h1 {
    font-size: 22px;
    margin: 0 0 5px;
    font-weight: 500;
    color: #333;
}

.aysa-dashboard-title p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-dashboard-user {
    display: flex;
    align-items: center;
    gap: 15px;
}

.aysa-btn-text {
    background: none;
    color: #1a73e8;
    padding: 0;
    border: none;
    font-size: 14px;
    cursor: pointer;
}

.aysa-btn-text:hover {
    text-decoration: underline;
}

/* Section Styles */
.aysa-section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px;
    color: #202124;
}

.aysa-subsection-title {
    font-size: 15px;
    font-weight: 500;
    margin: 0 0 12px;
    color: #202124;
}

.aysa-errors-overview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 12px;
    margin-bottom: 20px;
}

.aysa-overview-card {
    border: 1px solid #dcdcde;
    border-radius: 8px;
    background: #fff;
    padding: 14px 16px;
}

.aysa-overview-card strong {
    display: block;
    font-size: 24px;
    line-height: 1.2;
    color: #1d2327;
}

.aysa-overview-label {
    display: block;
    margin-bottom: 6px;
    font-size: 12px;
    font-weight: 600;
    color: #646970;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}

.aysa-errors-subtabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-bottom: 16px;
}

.aysa-errors-subtab-btn {
    border: 1px solid #c3c4c7;
    background: #fff;
    color: #1d2327;
    border-radius: 6px;
    padding: 8px 14px;
    cursor: pointer;
    font-weight: 600;
}

.aysa-errors-subtab-btn.active {
    border-color: #2271b1;
    color: #2271b1;
}

.aysa-errors-subtab-panel {
    display: none;
}

.aysa-errors-subtab-panel.active {
    display: block;
}

.aysa-panel {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

/* Overview Panel */
.aysa-overview-panel {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-performance-overview {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
}

.aysa-performance-score {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.aysa-circle-progress {
    width: 150px;
    height: 150px;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.aysa-circular-chart {
    display: block;
    margin: 0 auto;
    max-width: 100%;
    max-height: 100%;
}

.aysa-circle-bg {
    fill: none;
    stroke: #eee;
    stroke-width: 3.8;
}

.aysa-circle {
    fill: none;
    stroke-width: 3.8;
    stroke-linecap: round;
    stroke: #1a73e8;
}

.aysa-circular-chart.orange .aysa-circle {
    stroke: #fa7b17;
}

.aysa-percentage {
    fill: #202124;
    font-size: 0.5em;
    text-anchor: middle;
    font-weight: 500;
}

.aysa-score-label {
    margin-top: 10px;
    font-size: 14px;
    color: #5f6368;
    text-align: center;
}

.aysa-performance-metrics {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.aysa-metric-group {
    display: flex;
    gap: 20px;
}

/* Metrics Cards */
.aysa-metric-card {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    border: 1px solid #e0e0e0;
    flex: 1;
    min-width: 0;
}

.aysa-metric-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.aysa-metric-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 50%;
}

.aysa-metric-icon .dashicons {
    color: white;
    font-size: 20px;
    width: 20px;
    height: 20px;
}

.aysa-metric-trend {
    font-size: 13px;
    font-weight: 500;
}

.aysa-metric-trend.positive {
    color: #34a853;
}

.aysa-metric-trend.negative {
    color: #ea4335;
}

.aysa-metric-name {
    font-size: 13px;
    color: #5f6368;
    margin-bottom: 5px;
}

.aysa-metric-value {
    font-size: 24px;
    font-weight: 500;
    color: #202124;
}

.aysa-metric-unit {
    font-size: 14px;
    color: #5f6368;
    font-weight: normal;
}

.aysa-blue {
    background-color: #1a73e8;
}

.aysa-green {
    background-color: #34a853;
}

.aysa-purple {
    background-color: #9334e6;
}

.aysa-orange {
    background-color: #fa7b17;
}

.aysa-red {
    background-color: #ea4335;
}

.aysa-teal {
    background-color: #00a99d;
}

/* Internal Linking Styles */
.aysa-internal-linking-settings {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.aysa-settings-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-master-toggle {
    display: flex;
    align-items: center;
    gap: 10px;
}

.aysa-switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 24px;
}

.aysa-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.aysa-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 24px;
}

.aysa-slider:before {
    position: absolute;
    content: "";
    height: 18px;
    width: 18px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

input:checked + .aysa-slider {
    background-color: #2196F3;
}

input:checked + .aysa-slider:before {
    transform: translateX(26px);
}

.aysa-settings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.aysa-setting-group label {
    display: block;
    font-weight: 500;
    margin-bottom: 5px;
    color: #333;
}

.aysa-setting-group input,
.aysa-setting-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.aysa-checkbox-group label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: normal;
    margin-bottom: 0;
}

.aysa-checkbox-group input[type="checkbox"] {
    width: auto;
    margin: 0;
}

.aysa-advanced-settings {
    border-top: 1px solid #e0e0e0;
    padding-top: 20px;
    margin-top: 20px;
}

.aysa-advanced-settings h4 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
}

.aysa-settings-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}

.aysa-preview-section,
.aysa-reports-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.aysa-preview-section h3,
.aysa-reports-section h3 {
    margin-top: 0;
    margin-bottom: 10px;
    color: #333;
}

.aysa-description {
    color: #666;
    margin-bottom: 20px;
    font-size: 14px;
}

.aysa-input-group {
    margin-bottom: 15px;
}

.aysa-input-group label {
    display: block;
    font-weight: 500;
    margin-bottom: 5px;
    color: #333;
}

.aysa-input-group textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    font-family: inherit;
    resize: vertical;
}

.aysa-preview-actions,
.aysa-report-controls {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    align-items: center;
    flex-wrap: wrap;
}

.aysa-btn-secondary {
    background: #f1f3f4;
    color: #5f6368;
    border: 1px solid #dadce0;
    font-size: 13px;
    padding: 8px 14px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.aysa-btn-secondary:hover {
    background: #e8eaed;
    color: #3c4043;
    border-color: #bdc1c6;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(60,64,67,0.15);
}

.aysa-preview-comparison {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 15px;
}

.aysa-preview-original,
.aysa-preview-processed {
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    padding: 15px;
}

.aysa-preview-original h5,
.aysa-preview-processed h5 {
    margin-top: 0;
    margin-bottom: 10px;
    color: #333;
    font-size: 14px;
}

.aysa-preview-stats {
    padding: 10px 15px;
    background: #f8f9fa;
    border-radius: 4px;
    border-left: 4px solid #2196F3;
    font-weight: 500;
}

.aysa-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.aysa-stat-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    border-left: 4px solid #2196F3;
}

.aysa-stat-card h4 {
    margin: 0 0 10px;
    color: #666;
    font-size: 14px;
    font-weight: 500;
}

.aysa-stat-number {
    display: block;
    font-size: 24px;
    font-weight: bold;
    color: #333;
    cursor: help;
    position: relative;
}

.aysa-stat-number[title]:hover::after {
    content: attr(title);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background: #333;
    color: white;
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: normal;
    white-space: nowrap;
    z-index: 1000;
    margin-bottom: 5px;
}

.aysa-stat-status {
    display: block;
    font-size: 16px;
    font-weight: 500;
    color: #f44336;
}

.aysa-stat-status.active {
    color: #4caf50;
}

.aysa-reports-table {
    overflow-x: auto;
}

.aysa-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.aysa-table th,
.aysa-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-table th {
    background: #f8f9fa;
    font-weight: 500;
    color: #333;
}

.aysa-table .aysa-no-data {
    text-align: center;
    color: #666;
    font-style: italic;
    padding: 20px;
}

.aysa-modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
}

.aysa-modal-content {
    background-color: white;
    margin: 5% auto;
    border-radius: 8px;
    width: 80%;
    max-width: 600px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}

.aysa-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-modal-header h3 {
    margin: 0;
    color: #333;
}

.aysa-modal-close {
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
    color: #aaa;
}

.aysa-modal-close:hover {
    color: #333;
}

.aysa-modal-body {
    padding: 20px;
}

.aysa-internal-link {
    background-color: #e3f2fd;
    border-bottom: 1px solid #2196F3;
    text-decoration: none;
    padding: 1px 2px;
    border-radius: 2px;
}

.aysa-internal-link:hover {
    background-color: #bbdefb;
}

/* Tab Navigation */
.aysa-technical-tabs {
    margin-bottom: 20px;
}

.aysa-tab-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 10px;
}

.aysa-tab-btn {
    background: none;
    border: none;
    padding: 8px 15px;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
    color: #5f6368;
}

.aysa-tab-btn.active {
    background-color: #e8f0fe;
    color: #1a73e8;
    font-weight: 500;
}

.aysa-tab-btn:hover:not(.active) {
    background-color: #f8f9fa;
}

.aysa-tab-content {
    display: none;
}

.aysa-tab-content.active {
    display: block;
}

/* Checklist */
.aysa-checklist {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.aysa-checklist-item {
    display: flex;
    align-items: flex-start;
    padding-bottom: 20px;
    border-bottom: 1px solid #f1f3f4;
}

.aysa-checklist-item:last-child {
    border-bottom: none;
    padding-bottom: 0;
}

.aysa-checklist-status {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 15px;
    flex-shrink: 0;
}

.aysa-checklist-status.completed {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-checklist-status.partial {
    background-color: #fef7e0;
    color: #fbbc04;
}

.aysa-checklist-status.incomplete {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-checklist-content {
    flex: 1;
}

.aysa-checklist-title {
    font-weight: 500;
    margin-bottom: 5px;
    font-size: 15px;
}

.aysa-checklist-desc {
    color: #5f6368;
    font-size: 14px;
    margin-bottom: 10px;
}

.aysa-checklist-action {
    color: #1a73e8;
    text-decoration: none;
    font-size: 14px;
    font-weight: 500;
}

.aysa-checklist-action:hover {
    text-decoration: underline;
}

.aysa-checklist-percentage {
    font-weight: 500;
    min-width: 40px;
    text-align: right;
    color: #5f6368;
}

/* PageSpeed Metrics */
.aysa-pagespeed-metrics {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    margin-bottom: 20px;
}

.aysa-pagespeed-desktop, 
.aysa-pagespeed-mobile {
    flex: 1;
    min-width: 300px;
}

.aysa-metrics-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.aysa-metrics-table th {
    text-align: left;
    padding: 12px 10px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    color: #5f6368;
    font-weight: 500;
}

.aysa-metrics-table td {
    padding: 12px 10px;
    border-bottom: 1px solid #f1f3f4;
}

.aysa-status-indicator {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
}

.aysa-status-indicator.good {
    background-color: #34a853;
}

.aysa-status-indicator.average {
    background-color: #fbbc04;
}

.aysa-status-indicator.poor {
    background-color: #ea4335;
}

/* Action Buttons */
.aysa-test-actions {
    display: flex;
    justify-content: flex-start;
    margin-top: 20px;
}

.aysa-action-btn {
    background-color: #1a73e8;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    display: inline-block;
}

.aysa-action-btn:hover {
    background-color: #1765cc;
}

.aysa-action-btn.secondary {
    background-color: #f1f3f4;
    color: #5f6368;
}

.aysa-action-btn.secondary:hover {
    background-color: #e8eaed;
}

/* Table Styles */
.aysa-table-heading {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.aysa-table-actions {
    display: flex;
    gap: 15px;
}

.aysa-action-link {
    color: #1a73e8;
    text-decoration: none;
    font-size: 14px;
    font-weight: 500;
}

.aysa-action-link:hover {
    text-decoration: underline;
}

.aysa-data-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.aysa-data-table th {
    text-align: left;
    padding: 12px 15px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    color: #5f6368;
    font-weight: 500;
}

.aysa-data-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #f1f3f4;
}

.aysa-url-cell {
    color: #1a73e8;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.aysa-status-label {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-status-label.good {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-status-label.average {
    background-color: #fef7e0;
    color: #f9ab00;
}

.aysa-status-label.poor {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-status-label.warning {
    background-color: #fef7e0;
    color: #f9ab00;
}

.aysa-status-label.error {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-action-buttons {
    display: flex;
    gap: 8px;
}

.aysa-btn-small {
    font-size: 12px;
    padding: 4px 8px;
    background-color: #f1f3f4;
    color: #5f6368;
    border: none;
    border-radius: 4px;
    text-decoration: none;
    display: inline-block;
}

.aysa-btn-small:hover {
    background-color: #e8eaed;
}

/* Indexing Stats */
.aysa-indexing-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 25px;
}

.aysa-indexing-metric {
    flex: 1;
    min-width: 180px;
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    text-align: center;
}

.aysa-indexing-value {
    font-size: 22px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 5px;
}

.aysa-indexing-label {
    font-size: 14px;
    color: #5f6368;
    margin-bottom: 10px;
}

.aysa-indexing-progress {
    height: 6px;
    background-color: #e0e0e0;
    border-radius: 3px;
    overflow: hidden;
}

.aysa-indexing-progress .aysa-progress-bar {
    height: 100%;
    background-color: #34a853;
}

/* Config Sections */
.aysa-config-sections {
    display: flex;
    flex-direction: column;
    gap: 25px;
}

.aysa-config-section {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
}

.aysa-config-section h3 {
    margin: 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-config-content {
    padding: 15px;
}

.aysa-config-status {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.aysa-status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 8px;
}

.aysa-status-dot.green {
    background-color: #34a853;
}

.aysa-status-dot.red {
    background-color: #ea4335;
}

.aysa-status-dot.yellow {
    background-color: #fbbc04;
}

.aysa-status-text {
    font-weight: 500;
    margin-right: 15px;
}

.aysa-view-link {
    color: #1a73e8;
    text-decoration: none;
    font-size: 14px;
    margin-left: auto;
}

.aysa-config-details {
    margin-bottom: 15px;
}

.aysa-config-details p {
    margin: 5px 0;
    font-size: 14px;
    color: #5f6368;
}

.aysa-config-actions {
    display: flex;
    gap: 10px;
}

.aysa-robots-editor {
    width: 100%;
    height: 120px;
    font-family: monospace;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    margin-bottom: 15px;
    background-color: #f8f9fa;
    color: #202124;
}

/* Info Boxes */
.aysa-info-box {
    display: flex;
    padding: 15px;
    border-radius: 8px;
    background-color: #f8f9fa;
    margin-bottom: 20px;
}

.aysa-info-box.warning {
    background-color: #fef7e0;
}

.aysa-info-icon {
    margin-right: 15px;
    color: #5f6368;
}

.aysa-info-box.warning .aysa-info-icon {
    color: #f9ab00;
}

.aysa-info-content {
    flex: 1;
}

.aysa-info-content p {
    margin: 0 0 10px;
    color: #5f6368;
    font-size: 14px;
}

.aysa-info-content p:last-child {
    margin-bottom: 0;
}

.aysa-info-content p strong {
    color: #202124;
}

/* Site Structure */
.aysa-structure-graph {
    margin-bottom: 25px;
}

.aysa-placeholder-graph {
    width: 100%;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 15px;
}

.aysa-placeholder-graph img {
    max-width: 100%;
    max-height: 300px;
}

.aysa-graph-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    justify-content: center;
}

.aysa-legend-item {
    display: flex;
    align-items: center;
}

.aysa-legend-color {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    border-radius: 4px;
}

.aysa-legend-color.home {
    background-color: #1a73e8;
}

.aysa-legend-color.category {
    background-color: #34a853;
}

.aysa-legend-color.product {
    background-color: #fa7b17;
}

.aysa-legend-color.blog {
    background-color: #9334e6;
}

.aysa-structure-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;
}

.aysa-stat-box {
    flex: 1;
    min-width: 120px;
    text-align: center;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.aysa-stat-value {
    font-size: 22px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 5px;
}

.aysa-stat-label {
    font-size: 14px;
    color: #5f6368;
}

/* Subtabs */
.aysa-tabs-container {
    margin-bottom: 20px;
}

.aysa-subtab-buttons {
    display: flex;
    gap: 10px;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 10px;
    margin-bottom: 20px;
}

.aysa-subtab-btn {
    background: none;
    border: none;
    padding: 8px 15px;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
    color: #5f6368;
}

.aysa-subtab-btn.active {
    background-color: #e8f0fe;
    color: #1a73e8;
    font-weight: 500;
}

.aysa-subtab-content {
    display: none;
}

.aysa-subtab-content.active {
    display: block;
}

/* Status Boxes */
.aysa-status-box {
    display: flex;
    align-items: center;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.aysa-status-box.success {
    background-color: #e6f4ea;
}

.aysa-status-box.warning {
    background-color: #fef7e0;
}

.aysa-status-box.error {
    background-color: #fce8e6;
}

.aysa-status-box .dashicons {
    margin-right: 10px;
}

.aysa-status-box.success .dashicons {
    color: #34a853;
}

.aysa-status-box.warning .dashicons {
    color: #f9ab00;
}

.aysa-status-box.error .dashicons {
    color: #ea4335;
}

/* Breadcrumb & Schema */
.aysa-breadcrumb-info, 
.aysa-schema-info {
    margin-bottom: 20px;
}

.aysa-breadcrumb-example, 
.aysa-code-sample {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-top: 15px;
}

.aysa-code-block {
    background-color: #fff;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
    font-family: monospace;
    overflow-x: auto;
}

.aysa-schema-types {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    list-style: none;
    padding: 0;
    margin: 0;
}

.aysa-schema-tag {
    display: inline-block;
    padding: 5px 10px;
    background-color: #e8f0fe;
    color: #1a73e8;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
}

/* Content Silos */
.aysa-silo-visualization {
    margin-bottom: 25px;
}

.aysa-placeholder-silos {
    width: 100%;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.aysa-placeholder-silos img {
    max-width: 100%;
    max-height: 200px;
}

.aysa-silo-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 25px;
}

/* Mobile Optimization */
.aysa-mobile-overview {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
}

.aysa-mobile-score {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.aysa-mobile-summary {
    flex: 1;
    min-width: 300px;
}

.aysa-mobile-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 20px;
}

.aysa-mobile-stat-item {
    flex: 1;
    min-width: 120px;
    text-align: center;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.aysa-stat-desc {
    font-size: 12px;
    color: #5f6368;
    margin-top: 5px;
}

.aysa-mobile-test {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
}

.aysa-test-preview {
    flex: 1;
    min-width: 200px;
}

.aysa-device-wrapper {
    display: flex;
    justify-content: center;
}

.aysa-mobile-device {
    width: 280px;
    height: 520px;
    background-color: #202124;
    border-radius: 30px;
    padding: 35px 10px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;
}

.aysa-mobile-device:before {
    content: '';
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 6px;
    background-color: #333;
    border-radius: 3px;
}

.aysa-mobile-screen {
    width: 100%;
    height: 100%;
    background-color: #fff;
    overflow: hidden;
    border-radius: 2px;
    display: flex;
    flex-direction: column;
}

.aysa-mobile-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-mobile-placeholder img {
    max-width: 100%;
    max-height: 100%;
    width: 100%;
    height: 100%;
    object-fit: contain;
    object-position: top;
    border-radius: 2px;
    display: block;
}

.aysa-test-results {
    flex: 2;
    min-width: 300px;
}

.aysa-test-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.aysa-amp-status {
    margin-bottom: 20px;
}

.aysa-amp-benefits {
    margin-top: 20px;
    margin-bottom: 20px;
}

.aysa-benefit-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.aysa-benefit-list li {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.aysa-benefit-list li .dashicons {
    color: #1a73e8;
    margin-right: 10px;
}

.aysa-amp-actions {
    display: flex;
    gap: 10px;
}

/* Responsive Adjustments */
@media screen and (max-width: 1024px) {
    .aysa-performance-overview,
    .aysa-mobile-overview,
    .aysa-mobile-test {
        flex-direction: column;
        align-items: center;
    }
    
    .aysa-metric-group {
        width: 100%;
    }
    
    .aysa-device-wrapper {
        margin-bottom: 20px;
    }
}

@media screen and (max-width: 768px) {
    .aysa-dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .aysa-dashboard-user {
        flex-wrap: wrap;
    }
    
    .aysa-metric-group,
    .aysa-mobile-stats {
        flex-direction: column;
    }
    
    .aysa-checklist-item {
        flex-wrap: wrap;
    }
    
    .aysa-checklist-percentage {
        margin-left: 39px;
        margin-top: 10px;
    }
    
    .aysa-config-actions,
    .aysa-amp-actions,
    .aysa-test-actions {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .aysa-mobile-overview,
    .aysa-mobile-test {
        flex-direction: column;
    }
}

/* Stat Boxes pentru 404 Errors și alte secțiuni */
.aysa-overview-404 {
    margin-bottom: 25px;
}

.aysa-404-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 20px;
}

.aysa-stat-box {
    flex: 1;
    min-width: 150px;
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.aysa-stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #e8f0fe;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
}

.aysa-stat-icon .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
    color: #1a73e8;
}

.aysa-stat-value {
    font-size: 24px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 5px;
}

.aysa-stat-label {
    font-size: 13px;
    color: #5f6368;
}

/* 404 Filters */
.aysa-404-filters {
    margin-bottom: 20px;
}

.aysa-filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
}

.aysa-search-box {
    position: relative;
    flex: 1;
    min-width: 200px;
}

.aysa-search-box input {
    width: 100%;
    padding: 8px 32px 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-search-box .dashicons {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #5f6368;
}

.aysa-filter-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-filter-group label {
    font-size: 14px;
    color: #5f6368;
}

.aysa-filter-group select {
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    background-color: #fff;
}

.aysa-filter-actions {
    display: flex;
    gap: 8px;
}

/* Butoane pentru 404 */
.aysa-btn {
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
    border: none;
}

.aysa-btn .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

.aysa-btn-outline {
    background-color: transparent;
    border: 1px solid #e0e0e0;
    color: #5f6368;
}

.aysa-btn-outline:hover {
    background-color: #f1f3f4;
}

.aysa-btn-primary {
    background-color: #1a73e8;
    color: white;
    border: 1px solid #1a73e8;
}

.aysa-btn-primary:hover {
    background-color: #1765cc;
}

.aysa-btn-secondary {
    background-color: #f1f3f4;
    color: #5f6368;
}

.aysa-btn-secondary:hover {
    background-color: #e8eaed;
}

/* Paginare pentru 404 */
.aysa-404-pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;
    margin-bottom: 15px;
}

.aysa-page-info {
    color: #58677c;
    font-weight: 500;
    margin-left: 6px;
}

.aysa-page-numbers {
    display: inline-flex;
    gap: 6px;
    align-items: center;
    margin: 0 10px;
}

.aysa-page-number-btn {
    border: 1px solid #d7dee8;
    background: #fff;
    color: #22324a;
    border-radius: 6px;
    padding: 4px 9px;
    font-size: 12px;
    line-height: 1.2;
    cursor: pointer;
}

.aysa-page-number-btn.is-active {
    border-color: #2271b1;
    background: #eaf4ff;
    color: #0a4b78;
    font-weight: 700;
}

.aysa-page-number-ellipsis {
    color: #8593a8;
    font-size: 12px;
    padding: 0 2px;
}

.aysa-sortable-header {
    cursor: pointer;
    user-select: none;
    white-space: nowrap;
}

.aysa-sortable-header::after {
    content: '↕';
    margin-left: 6px;
    color: #9aa8bc;
    font-size: 11px;
}

.aysa-sortable-header.is-sorted-asc::after {
    content: '↑';
    color: #2271b1;
}

.aysa-sortable-header.is-sorted-desc::after {
    content: '↓';
    color: #2271b1;
}

.aysa-pagination-info {
    font-size: 14px;
    color: #5f6368;
}

.aysa-pagination-controls {
    display: flex;
    gap: 8px;
}

.aysa-pagination-btn {
    padding: 6px 12px;
    background-color: #f1f3f4;
    border: none;
    border-radius: 4px;
    font-size: 13px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
}

.aysa-pagination-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.aysa-pagination-btn .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

/* Dialog pentru Auto-fix */
#aysa-404-autofix-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-dialog-content {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    padding: 24px;
    width: 100%;
    max-width: 500px;
}

.aysa-dialog-content h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: 500;
}

.aysa-suggestion-options {
    margin: 15px 0;
}

.aysa-suggestion-option {
    display: flex;
    align-items: center;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    margin-bottom: 8px;
    cursor: pointer;
}

.aysa-suggestion-option:hover {
    background-color: #f8f9fa;
}

.aysa-suggestion-option.selected {
    background-color: #e8f0fe;
    border-color: #1a73e8;
}

.aysa-suggestion-option input[type="radio"] {
    margin-right: 10px;
}

.aysa-custom-url-input {
    margin: 15px 0;
}

.aysa-custom-url-input input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-dialog-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    gap: 8px;
}

/* Additional styles for 404 table */
#aysa-404-table th,
#aysa-404-table td {
    padding: 10px 12px;
}

.aysa-hit-count {
    display: inline-block;
    background-color: #f1f3f4;
    color: #5f6368;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 12px;
    min-width: 40px;
    text-align: center;
    font-weight: 500;
}

.aysa-hit-count.high {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-hit-count.medium {
    background-color: #fef7e0;
    color: #f9ab00;
}

.aysa-referer-link {
    color: #1a73e8;
    text-decoration: none;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}

.aysa-referer-link:hover {
    text-decoration: underline;
}

.aysa-suggested-url {
    color: #188038;
    font-weight: 500;
}

.aysa-404-type-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-404-type-icon.bot {
    background-color: #e8f0fe;
    color: #1a73e8;
}

.aysa-404-type-icon.user {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-404-type-icon .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.aysa-404-url-cell {
    max-width: 250px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Modal Styles */
.aysa-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-modal {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
    width: 100%;
    max-width: 500px;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    margin: 0 auto;
}

.aysa-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
}

.aysa-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #1a73e8;
}

.aysa-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    line-height: 1;
    color: #5f6368;
    cursor: pointer;
    padding: 0;
}

.aysa-modal-body {
    padding: 20px;
    overflow-y: auto;
    max-height: 60vh;
}

.aysa-modal-footer {
    padding: 12px 20px;
    border-top: 1px solid #e5e7eb;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.aysa-form-group {
    margin-bottom: 16px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    color: #202124;
}

.aysa-form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d2d6dc;
    border-radius: 4px;
    font-size: 14px;
    line-height: 1.5;
}

.aysa-form-static {
    padding: 8px 12px;
    background-color: #f8f9fa;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    font-size: 14px;
    word-break: break-word;
}

.aysa-modal-short {
    max-height: none !important;
    height: auto !important;
}

/* Stiluri pentru badge-urile cu procent */
.aysa-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: bold;
    font-size: 14px;
    color: #fff;
    text-align: center;
    min-width: 40px;
}
.aysa-badge-error {
    background-color: #d63638;
}
.aysa-badge-warning {
    background-color: #f0b849;
}
.aysa-badge-info {
    background-color: #72aee6;
}
.aysa-badge-success {
    background-color: #46b450;
}
.aysa-badge-neutral {
    background-color: #777;
}

.aysa-inline-badge {
    display: inline-block;
    margin-left: 8px;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
    line-height: 1.6;
    vertical-align: middle;
}

.aysa-badge-good {
    background-color: #e9f9ef;
    color: #1d7a39;
    border: 1px solid #c3e9d0;
}

.aysa-muted-note {
    color: #6b7280;
    font-size: 12px;
    font-weight: 500;
}

/* Status vizual pentru checklist item */
.aysa-checklist-status.error .dashicons {
    color: #d63638;
}
.aysa-checklist-status.warning .dashicons {
    color: #f0b849;
}
.aysa-checklist-status.info .dashicons {
    color: #72aee6;
}
.aysa-checklist-status.success .dashicons {
    color: #46b450;
}

/* Loader styling */
.aysa-loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    width: 100%;
}

.aysa-loader {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #1a73e8;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: aysa-spin 1.5s linear infinite;
    margin-bottom: 15px;
}

.aysa-loading-text {
    color: #666;
    font-size: 14px;
    margin: 0;
}

@keyframes aysa-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Hidden template for the overview UI */
.aysa-overview-template {
    display: none;
}

/* Circle chart colors */
.aysa-circular-chart.red path.aysa-circle {
    stroke: #d63638;
}
.aysa-circular-chart.orange path.aysa-circle {
    stroke: #f0b849;
}
.aysa-circular-chart.green path.aysa-circle {
    stroke: #46b450;
}
.aysa-circular-chart.blue path.aysa-circle {
    stroke: #2271b1;
}

/* Metric icons */
.aysa-metric-icon.aysa-red {
    background-color: rgba(214, 54, 56, 0.25);
    color: #d63638;
}
.aysa-metric-icon.aysa-orange {
    background-color: rgba(240, 184, 73, 0.25);
    color: #f0b849;
}
.aysa-metric-icon.aysa-green {
    background-color: rgba(70, 180, 80, 0.25);
    color: #46b450;
}
.aysa-metric-icon.aysa-blue {
    background-color: rgba(34, 113, 177, 0.25);
    color: #2271b1;
}

/* Table loading indicator */
.aysa-table-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    color: #666;
    font-size: 14px;
}

.aysa-loader-small {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #1a73e8;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: aysa-spin 1.5s linear infinite;
    margin-right: 10px;
}

/* Mobile optimization loading */
#aysa-mobile-opportunities .aysa-checklist-item {
    text-align: center;
    padding: 20px;
}

/* Checklist loading */
.aysa-loading-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px;
    text-align: center;
}

.aysa-checklist-loading-text {
    margin-top: 15px;
    color: #666;
    font-size: 14px;
}
</style>

<script type="text/javascript">
(function() {
    var pollTimer = null;
    var issueIndex = [];
    var siteAuditSnapshot = {};
    var siteAuditUiState = {
        issueSeverity: 'all',
        issueCategory: 'all',
        issueQuery: '',
        pageType: 'all',
        pageQuery: ''
    };

    function getAjaxUrl() {
        if (window.aysaParams && window.aysaParams.ajax_url) {
            return window.aysaParams.ajax_url;
        }
        return (window.ajaxurl || '');
    }

    function getProjectId() {
        var candidates = [
            window.aysaParams && window.aysaParams.canonical_project_id,
            window.aysaParams && window.aysaParams.project_id,
            window.aysaParams && window.aysaParams.wp_project_id
        ];
        for (var i = 0; i < candidates.length; i++) {
            var parsed = parseInt(candidates[i], 10);
            if (!isNaN(parsed) && parsed > 0) {
                return parsed;
            }
        }
        return 0;
    }

    function getNonce() {
        if (window.aysaParams && window.aysaParams.nonce) {
            return window.aysaParams.nonce;
        }
        return '';
    }

    function getTechnicalAuditNonce() {
        if (window.aysaParams && window.aysaParams.ajax_nonce) {
            return window.aysaParams.ajax_nonce;
        }
        return getNonce();
    }

    function getAgent8Url() {
        return <?php echo wp_json_encode(admin_url('admin.php?page=aysa-agent8-v3-lab')); ?>;
    }

    function encodeActionPayload(payload) {
        try {
            return window.encodeURIComponent(JSON.stringify(payload || {}));
        } catch (e) {
            return '';
        }
    }

    function decodeActionPayload(raw) {
        if (!raw) {
            return {};
        }
        try {
            return JSON.parse(window.decodeURIComponent(String(raw)));
        } catch (e) {
            return {};
        }
    }

    function queueAgent8SiteAuditAction(actionKey, actionPayload) {
        var normalizedActionKey = String(actionKey || '').trim();
        if (!normalizedActionKey) {
            return;
        }
        var payload = Object.assign({}, (actionPayload && typeof actionPayload === 'object') ? actionPayload : {}, {
            project_id: getProjectId()
        });
        try {
            window.localStorage.setItem('aysa_agent8_pending_action', JSON.stringify({
                source: 'site_audit',
                action_key: normalizedActionKey,
                action_payload: payload,
                created_at: new Date().toISOString()
            }));
            window.location.href = getAgent8Url();
        } catch (e) {
            setMessage('Could not pass the selected action into Agent8. Open Agent8 manually and retry.', 'error');
        }
    }

    function triggerPageSpeedPdfDownload(downloadUrl, fileName) {
        var resolvedUrl = String(downloadUrl || '');
        if (!resolvedUrl) {
            throw new Error('The report was generated without a valid download URL.');
        }
        var link = document.createElement('a');
        link.href = resolvedUrl;
        link.target = '_blank';
        link.rel = 'noopener';
        link.download = String(fileName || 'aysa-pagespeed-report.pdf');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function notifyPageSpeed(text, type) {
        if (typeof window.aysaShowPageSpeedNotice === 'function') {
            window.aysaShowPageSpeedNotice(text, type);
            return;
        }
        var cssClass = 'info';
        if (type === 'error') {
            cssClass = 'error';
        } else if (type === 'success') {
            cssClass = 'success';
        }
        var overview = document.getElementById('overview-data');
        if (overview) {
            overview.style.display = '';
            overview.innerHTML = '<div class="aysa-site-audit-message ' + cssClass + '">' + String(text || '') + '</div>';
        }
    }

    function pollPageSpeedDetailedReportStatus(jobId, button, originalButtonText, attempt) {
        var currentAttempt = parseInt(attempt, 10);
        if (isNaN(currentAttempt) || currentAttempt < 0) {
            currentAttempt = 0;
        }
        if (currentAttempt > 90) {
            var timeoutMessage = 'The AI report is still generating. Please retry in a moment.';
            notifyPageSpeed(timeoutMessage, 'error');
            window.alert(timeoutMessage);
            if (button) {
                button.disabled = false;
                button.textContent = originalButtonText;
            }
            return;
        }

        var params = new URLSearchParams();
        params.append('action', 'aysa_export_pagespeed_pdf_status');
        params.append('nonce', getTechnicalAuditNonce());
        params.append('job_id', String(jobId || ''));

        fetch(getAjaxUrl(), {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params.toString()
        }).then(function(resp) {
            return resp.text().then(function(text) {
                var data = null;
                try {
                    data = JSON.parse(text);
                } catch (e) {
                    throw new Error('Invalid status response: ' + text.slice(0, 800));
                }
                return data;
            });
        }).then(function(response) {
            if (!response || !response.success || !response.data) {
                var failureMessage = (response && response.data && response.data.message) ? String(response.data.message) : 'Detailed PageSpeed report status failed.';
                throw new Error(failureMessage);
            }

            var payload = response.data || {};
            var status = String(payload.status || 'queued');
            var progressLabel = String(payload.progress_label || status);
            if (button) {
                button.textContent = progressLabel || 'Generating report...';
            }

            if (status === 'completed') {
                notifyPageSpeed('Detailed PageSpeed report ready. Starting download...', 'success');
                triggerPageSpeedPdfDownload(String(payload.download_url || ''), String(payload.file_name || 'aysa-pagespeed-report.pdf'));
                if (button) {
                    button.disabled = false;
                    button.textContent = originalButtonText;
                }
                return;
            }

            if (status === 'failed') {
                var errorMessage = String(payload.error || 'Detailed PageSpeed report generation failed.');
                throw new Error(errorMessage);
            }

            notifyPageSpeed(progressLabel || 'Generating the detailed AI report for the web agency...', 'info');
            window.setTimeout(function() {
                pollPageSpeedDetailedReportStatus(jobId, button, originalButtonText, currentAttempt + 1);
            }, 2000);
        }).catch(function(error) {
            var message = (error && error.message) ? String(error.message) : 'Detailed PageSpeed report status failed.';
            notifyPageSpeed(message, 'error');
            window.alert(message);
            if (button) {
                button.disabled = false;
                button.textContent = originalButtonText;
            }
        });
    }

    function requestPageSpeedDetailedReport(buttonEl, options) {
        try {
            options = options || {};
            var projectId = getProjectId();
            if (!projectId) {
                var noProjectMessage = 'Project ID not found. Open the project again and retry.';
                notifyPageSpeed(noProjectMessage, 'error');
                window.alert(noProjectMessage);
                return;
            }

            var button = buttonEl || document.getElementById('aysa-download-pagespeed-pdf');
            var originalButtonText = button && button.textContent ? button.textContent : 'Download AI Report';
            var forceRegenerate = !!options.forceRegenerate;
            if (button) {
                button.disabled = true;
                button.textContent = forceRegenerate ? 'Refreshing report...' : 'Generating report...';
            }

            var ajaxUrl = getAjaxUrl();
            var nonce = getTechnicalAuditNonce();
            if (!ajaxUrl) {
                throw new Error('AJAX URL missing.');
            }
            if (!nonce) {
                throw new Error('Technical audit nonce missing.');
            }

            notifyPageSpeed(forceRegenerate ? 'Refreshing the AI report from the latest snapshot...' : 'Queueing the detailed AI report for the web agency...', 'info');

            var params = new URLSearchParams();
            params.append('action', 'aysa_export_pagespeed_pdf');
            params.append('nonce', nonce);
            params.append('project_id', String(projectId));
            if (forceRegenerate) {
                params.append('force_regenerate', '1');
            }

            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            }).then(function(resp) {
                return resp.text().then(function(text) {
                    var data = null;
                    try {
                        data = JSON.parse(text);
                    } catch (e) {
                        throw new Error('Invalid AJAX response: ' + text.slice(0, 800));
                    }
                    return data;
                });
            }).then(function(response) {
                try {
                    console.log('AYSA PageSpeed PDF response:', response);
                } catch (e) {}
                if (!response || !response.success || !response.data) {
                    var genericMessage = (response && response.data && response.data.message) ? String(response.data.message) : 'Detailed PageSpeed report generation failed.';
                    if (response && response.data && response.data.result) {
                        try {
                            genericMessage += ' ' + JSON.stringify(response.data.result).slice(0, 800);
                        } catch (e) {}
                    }
                    throw new Error(genericMessage);
                }

                var jobId = String(response.data.job_id || '');
                if (!jobId) {
                    throw new Error('The report job did not return a valid job ID.');
                }
                if (String(response.data.status || '').toLowerCase() === 'completed' && response.data.download_url) {
                    notifyPageSpeed('Report ready. Starting download...', 'success');
                    window.location.href = String(response.data.download_url);
                    if (button) {
                        button.disabled = false;
                        button.textContent = originalButtonText;
                    }
                    return;
                }
                var progressLabel = String(response.data.progress_label || response.data.status || 'Queued');
                notifyPageSpeed(progressLabel, 'info');
                pollPageSpeedDetailedReportStatus(jobId, button, originalButtonText, 0);
            }).catch(function(error) {
                var message = (error && error.message) ? String(error.message) : 'Detailed PageSpeed report request failed.';
                notifyPageSpeed(message, 'error');
                window.alert(message);
                if (button) {
                    button.disabled = false;
                    button.textContent = originalButtonText;
                }
            });
        } catch (error) {
            var fatalMessage = (error && error.message) ? String(error.message) : 'Detailed PageSpeed report request failed before dispatch.';
            notifyPageSpeed(fatalMessage, 'error');
            window.alert(fatalMessage);
        }
    }
    window.aysaRequestPageSpeedDetailedReport = requestPageSpeedDetailedReport;

    function emailPageSpeedDetailedReport(buttonEl) {
        try {
            var projectId = getProjectId();
            if (!projectId) {
                throw new Error('Project ID not found. Open the project again and retry.');
            }

            var recipient = window.prompt('Send the PageSpeed AI report to which email address?');
            if (!recipient) {
                return;
            }

            var button = buttonEl || document.getElementById('aysa-email-pagespeed-pdf');
            var originalButtonText = button && button.textContent ? button.textContent : 'Send AI Report';
            if (button) {
                button.disabled = true;
                button.textContent = 'Sending...';
            }

            var ajaxUrl = getAjaxUrl();
            var nonce = getTechnicalAuditNonce();
            if (!ajaxUrl || !nonce) {
                throw new Error('Technical audit request context missing.');
            }

            notifyPageSpeed('Preparing the AI report email...', 'info');
            var params = new URLSearchParams();
            params.append('action', 'aysa_pagespeed_report_email');
            params.append('nonce', nonce);
            params.append('project_id', String(projectId));
            params.append('recipient_email', String(recipient));

            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            }).then(function(resp) {
                return resp.json();
            }).then(function(response) {
                if (!response || !response.success || !response.data) {
                    throw new Error(response && response.data && response.data.message ? String(response.data.message) : 'Could not send the AI report.');
                }
                notifyPageSpeed('AI report sent to ' + String(response.data.recipient_email || recipient) + '.', 'success');
            }).catch(function(error) {
                var message = (error && error.message) ? String(error.message) : 'Could not send the AI report.';
                notifyPageSpeed(message, 'error');
                window.alert(message);
            }).finally(function() {
                if (button) {
                    button.disabled = false;
                    button.textContent = originalButtonText;
                }
            });
        } catch (error) {
            var fatalMessage = (error && error.message) ? String(error.message) : 'Could not send the AI report.';
            notifyPageSpeed(fatalMessage, 'error');
            window.alert(fatalMessage);
        }
    }
    window.aysaEmailPageSpeedDetailedReport = emailPageSpeedDetailedReport;

    function setBadge(status) {
        var el = document.getElementById('aysa-site-audit-status-badge');
        if (!el) {
            return;
        }
        var normalized = String(status || 'idle').toLowerCase();
        el.textContent = normalized;
        el.className = 'button button-secondary aysa-site-audit-status-badge is-' + normalized;
    }

    function setMessage(text, type) {
        var el = document.getElementById('aysa-site-audit-message');
        if (!el) {
            return;
        }
        if (!text) {
            el.style.display = 'none';
            el.textContent = '';
            el.className = 'notice inline';
            return;
        }
        el.style.display = 'block';
        el.innerHTML = '<p>' + escapeHtml(text) + '</p>';
        var cssClass = 'notice inline notice-info';
        if (type === 'success') {
            cssClass = 'notice inline notice-success';
        } else if (type === 'error') {
            cssClass = 'notice inline notice-error';
        } else if (type === 'warning') {
            cssClass = 'notice inline notice-warning';
        }
        el.className = cssClass;
    }

    function setSiteAuditBusy(isBusy, runLabel, refreshLabel) {
        var runBtn = document.getElementById('aysa-site-audit-run');
        var refreshBtn = document.getElementById('aysa-site-audit-refresh');
        if (runBtn) {
            runBtn.disabled = !!isBusy;
            runBtn.textContent = runLabel || 'Run Full Site Audit';
        }
        if (refreshBtn) {
            refreshBtn.disabled = !!isBusy;
            refreshBtn.textContent = refreshLabel || 'Refresh Status';
        }
    }

    function buildSiteAuditCompletionMessage(data) {
        if (data && data.warning) {
            return String(data.warning);
        }
        if (data && data.cached) {
            return 'Loaded cached site audit snapshot from local database.';
        }
        return 'Audit completed.';
    }

    function setRedirectsMessage(text, type) {
        var $box = $('#aysa-redirects-message');
        if (!$box.length) {
            return;
        }
        if (!text) {
            $box.hide().text('').removeClass('info success warning error');
            return;
        }
        $box.removeClass('info success warning error').addClass(type || 'info').html(text).show();
    }

    function renderState(state) {
        var targetEl = document.getElementById('aysa-site-audit-target');
        var jobEl = document.getElementById('aysa-site-audit-job');
        var updatedEl = document.getElementById('aysa-site-audit-updated');
        var modeEl = document.getElementById('aysa-site-audit-mode');
        var versionEl = document.getElementById('aysa-site-audit-version');
        var historyEl = document.getElementById('aysa-site-audit-history');
        if (targetEl) targetEl.textContent = state && state.target_url ? state.target_url : '-';
        if (jobEl) jobEl.textContent = state && state.job_id ? state.job_id : '-';
        if (updatedEl) updatedEl.textContent = state && state.updated_at ? state.updated_at : '-';
        if (modeEl) modeEl.textContent = state && state.mode ? state.mode : 'baseline_full';
        if (versionEl) versionEl.textContent = state && state.version_number ? ('v' + String(state.version_number)) : '-';
        if (historyEl) historyEl.textContent = state && state.history_count ? (formatNumber(state.history_count) + ' runs') : '0 runs';
        setBadge(state && state.status ? state.status : 'idle');
    }

    function formatNumber(value) {
        var num = parseInt(value || 0, 10);
        if (isNaN(num)) {
            num = 0;
        }
        return num.toLocaleString('en-US');
    }

    function escapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function renderResults(files) {
        var body = document.getElementById('aysa-site-audit-results-body');
        if (!body) {
            return;
        }
        body.innerHTML = '';
        if (!files || !files.length) {
            body.innerHTML = '<tr><td colspan="4">No audit files generated yet.</td></tr>';
            return;
        }
        files.forEach(function(file) {
            var tr = document.createElement('tr');
            var size = file && file.size_bytes ? String(file.size_bytes) + ' B' : '-';
            var rows = file && file.row_count ? formatNumber(file.row_count) : '-';
            tr.innerHTML =
                '<td>' + String((file && file.filename) || '-') + '</td>' +
                '<td>' + rows + '</td>' +
                '<td>' + size + '</td>' +
                '<td>' + String((file && file.updated_at) || '-') + '</td>';
            body.appendChild(tr);
        });
    }

    function renderOverview(overview) {
        overview = overview || {};
        var pagesEl = document.getElementById('aysa-site-audit-pages-crawled');
        var healthEl = document.getElementById('aysa-site-audit-site-health');
        var errorsEl = document.getElementById('aysa-site-audit-errors');
        var warningsEl = document.getElementById('aysa-site-audit-warnings');
        if (pagesEl) pagesEl.textContent = formatNumber(overview.pages_crawled || 0);
        if (healthEl) healthEl.textContent = String(parseInt(overview.site_health || 0, 10) || 0) + '%';
        if (errorsEl) errorsEl.textContent = formatNumber(overview.errors || 0);
        if (warningsEl) warningsEl.textContent = formatNumber(overview.warnings || 0);

        var statusCodes = overview.status_codes || {};
        var statusEl = document.getElementById('aysa-site-audit-status-codes');
        if (statusEl) {
            statusEl.innerHTML =
                '<li>2xx: ' + formatNumber(statusCodes['2xx'] || 0) + '</li>' +
                '<li>3xx: ' + formatNumber(statusCodes['3xx'] || 0) + '</li>' +
                '<li>4xx: ' + formatNumber(statusCodes['4xx'] || 0) + '</li>' +
                '<li>5xx: ' + formatNumber(statusCodes['5xx'] || 0) + '</li>';
        }

        var indexabilityEl = document.getElementById('aysa-site-audit-indexability');
        if (indexabilityEl) {
            indexabilityEl.innerHTML =
                '<li>Indexable: ' + formatNumber(overview.indexable_pages || 0) + '</li>' +
                '<li>Non-indexable: ' + formatNumber(overview.non_indexable_pages || 0) + '</li>';
        }

        var depthEl = document.getElementById('aysa-site-audit-depth');
        if (depthEl) {
            depthEl.innerHTML = '<li>Pages over depth 3: ' + formatNumber(overview.deep_pages_over_3 || 0) + '</li>';
        }

        var linksEl = document.getElementById('aysa-site-audit-links');
        if (linksEl) {
            linksEl.innerHTML = '<li>Pages with <=1 inlink: ' + formatNumber(overview.single_inlink_pages || 0) + '</li>';
        }
    }

    function renderConclusions(conclusion) {
        conclusion = conclusion || {};
        var summaryEl = document.getElementById('aysa-site-audit-conclusion-summary');
        var statusEl = document.getElementById('aysa-site-audit-conclusion-status');
        var problemEl = document.getElementById('aysa-site-audit-main-problem');
        var impactEl = document.getElementById('aysa-site-audit-business-impact');
        var actionsEl = document.getElementById('aysa-site-audit-conclusion-actions');
        var contextEl = document.getElementById('aysa-site-audit-conclusion-context');
        var status = String(conclusion.status || 'idle').toLowerCase();
        var badgeStatus = status === 'attention' ? 'running' : status;

        if (summaryEl) {
            summaryEl.textContent = conclusion.summary || 'No baseline conclusion available yet.';
        }
        if (statusEl) {
            statusEl.className = 'button button-secondary aysa-site-audit-status-badge is-' + badgeStatus;
            statusEl.textContent = conclusion.status_label || status;
        }
        if (problemEl) {
            problemEl.textContent = conclusion.main_problem || 'Run a full audit to identify the main issue.';
        }
        if (impactEl) {
            impactEl.textContent = conclusion.business_impact || 'The plugin will explain the business impact after the crawl finishes.';
        }
        if (actionsEl) {
            var actions = Array.isArray(conclusion.what_to_do_first) ? conclusion.what_to_do_first : (Array.isArray(conclusion.priority_actions) ? conclusion.priority_actions : []);
            actionsEl.innerHTML = actions.length ? actions.map(function(item) {
                return '<li>' + escapeHtml(String(item || '-')) + '</li>';
            }).join('') : '<li>No priority actions available yet.</li>';
        }
        if (contextEl) {
            var contextRows = [];
            if (conclusion.mode) {
                contextRows.push('Mode: ' + String(conclusion.mode));
            }
            if (conclusion.version_label) {
                contextRows.push('Version: ' + String(conclusion.version_label));
            }
            if (conclusion.history_count !== undefined) {
                contextRows.push('History: ' + formatNumber(conclusion.history_count || 0) + ' runs');
            }
            if (conclusion.artifact_count !== undefined) {
                contextRows.push('Artifacts: ' + formatNumber(conclusion.artifact_count || 0));
            }
            if (conclusion.updated_at) {
                contextRows.push('Last sync: ' + String(conclusion.updated_at));
            }
            contextEl.innerHTML = contextRows.length ? contextRows.map(function(item) {
                return '<li>' + escapeHtml(item) + '</li>';
            }).join('') : '<li>No audit context available yet.</li>';
        }
        renderRecommendedActions(conclusion.recommended_actions || []);
    }

    function renderRecommendedActions(actions) {
        var listEl = document.getElementById('aysa-site-audit-recommended-actions-list');
        if (!listEl) {
            return;
        }
        var bundles = Array.isArray(actions) ? actions : [];
        if (!bundles.length) {
            listEl.innerHTML = '<p>No preparation bundles available yet.</p>';
            return;
        }
        listEl.innerHTML = '<table class="widefat striped"><thead><tr><th>Action</th><th>Reason</th><th>Scope</th><th>State</th><th>Next step</th><th>Agent8</th></tr></thead><tbody>' + bundles.map(function(bundle) {
            var actionKey = String((bundle && bundle.action_key) || '');
            var breakdown = Array.isArray(bundle && bundle.issue_breakdown) ? bundle.issue_breakdown : [];
            var payload = encodeActionPayload({
                action_key: actionKey,
                bundle_type: String((bundle && bundle.bundle_type) || ''),
                issue_category: String((bundle && bundle.issue_category) || ''),
                issue_title: String((bundle && bundle.issue_title) || ''),
                affected_urls_preview: Array.isArray(bundle && bundle.affected_urls_preview) ? bundle.affected_urls_preview : [],
                affected_count: parseInt((bundle && bundle.affected_count) || 0, 10) || 0,
                source_files: Array.isArray(bundle && bundle.source_files) ? bundle.source_files : [],
                target_scope: String((bundle && bundle.target_scope) || ''),
                next_step: String((bundle && bundle.next_step) || '')
            });
            var state = String((bundle && bundle.approval_state) || 'suggested');
            var stateLabel = state.replace(/_/g, ' ');
            var breakdownHtml = '';
            if (breakdown.length) {
                breakdownHtml = '<div><strong>Coverage:</strong><ul>' + breakdown.map(function(item) {
                    return '<li>' + escapeHtml(String((item && item.label) || 'Review area')) + (item && item.affected_count ? ' (' + escapeHtml(formatNumber(item.affected_count)) + ' URLs in review scope)' : '') + '</li>';
                }).join('') + '</ul></div>';
            }
            return '' +
                '<tr>' +
                    '<td><strong>' + escapeHtml(String(bundle.action_label || bundle.issue_title || 'Preparation bundle')) + '</strong><br><span class="button button-secondary">' + escapeHtml(String(bundle.priority_label || 'Medium')) + '</span></td>' +
                    '<td>' + escapeHtml(String(bundle.reason || 'This bundle prepares the next technical remediation step.')) + breakdownHtml + '</td>' +
                    '<td><strong>Review scope:</strong> ' + escapeHtml(formatNumber(bundle.affected_count || 0) + ' URLs') + '<br><strong>Source family:</strong> ' + escapeHtml((Array.isArray(bundle.source_files) && bundle.source_files.length) ? bundle.source_files.join(', ') : 'audit dataset') + '</td>' +
                    '<td><span class="button button-secondary">' + escapeHtml(stateLabel) + '</span></td>' +
                    '<td>' + escapeHtml(String(bundle.next_step || '-')) + '</td>' +
                    '<td><button type="button" class="button aysa-site-audit-send-agent8" data-action-key="' + escapeHtml(actionKey) + '" data-action-payload="' + payload + '">Send to Agent8</button></td>' +
                '</tr>';
        }).join('') + '</tbody></table>';
    }

    function renderTopProblems(topIssues) {
        var listEl = document.getElementById('aysa-site-audit-top-problems-list');
        if (!listEl) {
            return;
        }
        var issues = Array.isArray(topIssues) ? topIssues.slice(0, 3) : [];
        if (!issues.length) {
            listEl.innerHTML = '<p>No prioritized issues available yet.</p>';
            return;
        }
        listEl.innerHTML = '<table class="widefat striped"><thead><tr><th>Problem</th><th>Why it matters</th><th>Affected</th><th>First action</th></tr></thead><tbody>' + issues.map(function(issue) {
            return '<tr>' +
                '<td><strong>' + escapeHtml(String(issue.title || '-')) + '</strong><br><span class="button button-secondary">' + escapeHtml(String(issue.priority_label || 'Medium')) + '</span></td>' +
                '<td>' + escapeHtml(String(issue.impact_plain || 'This can limit crawl quality or search visibility.')) + '</td>' +
                '<td>' + escapeHtml(String(issue.affected_display || ((issue.affected_pages || 0) + ' pages'))) + '</td>' +
                '<td>' + escapeHtml(String(issue.first_action_plain || 'Open details and review the affected URLs first.')) + '</td>' +
            '</tr>';
        }).join('') + '</tbody></table>';
    }

    function normalizeSiteAuditCategoryLabel(key) {
        var map = {
            response_codes: 'Crawlability',
            server: 'Crawlability',
            canonical: 'Canonicalization',
            indexability: 'Indexability',
            metadata: 'Meta Tags',
            internal_linking: 'Internal Linking',
            media: 'Images',
            technical: 'Technical'
        };
        return map[String(key || '')] || String(key || 'Technical');
    }

    function normalizePageTypeLabel(type) {
        var map = {
            all: 'Everywhere',
            homepage: 'Homepage',
            commercial: 'Commercial',
            content: 'Content',
            static: 'Static',
            asset: 'Assets',
            page: 'Pages'
        };
        return map[String(type || '')] || String(type || 'Pages');
    }

    function buildIssueActionChips(issue) {
        if (!Array.isArray(issue && issue.recommended_actions) || !issue.recommended_actions.length) {
            return '';
        }
        return '<div class="aysa-site-audit-inline-actions">' + issue.recommended_actions.map(function(bundle) {
            var actionKey = String((bundle && bundle.action_key) || '');
            var payload = encodeActionPayload({
                action_key: actionKey,
                bundle_type: String((bundle && bundle.bundle_type) || ''),
                issue_category: String((issue && issue.category) || ''),
                issue_title: String((issue && (issue.title_plain || issue.title)) || ''),
                affected_urls_preview: Array.isArray(issue && issue.examples) ? issue.examples.map(function(example) {
                    return String((example && example.url) || '');
                }).filter(Boolean).slice(0, 5) : [],
                affected_count: parseInt((issue && issue.affected_pages) || 0, 10) || 0,
                source_files: issue && issue.details && issue.details.filename ? [String(issue.details.filename)] : [],
                target_scope: String((bundle && bundle.bundle_type) || ''),
                next_step: String((issue && issue.first_action_plain) || '')
            });
            return '<button type="button" class="button aysa-site-audit-inline-action" data-action-key="' + escapeHtml(actionKey) + '" data-action-payload="' + payload + '">' + escapeHtml(String((bundle && bundle.action_label) || 'Send to Agent8')) + '</button>';
        }).join('') + '</div>';
    }

    function renderIssueFilters(snapshot, issues) {
        var severityWrap = document.getElementById('aysa-site-audit-severity-filters');
        var categoryWrap = document.getElementById('aysa-site-audit-category-filters');
        var severitySelect = document.getElementById('aysa-site-audit-severity-select');
        var categorySelect = document.getElementById('aysa-site-audit-category-select');
        var severitySummary = snapshot && snapshot.severity_summary ? snapshot.severity_summary : {};
        var categorySummary = Array.isArray(snapshot && snapshot.category_summary) ? snapshot.category_summary : [];
        var total = Array.isArray(issues) ? issues.length : 0;

        if (severityWrap && severitySelect) {
            var severityItems = [
                { key: 'all', label: 'All', count: parseInt(severitySummary.all || total || 0, 10) || 0 },
                { key: 'error', label: 'Errors', count: parseInt(severitySummary.error || 0, 10) || 0 },
                { key: 'warning', label: 'Warnings', count: parseInt(severitySummary.warning || 0, 10) || 0 },
                { key: 'notice', label: 'Notices', count: parseInt(severitySummary.notice || 0, 10) || 0 }
            ];
            severitySelect.innerHTML = severityItems.map(function(item) {
                var selected = siteAuditUiState.issueSeverity === item.key ? ' selected' : '';
                return '<option value="' + escapeHtml(item.key) + '"' + selected + '>' + escapeHtml(item.label) + ' (' + escapeHtml(formatNumber(item.count)) + ')</option>';
            }).join('');
        }

        if (categoryWrap && categorySelect) {
            var items = [{ key: 'all', label: 'All categories', count: total }].concat(categorySummary.map(function(item) {
                return {
                    key: String((item && item.key) || ''),
                    label: String((item && item.label) || normalizeSiteAuditCategoryLabel(item && item.key)),
                    count: parseInt((item && item.count) || 0, 10) || 0
                };
            }));
            categorySelect.innerHTML = items.map(function(item) {
                var selected = siteAuditUiState.issueCategory === item.key ? ' selected' : '';
                return '<option value="' + escapeHtml(item.key) + '"' + selected + '>' + escapeHtml(item.label) + ' (' + escapeHtml(formatNumber(item.count)) + ')</option>';
            }).join('');
        }
    }

    function buildIssuePreviewUrls(issue) {
        var examples = Array.isArray(issue && issue.examples) ? issue.examples.slice(0, 3) : [];
        if (!examples.length) {
            return '<em>No sample URLs saved yet.</em>';
        }
        return '<ul>' + examples.map(function(example) {
            var url = String((example && example.url) || '');
            if (!url) {
                return '';
            }
            return '<li><a href="' + escapeHtml(url) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(url) + '</a></li>';
        }).join('') + '</ul>';
    }

    function issueAffectedLabel(issue) {
        var count = parseInt((issue && issue.affected_pages) || 0, 10) || 0;
        return formatNumber(count) + ' URLs';
    }

    function getFilteredIssues(issues) {
        var query = String(siteAuditUiState.issueQuery || '').toLowerCase().trim();
        return (Array.isArray(issues) ? issues : []).filter(function(issue) {
            if (!issue || typeof issue !== 'object') {
                return false;
            }
            if (siteAuditUiState.issueSeverity !== 'all' && String(issue.severity || 'notice') !== siteAuditUiState.issueSeverity) {
                return false;
            }
            if (siteAuditUiState.issueCategory !== 'all' && String(issue.category || '') !== siteAuditUiState.issueCategory) {
                return false;
            }
            if (!query) {
                return true;
            }
            var haystack = [
                issue.title_plain,
                issue.title,
                issue.impact_plain,
                issue.first_action_plain,
                normalizeSiteAuditCategoryLabel(issue.category)
            ].join(' ').toLowerCase();
            return haystack.indexOf(query) !== -1;
        });
    }

    function renderIssues(issues, snapshot) {
        var container = document.getElementById('aysa-site-audit-issues-groups');
        var countEl = document.getElementById('aysa-site-audit-issues-count');
        if (!container) {
            return;
        }
        issueIndex = Array.isArray(issues) ? issues : [];
        renderIssueFilters(snapshot || {}, issueIndex);
        var filteredIssues = getFilteredIssues(issueIndex);
        if (countEl) {
            countEl.textContent = formatNumber(filteredIssues.length) + ' shown from ' + formatNumber(issueIndex.length) + ' total issues';
        }
        if (!filteredIssues.length) {
            container.innerHTML = '<p>No issues match the current filters.</p>';
            return;
        }

        var groups = { error: [], warning: [], notice: [] };
        filteredIssues.forEach(function(issue) {
            var severity = String((issue && issue.severity) || 'notice');
            if (!groups[severity]) {
                severity = 'notice';
            }
            groups[severity].push(issue);
        });

        var groupMeta = {
            error: { label: 'Errors', className: 'is-error' },
            warning: { label: 'Warnings', className: 'is-warning' },
            notice: { label: 'Notices', className: 'is-notice' }
        };

        container.innerHTML = ['error', 'warning', 'notice'].map(function(key) {
            var rows = groups[key] || [];
            if (!rows.length) {
                return '';
            }
            return '' +
                '<section class="aysa-site-audit-issue-group ' + groupMeta[key].className + '">' +
                    '<div class="postbox">' +
                        '<div class="inside">' +
                            '<h3 style="margin-top:0;">' + escapeHtml(groupMeta[key].label) + ' (' + escapeHtml(formatNumber(rows.length)) + ')</h3>' +
                            '<table class="widefat striped">' +
                                '<thead><tr><th>Problem</th><th>Affected</th><th>What to do first</th><th>URLs</th><th>Details</th></tr></thead>' +
                                '<tbody>' +
                        rows.map(function(issue) {
                            var issueIdx = issueIndex.indexOf(issue);
                            var priority = String((issue && issue.priority_label) || 'Medium');
                            var detailsFile = issue && issue.details && issue.details.filename ? String(issue.details.filename) : 'audit dataset';
                            var chips = buildIssueActionChips(issue);
                            return '' +
                                '<tr>' +
                                    '<td><strong>' + escapeHtml(String((issue && (issue.title_plain || issue.title)) || '-')) + '</strong><br><span class="button button-secondary">' + escapeHtml(priority) + '</span> <span class="description">' + escapeHtml(normalizeSiteAuditCategoryLabel(issue.category)) + '</span><br><small>' + escapeHtml(String((issue && issue.impact_plain) || 'This can limit crawl quality or search visibility.')) + '</small></td>' +
                                    '<td><strong>' + escapeHtml(issueAffectedLabel(issue)) + '</strong><br><small>Source: ' + escapeHtml(detailsFile) + '</small></td>' +
                                    '<td>' + escapeHtml(String((issue && issue.first_action_plain) || 'Open details and review the affected URLs first.')) + (chips ? '<div style="margin-top:8px;">' + chips + '</div>' : '') + '</td>' +
                                    '<td>' + buildIssuePreviewUrls(issue) + '</td>' +
                                    '<td><button type="button" class="button aysa-site-audit-issue-view" data-issue-index="' + String(issueIdx) + '">View details</button></td>' +
                                '</tr>';
                        }).join('') +
                                '</tbody>' +
                            '</table>' +
                        '</div>' +
                    '</div>' +
                '</section>';
        }).join('');
    }

    function normalizeDetailsRows(rows, maxRows) {
        if (!Array.isArray(rows)) {
            return [];
        }
        var out = [];
        rows.forEach(function(row) {
            if (!row || typeof row !== 'object') {
                return;
            }
            if (out.length >= maxRows) {
                return;
            }
            out.push(row);
        });
        return out;
    }

    function normalizeIssueColumnKey(value) {
        return String(value || '')
            .replace(/^\uFEFF/, '')
            .replace(/["']/g, '')
            .trim()
            .toLowerCase();
    }

    function normalizeIssueCellValue(value) {
        if (value === null || value === undefined) {
            return '';
        }
        return String(value)
            .replace(/^\uFEFF/, '')
            .replace(/\u00a0/g, ' ')
            .trim();
    }

    function getIssueRowValue(row, column) {
        if (!row || typeof row !== 'object') {
            return '';
        }
        if (Object.prototype.hasOwnProperty.call(row, column)) {
            return normalizeIssueCellValue(row[column]);
        }
        var normalizedNeedle = normalizeIssueColumnKey(column);
        var match = '';
        Object.keys(row).some(function(key) {
            if (normalizeIssueColumnKey(key) === normalizedNeedle) {
                match = normalizeIssueCellValue(row[key]);
                return true;
            }
            return false;
        });
        return match;
    }

    function isIssueUrlColumn(column) {
        var normalized = normalizeIssueColumnKey(column);
        return normalized === 'url' || normalized === 'address' || normalized.indexOf('address') !== -1 || normalized.indexOf('url') !== -1;
    }

    function buildFallbackModalRows(issue) {
        var examples = Array.isArray(issue && issue.examples) ? issue.examples : [];
        if (!examples.length) {
            return { columns: [], rows: [] };
        }
        return {
            columns: ['URL', 'Page Type'],
            rows: examples.slice(0, 20).map(function(example) {
                return {
                    'URL': normalizeIssueCellValue(example && example.url),
                    'Page Type': normalizeIssueCellValue(example && example.page_type)
                };
            }).filter(function(row) {
                return normalizeIssueCellValue(row.URL) !== '' || normalizeIssueCellValue(row['Page Type']) !== '';
            })
        };
    }

    function getPreferredIssueColumns(issue) {
        var key = String((issue && issue.key) || '').toLowerCase();
        if (key.indexOf('meta_description') === 0) {
            return ['Address', 'Meta Description 1', 'Meta Description 1 Length', 'Occurrences', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('page_title') === 0) {
            return ['Address', 'Title 1', 'Title 1 Length', 'Occurrences', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('h1_') === 0) {
            return ['Address', 'Occurrences', 'H1-1', 'H1-2', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('h2_') === 0) {
            return ['Address', 'Occurrences', 'H2-1', 'H2-1 Length', 'H2-2', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('response_codes') === 0 || key.indexOf('client_error') === 0 || key.indexOf('server_error') === 0 || key.indexOf('redirect') === 0) {
            return ['Address', 'Status Code', 'Status', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('directives_') === 0 || key.indexOf('noindex') === 0) {
            return ['Address', 'Meta Robots 1', 'X-Robots-Tag 1', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('canonical') === 0) {
            return ['Address', 'Canonical Link Element 1', 'Indexability', 'Indexability Status'];
        }
        if (key.indexOf('images_') === 0) {
            return ['Address', 'Size', 'Alt Text', 'Indexability', 'Indexability Status'];
        }
        return ['Address', 'URL', 'Title 1', 'Meta Description 1', 'Occurrences', 'Status Code', 'Indexability', 'Indexability Status'];
    }

    function selectIssueModalColumns(issue, rows, columns) {
        var availableColumns = Array.isArray(columns) ? columns.slice() : [];
        if (!availableColumns.length && Array.isArray(rows) && rows.length) {
            availableColumns = Object.keys(rows[0]);
        }
        if (!availableColumns.length) {
            return [];
        }

        var preferred = getPreferredIssueColumns(issue);
        var selected = preferred.filter(function(candidate) {
            return availableColumns.some(function(col) {
                return normalizeIssueColumnKey(col) === normalizeIssueColumnKey(candidate);
            });
        });

        if (!selected.length) {
            selected = availableColumns.slice(0, 10);
        }

        selected = selected.filter(function(col) {
            return (Array.isArray(rows) ? rows : []).some(function(row) {
                return normalizeIssueCellValue(getIssueRowValue(row, col)) !== '';
            });
        });

        return selected.slice(0, 8);
    }

    function openIssueModal(issue) {
        var modal = document.getElementById('aysa-site-audit-issue-modal');
        if (!modal || !issue) {
            return;
        }
        var severity = String(issue.severity || 'notice').toLowerCase();
        var severityEl = document.getElementById('aysa-site-audit-modal-severity');
        var titleEl = document.getElementById('aysa-site-audit-modal-title');
        var affectedEl = document.getElementById('aysa-site-audit-modal-affected');
        var sourceEl = document.getElementById('aysa-site-audit-modal-source');
        var descEl = document.getElementById('aysa-site-audit-modal-description');
        var headEl = document.getElementById('aysa-site-audit-modal-table-head');
        var bodyEl = document.getElementById('aysa-site-audit-modal-table-body');

        if (titleEl) {
            titleEl.textContent = String(issue.title_plain || issue.title || 'Issue Details');
        }
        if (severityEl) {
            severityEl.className = 'aysa-site-audit-priority-badge is-' + String(issue.priority_label || severity).toLowerCase().replace(/[^a-z0-9]+/g, '-');
            severityEl.textContent = String(issue.priority_label || severity);
        }
        if (affectedEl) {
            affectedEl.textContent = String(issue.affected_display || (formatNumber(issue.affected_pages || 0) + ' affected pages'));
        }
        if (sourceEl) {
            var src = issue && issue.details && issue.details.filename ? String(issue.details.filename) : 'audit dataset';
            sourceEl.textContent = 'Source: ' + src;
        }
        if (descEl) {
            descEl.textContent = String(issue.impact_plain || issue.description || '');
        }

        var rows = normalizeDetailsRows(issue && issue.details ? issue.details.sample_rows : [], 80);
        var columns = [];
        if (issue && issue.details && Array.isArray(issue.details.sample_columns) && issue.details.sample_columns.length) {
            columns = issue.details.sample_columns.slice(0, 10).map(function(col) { return String(col); });
        } else if (rows.length) {
            columns = Object.keys(rows[0]).slice(0, 10);
        }
        if (rows.length && columns.length) {
            rows = rows.filter(function(row) {
                return columns.some(function(col) {
                    return normalizeIssueCellValue(getIssueRowValue(row, col)) !== '';
                });
            });
        }
        columns = selectIssueModalColumns(issue, rows, columns);
        if ((!rows.length || !columns.length) && issue) {
            var fallback = buildFallbackModalRows(issue);
            columns = fallback.columns;
            rows = fallback.rows;
        }

        if (headEl) {
            if (!columns.length) {
                headEl.innerHTML = '';
            } else {
                headEl.innerHTML = '<tr>' + columns.map(function(col) {
                    return '<th>' + escapeHtml(col) + '</th>';
                }).join('') + '</tr>';
            }
        }
        if (bodyEl) {
            if (!rows.length || !columns.length) {
                bodyEl.innerHTML = '<tr><td colspan="10">No detailed sample rows available yet for this issue.</td></tr>';
            } else {
                bodyEl.innerHTML = rows.map(function(row) {
                    return '<tr>' + columns.map(function(col) {
                        var value = normalizeIssueCellValue(getIssueRowValue(row, col));
                        if (value === '') {
                            value = '-';
                        }
                        var safe = escapeHtml(String(value));
                        if (isIssueUrlColumn(col) && value !== '-') {
                            return '<td><a href="' + safe + '" target="_blank" rel="noopener noreferrer">' + safe + '</a></td>';
                        }
                        return '<td>' + safe + '</td>';
                    }).join('') + '</tr>';
                }).join('');
            }
        }
        modal.style.display = 'block';
        document.body.classList.add('aysa-site-audit-modal-open');
    }

    function closeIssueModal() {
        var modal = document.getElementById('aysa-site-audit-issue-modal');
        if (!modal) {
            return;
        }
        modal.style.display = 'none';
        document.body.classList.remove('aysa-site-audit-modal-open');
    }

    function bindIssueModalTriggers() {
        document.addEventListener('click', function(event) {
            var actionTrigger = event.target && event.target.closest ? event.target.closest('.aysa-site-audit-send-agent8, .aysa-site-audit-inline-action') : null;
            if (actionTrigger) {
                event.preventDefault();
                event.stopPropagation();
                queueAgent8SiteAuditAction(
                    actionTrigger.getAttribute('data-action-key') || '',
                    decodeActionPayload(actionTrigger.getAttribute('data-action-payload') || '')
                );
                return;
            }
            var trigger = event.target && event.target.closest ? event.target.closest('[data-issue-index]') : null;
            if (!trigger) {
                return;
            }
            var issueIdx = parseInt(trigger.getAttribute('data-issue-index') || '', 10);
            if (isNaN(issueIdx) || !issueIndex[issueIdx]) {
                return;
            }
            openIssueModal(issueIndex[issueIdx]);
        });

        var modal = document.getElementById('aysa-site-audit-issue-modal');
        if (!modal) {
            return;
        }
        var closeBtn = document.getElementById('aysa-site-audit-modal-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', closeIssueModal);
        }
        modal.addEventListener('click', function(event) {
            if (event.target && event.target.classList && event.target.classList.contains('aysa-site-audit-modal-backdrop')) {
                closeIssueModal();
            }
        });
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeIssueModal();
            }
        });
    }

    function renderPageTypeFilters(pages) {
        var wrap = document.getElementById('aysa-site-audit-page-type-filters');
        if (!wrap) {
            return;
        }
        var counts = { all: Array.isArray(pages) ? pages.length : 0 };
        (Array.isArray(pages) ? pages : []).forEach(function(page) {
            var key = String((page && page.page_type) || 'page');
            if (!counts[key]) {
                counts[key] = 0;
            }
            counts[key]++;
        });
        var orderedKeys = ['all', 'homepage', 'commercial', 'content', 'static', 'page', 'asset'];
        wrap.innerHTML = orderedKeys.filter(function(key) {
            return counts[key] > 0 || key === 'all';
        }).map(function(key) {
            return '<button type="button" class="button button-secondary aysa-site-audit-filter-pill' + (siteAuditUiState.pageType === key ? ' is-active' : '') + '" data-filter-type="page-type" data-filter-value="' + escapeHtml(key) + '">' + escapeHtml(normalizePageTypeLabel(key)) + ' (' + escapeHtml(formatNumber(counts[key] || 0)) + ')</button>';
        }).join('');
    }

    function renderPages(pages) {
        var body = document.getElementById('aysa-site-audit-pages-body');
        if (!body) {
            return;
        }
        body.innerHTML = '';
        var pageRows = Array.isArray(pages) ? pages : [];
        renderPageTypeFilters(pageRows);
        var query = String(siteAuditUiState.pageQuery || '').toLowerCase().trim();
        pageRows = pageRows.filter(function(page) {
            if (!page || typeof page !== 'object') {
                return false;
            }
            if (siteAuditUiState.pageType !== 'all' && String(page.page_type || 'page') !== siteAuditUiState.pageType) {
                return false;
            }
            if (!query) {
                return true;
            }
            var haystack = [
                page.url,
                page.title,
                page.page_type,
                page.top_issue_title
            ].join(' ').toLowerCase();
            return haystack.indexOf(query) !== -1;
        });
        if (!pageRows.length) {
            body.innerHTML = '<tr><td colspan="7">No crawled pages match the current filters.</td></tr>';
            return;
        }
        pageRows.forEach(function(page) {
            var tr = document.createElement('tr');
            var url = page && page.url ? String(page.url) : '-';
            var safeUrl = escapeHtml(url);
            var issueCount = parseInt((page && page.issues_count) || 0, 10) || 0;
            var issuePriority = String((page && page.issue_priority) || '').toLowerCase().replace(/[^a-z0-9]+/g, '-');
            var pageType = normalizePageTypeLabel(page && page.page_type ? page.page_type : 'page');
            tr.innerHTML =
                '<td><a href=\"' + safeUrl + '\" target=\"_blank\" rel=\"noopener noreferrer\">' + safeUrl + '</a></td>' +
                '<td>' + escapeHtml(page && page.title ? page.title : '-') + '</td>' +
                '<td><span class="button button-secondary">' + escapeHtml(page && page.status_code ? page.status_code : '-') + '</span></td>' +
                '<td><strong>' + escapeHtml(String((page && page.issues_label) || '0 issues')) + '</strong>' + (page && page.top_issue_title ? '<div><small>' + escapeHtml(String(page.top_issue_title)) + '</small></div>' : '') + '</td>' +
                '<td>' + escapeHtml(pageType) + '</td>' +
                '<td>' + escapeHtml(page && page.crawl_depth !== undefined ? page.crawl_depth : '-') + '</td>' +
                '<td>' + escapeHtml(page && page.inlinks !== undefined ? page.inlinks : '-') + '</td>';
            body.appendChild(tr);
        });
    }

    function renderStatistics(stats, snapshot, overview, files) {
        var exportsData = (stats || {}).exports || {};
        var coverageEl = document.getElementById('aysa-site-audit-export-coverage');
        var cardsEl = document.getElementById('aysa-site-audit-stats-cards');
        if (!coverageEl) {
            return;
        }
        coverageEl.innerHTML =
            '<li>Internal: ' + formatNumber(exportsData.internal || 0) + '</li>' +
            '<li>Titles: ' + formatNumber(exportsData.page_titles || 0) + '</li>' +
            '<li>Meta: ' + formatNumber(exportsData.meta_descriptions || 0) + '</li>' +
            '<li>H1: ' + formatNumber(exportsData.h1 || 0) + '</li>' +
            '<li>Canonicals: ' + formatNumber(exportsData.canonicals || 0) + '</li>' +
            '<li>Directives: ' + formatNumber(exportsData.directives || 0) + '</li>' +
            '<li>Images: ' + formatNumber(exportsData.images || 0) + '</li>';

        if (cardsEl) {
            var pagesCrawled = parseInt((overview && overview.pages_crawled) || 0, 10) || 0;
            var statusCodes = (overview && overview.status_codes) || {};
            var issueSummary = (snapshot && snapshot.severity_summary) || {};
            var fileCount = Array.isArray(files) ? files.length : 0;
            var cards = [
                {
                    title: 'HTTP Status Code',
                    value: pagesCrawled > 0 ? Math.round((((parseInt(statusCodes['4xx'] || 0, 10) || 0) + (parseInt(statusCodes['5xx'] || 0, 10) || 0)) / pagesCrawled) * 100) + '%' : '0%',
                    subtitle: 'pages with 4xx and 5xx status codes',
                    lines: [
                        '5xx: ' + formatNumber(statusCodes['5xx'] || 0),
                        '4xx: ' + formatNumber(statusCodes['4xx'] || 0),
                        '3xx: ' + formatNumber(statusCodes['3xx'] || 0),
                        '2xx: ' + formatNumber(statusCodes['2xx'] || 0)
                    ]
                },
                {
                    title: 'Indexability',
                    value: formatNumber((overview && overview.indexable_pages) || 0),
                    subtitle: 'indexable pages in current crawl',
                    lines: [
                        'Non-indexable: ' + formatNumber((overview && overview.non_indexable_pages) || 0),
                        'Canonical signals: ' + formatNumber(exportsData.canonicals || 0),
                        'Directives: ' + formatNumber(exportsData.directives || 0)
                    ]
                },
                {
                    title: 'Pages Crawl Depth',
                    value: formatNumber((overview && overview.deep_pages_over_3) || 0),
                    subtitle: 'pages with more than 3 clicks',
                    lines: [
                        'Pages crawled: ' + formatNumber(pagesCrawled),
                        'Single-inlink pages: ' + formatNumber((overview && overview.single_inlink_pages) || 0)
                    ]
                },
                {
                    title: 'Incoming Internal Links',
                    value: pagesCrawled > 0 ? Math.round(((parseInt((overview && overview.single_inlink_pages) || 0, 10) || 0) / pagesCrawled) * 100) + '%' : '0%',
                    subtitle: 'pages have only one incoming internal link',
                    lines: [
                        'Weak pages: ' + formatNumber((overview && overview.single_inlink_pages) || 0),
                        'Internal export: ' + formatNumber(exportsData.internal || 0),
                        'Links export: ' + formatNumber(exportsData.links || 0)
                    ]
                },
                {
                    title: 'Markup Types',
                    value: formatNumber(exportsData.structured_data || 0),
                    subtitle: 'pages with structured data export rows',
                    lines: [
                        'Images: ' + formatNumber(exportsData.images || 0),
                        'Meta descriptions: ' + formatNumber(exportsData.meta_descriptions || 0),
                        'Titles: ' + formatNumber(exportsData.page_titles || 0)
                    ]
                },
                {
                    title: 'Audit Dataset',
                    value: formatNumber(fileCount),
                    subtitle: 'generated files in the current baseline',
                    lines: [
                        'Errors: ' + formatNumber(issueSummary.error || 0),
                        'Warnings: ' + formatNumber(issueSummary.warning || 0),
                        'Notices: ' + formatNumber(issueSummary.notice || 0)
                    ]
                }
            ];
            cardsEl.innerHTML = cards.map(function(card) {
                return '<div class="postbox"><div class="inside">' +
                    '<h3 style="margin-top:0;">' + escapeHtml(card.title) + '</h3>' +
                    '<p><strong>' + escapeHtml(String(card.value || '0')) + '</strong></p>' +
                    '<p>' + escapeHtml(String(card.subtitle || '')) + '</p>' +
                    '<ul>' + (card.lines || []).map(function(line) {
                        return '<li>' + escapeHtml(String(line || '')) + '</li>';
                    }).join('') + '</ul>' +
                '</div></div>';
            }).join('');
        }
    }

    function renderAudit(audit, snapshot) {
        audit = audit || {};
        renderOverview(audit.overview || {});
        renderIssues(audit.issues || [], snapshot || {});
        renderPages(audit.pages || []);
        renderStatistics(audit.statistics || {}, snapshot || {}, audit.overview || {}, Array.isArray(snapshot && snapshot.files) ? snapshot.files : []);
    }

    function renderSiteAuditSnapshot(snapshot, fallbackState, fallbackAudit, fallbackFiles) {
        var normalizedSnapshot = snapshot && typeof snapshot === 'object' ? snapshot : {};
        siteAuditSnapshot = normalizedSnapshot;
        var state = normalizedSnapshot && Object.keys(normalizedSnapshot).length ? normalizedSnapshot : (fallbackState || {});
        var audit = fallbackAudit || {};
        if (normalizedSnapshot && normalizedSnapshot.overview_rows) {
            audit = {
                overview: {
                    pages_crawled: normalizedSnapshot.pages_crawled || 0,
                    site_health: normalizedSnapshot.site_health || 0,
                    errors: normalizedSnapshot.errors || 0,
                    warnings: normalizedSnapshot.warnings || 0,
                    status_codes: ((fallbackAudit || {}).overview || {}).status_codes || {},
                    indexable_pages: ((fallbackAudit || {}).overview || {}).indexable_pages || 0,
                    non_indexable_pages: ((fallbackAudit || {}).overview || {}).non_indexable_pages || 0,
                    deep_pages_over_3: ((fallbackAudit || {}).overview || {}).deep_pages_over_3 || 0,
                    single_inlink_pages: ((fallbackAudit || {}).overview || {}).single_inlink_pages || 0
                },
                issues: Array.isArray(normalizedSnapshot.rows) ? normalizedSnapshot.rows : [],
                pages: Array.isArray(normalizedSnapshot.pages) ? normalizedSnapshot.pages : [],
                statistics: {
                    exports: Array.isArray(normalizedSnapshot.exports) ? normalizedSnapshot.exports.reduce(function(acc, row) {
                        var key = String((row && row.export) || '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
                        if (key) {
                            acc[key] = parseInt((row && row.rows) || 0, 10) || 0;
                        }
                        return acc;
                    }, {}) : {}
                }
            };
        }

        renderState(state || {});
        renderResults(Array.isArray(normalizedSnapshot.files) ? normalizedSnapshot.files : (fallbackFiles || []));
        renderAudit((normalizedSnapshot && normalizedSnapshot.overview_rows) ? audit : (hasAuditPayload(fallbackAudit) ? fallbackAudit : audit), normalizedSnapshot);
        renderConclusions(normalizedSnapshot.conclusion || {});
        renderTopProblems((normalizedSnapshot.conclusion || {}).top_issues || []);
    }

    function rerenderCurrentSiteAuditViews() {
        if (!siteAuditSnapshot || typeof siteAuditSnapshot !== 'object' || !Object.keys(siteAuditSnapshot).length) {
            return;
        }
        var audit = {
            issues: Array.isArray(siteAuditSnapshot.rows) ? siteAuditSnapshot.rows : [],
            pages: Array.isArray(siteAuditSnapshot.pages) ? siteAuditSnapshot.pages : [],
            statistics: {
                exports: Array.isArray(siteAuditSnapshot.exports) ? siteAuditSnapshot.exports.reduce(function(acc, row) {
                    var key = String((row && row.export) || '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
                    if (key) {
                        acc[key] = parseInt((row && row.rows) || 0, 10) || 0;
                    }
                    return acc;
                }, {}) : {}
            },
            overview: {
                pages_crawled: siteAuditSnapshot.pages_crawled || 0,
                site_health: siteAuditSnapshot.site_health || 0,
                errors: siteAuditSnapshot.errors || 0,
                warnings: siteAuditSnapshot.warnings || 0
            }
        };
        renderIssues(audit.issues, siteAuditSnapshot);
        renderPages(audit.pages);
        renderStatistics(audit.statistics, siteAuditSnapshot, audit.overview, Array.isArray(siteAuditSnapshot.files) ? siteAuditSnapshot.files : []);
    }

    function bindSiteAuditFilterControls() {
        document.addEventListener('input', function(event) {
            var target = event.target;
            if (!target) {
                return;
            }
            if (target.id === 'aysa-site-audit-issues-search') {
                siteAuditUiState.issueQuery = String(target.value || '');
                renderIssues(Array.isArray(siteAuditSnapshot.rows) ? siteAuditSnapshot.rows : [], siteAuditSnapshot);
            }
            if (target.id === 'aysa-site-audit-pages-search') {
                siteAuditUiState.pageQuery = String(target.value || '');
                renderPages(Array.isArray(siteAuditSnapshot.pages) ? siteAuditSnapshot.pages : []);
            }
        });

        document.addEventListener('change', function(event) {
            var target = event.target;
            if (!target) {
                return;
            }
            if (target.id === 'aysa-site-audit-severity-select') {
                siteAuditUiState.issueSeverity = String(target.value || 'all');
                renderIssues(Array.isArray(siteAuditSnapshot.rows) ? siteAuditSnapshot.rows : [], siteAuditSnapshot);
            } else if (target.id === 'aysa-site-audit-category-select') {
                siteAuditUiState.issueCategory = String(target.value || 'all');
                renderIssues(Array.isArray(siteAuditSnapshot.rows) ? siteAuditSnapshot.rows : [], siteAuditSnapshot);
            } else if (target.matches('.aysa-site-audit-filter-pill[data-filter-type="page-type"]')) {
                siteAuditUiState.pageType = String(target.getAttribute('data-filter-value') || 'all');
                renderPages(Array.isArray(siteAuditSnapshot.pages) ? siteAuditSnapshot.pages : []);
            }
        });

        document.addEventListener('click', function(event) {
            var target = event.target;
            if (!target) {
                return;
            }
            if (target.id === 'aysa-site-audit-issues-reset') {
                siteAuditUiState.issueQuery = '';
                siteAuditUiState.issueSeverity = 'all';
                siteAuditUiState.issueCategory = 'all';
                var queryInput = document.getElementById('aysa-site-audit-issues-search');
                if (queryInput) {
                    queryInput.value = '';
                }
                renderIssues(Array.isArray(siteAuditSnapshot.rows) ? siteAuditSnapshot.rows : [], siteAuditSnapshot);
            }
        });
    }

    function ajaxPost(data) {
        return jQuery.ajax({
            url: getAjaxUrl(),
            method: 'POST',
            dataType: 'json',
            data: data
        });
    }

    function stopPolling() {
        if (pollTimer) {
            clearInterval(pollTimer);
            pollTimer = null;
        }
    }

    function hasAuditPayload(audit) {
        if (!audit || typeof audit !== 'object') {
            return false;
        }
        return Object.keys(audit).length > 0;
    }

    function fetchResults(jobId, forceRefresh) {
        return ajaxPost({
            action: 'aysa_technical_site_audit_results',
            _ajax_nonce: getTechnicalAuditNonce(),
            project_id: getProjectId(),
            job_id: jobId || '',
            preview_rows: 120,
            refresh: forceRefresh ? 1 : 0
        }).done(function(resp) {
            if (!resp || !resp.success) {
                return;
            }
            var data = resp.data || {};
            var broker = data.broker || {};
            var files = Array.isArray(data.files) ? data.files : (broker.files || []);
            var audit = hasAuditPayload(data.audit) ? data.audit : (broker.audit || {});
            renderSiteAuditSnapshot(data.snapshot || {}, data.state || {}, audit || {}, files || []);
            if (data.warning) {
                setMessage(String(data.warning), 'info');
            }
        }).fail(function(xhr) {
            setMessage('Could not load audit results: ' + (xhr && xhr.status ? xhr.status : 'network'), 'error');
        }).always(function() {
            setSiteAuditBusy(false);
        });
    }

    function checkStatus(jobId, forceRefresh, loadResultsIfCompleted) {
        return ajaxPost({
            action: 'aysa_technical_site_audit_status',
            _ajax_nonce: getTechnicalAuditNonce(),
            project_id: getProjectId(),
            job_id: jobId || '',
            refresh: forceRefresh ? 1 : 0
        }).done(function(resp) {
            if (!resp || !resp.success) {
                setMessage((resp && resp.data) ? String(resp.data) : 'Status check failed.', 'error');
                return;
            }
            var data = resp.data || {};
            var state = data.state || {};
            var hasCachedAudit = hasAuditPayload(data.audit);
            renderSiteAuditSnapshot(data.snapshot || {}, state, hasCachedAudit ? data.audit : {}, Array.isArray(data.files) ? data.files : []);
            if (data.warning) {
                setMessage(String(data.warning), 'info');
            }
            if (state.status === 'completed') {
                stopPolling();
                setSiteAuditBusy(false);
                if (loadResultsIfCompleted && (!hasCachedAudit || forceRefresh)) {
                    setMessage('Audit completed. Loading files...', 'success');
                    fetchResults(state.job_id || jobId || '', !!forceRefresh);
                } else {
                    setMessage(buildSiteAuditCompletionMessage(data), 'success');
                }
            } else if (state.status === 'failed') {
                stopPolling();
                setSiteAuditBusy(false);
                setMessage(data.cached ? 'Last crawl failed. Showing cached site audit snapshot from local database.' : 'Audit failed. Check broker logs for details.', data.cached ? 'info' : 'error');
            } else if (state.status === 'running') {
                setSiteAuditBusy(true, 'Running audit...', 'Checking...');
                setMessage('Audit in progress...', 'info');
            }
        }).fail(function(xhr) {
            setSiteAuditBusy(false);
            setMessage('Status request failed: ' + (xhr && xhr.status ? xhr.status : 'network'), 'error');
        });
    }

    function startAudit() {
        setSiteAuditBusy(true, 'Starting...', 'Waiting...');
        setMessage('Starting full site audit...', 'info');
        ajaxPost({
            action: 'aysa_technical_site_audit_start',
            _ajax_nonce: getTechnicalAuditNonce(),
            project_id: getProjectId()
        }).done(function(resp) {
            if (!resp || !resp.success) {
                setSiteAuditBusy(false);
                setMessage((resp && resp.data) ? String(resp.data) : 'Could not start audit.', 'error');
                return;
            }
            var data = resp.data || {};
            var state = data.state || {};
            renderSiteAuditSnapshot(data.snapshot || {}, state, hasAuditPayload(data.audit) ? data.audit : {}, Array.isArray(data.files) ? data.files : []);
            if (data.warning) {
                setMessage(String(data.warning), 'info');
            }
            if (state.status === 'completed') {
                stopPolling();
                setSiteAuditBusy(false);
                setMessage(buildSiteAuditCompletionMessage(data), 'success');
                return;
            }
            if (state.status === 'failed') {
                stopPolling();
                setSiteAuditBusy(false);
                setMessage((resp && resp.data && resp.data.warning) ? String(resp.data.warning) : 'Audit failed. Check broker logs for details.', 'error');
                return;
            }
            setSiteAuditBusy(true, 'Running audit...', 'Checking...');
            setMessage('Audit started. Collecting crawl data in background...', 'success');
            stopPolling();
            pollTimer = setInterval(function() {
                checkStatus(state.job_id || '', true, true);
            }, 5000);
        }).fail(function(xhr) {
            setSiteAuditBusy(false);
            setMessage('Start failed: ' + (xhr && xhr.status ? xhr.status : 'network'), 'error');
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        bindIssueModalTriggers();
        bindSiteAuditFilterControls();
        var runBtn = document.getElementById('aysa-site-audit-run');
        var refreshBtn = document.getElementById('aysa-site-audit-refresh');
        var subTabButtons = document.querySelectorAll('.aysa-site-audit-subtab-btn');
        subTabButtons.forEach(function(btn) {
            btn.addEventListener('click', function() {
                var key = btn.getAttribute('data-site-audit-subtab');
                document.querySelectorAll('.aysa-site-audit-subtab-btn').forEach(function(node) {
                    node.classList.remove('is-active');
                    node.classList.remove('nav-tab-active');
                });
                document.querySelectorAll('.aysa-site-audit-subtab-content').forEach(function(node) {
                    node.classList.remove('is-active');
                });
                btn.classList.add('is-active');
                btn.classList.add('nav-tab-active');
                var target = document.getElementById('aysa-site-audit-subtab-' + key);
                if (target) {
                    target.classList.add('is-active');
                }
            });
        });
        if (runBtn) {
            runBtn.addEventListener('click', startAudit);
        }
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function() {
                checkStatus('', true, true);
            });
        }
        setMessage('Site Audit no longer auto-loads on page open. Use Refresh Status when you want to load the cached audit snapshot.', 'info');
    });
})();
</script>

<!-- Hidden template for overview content -->
<div class="aysa-overview-template">
    <div class="aysa-performance-score">
        <div class="aysa-circle-progress">
            <svg viewBox="0 0 36 36" class="aysa-circular-chart">
                <path class="aysa-circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path>
                <path class="aysa-circle" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path>
                <text x="18" y="20.35" class="aysa-percentage">0%</text>
            </svg>
            <div class="aysa-score-label">Overall Score</div>
        </div>
    </div>
    
    <div class="aysa-performance-metrics">
        <div class="aysa-metric-group">
            <div class="aysa-metric-card">
                <div class="aysa-metric-header">
                    <span class="aysa-metric-icon aysa-orange"><span class="dashicons dashicons-performance"></span></span>
                    <span class="aysa-metric-trend">-</span>
                </div>
                <div class="aysa-metric-name">Page Speed (Desktop)</div>
                <div class="aysa-metric-value">0<span class="aysa-metric-unit">/100</span></div>
            </div>
            
            <div class="aysa-metric-card">
                <div class="aysa-metric-header">
                    <span class="aysa-metric-icon aysa-red"><span class="dashicons dashicons-smartphone"></span></span>
                    <span class="aysa-metric-trend">-</span>
                </div>
                <div class="aysa-metric-name">Page Speed (Mobile)</div>
                <div class="aysa-metric-value">0<span class="aysa-metric-unit">/100</span></div>
            </div>
        </div>
        
        <div class="aysa-metric-group">
            <div class="aysa-metric-card">
                <div class="aysa-metric-header">
                    <span class="aysa-metric-icon aysa-green"><span class="dashicons dashicons-welcome-view-site"></span></span>
                    <span class="aysa-metric-trend">-</span>
                </div>
                <div class="aysa-metric-name">Mobile-Friendly</div>
                <div class="aysa-metric-value">0<span class="aysa-metric-unit">/100</span></div>
            </div>
            
            <div class="aysa-metric-card">
                <div class="aysa-metric-header">
                    <span class="aysa-metric-icon aysa-blue"><span class="dashicons dashicons-admin-site"></span></span>
                    <span class="aysa-metric-trend">-</span>
                </div>
                <div class="aysa-metric-name">Indexability</div>
                <div class="aysa-metric-value">0<span class="aysa-metric-unit">/100</span></div>
            </div>
        </div>
    </div>
</div>

<script>
// Modal utility functions
function showModal(modalId) {
    document.getElementById(modalId).style.display = 'flex';
}

function hideModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function showSuccessModal(message, callback) {
    document.getElementById('aysa-success-message').textContent = message;
    showModal('aysa-success-modal');
    
    // Set callback for OK button if provided
    if (callback) {
        document.querySelector('#aysa-success-modal .aysa-success-ok').onclick = function() {
            hideModal('aysa-success-modal');
            callback();
        };
    } else {
        document.querySelector('#aysa-success-modal .aysa-success-ok').onclick = function() {
            hideModal('aysa-success-modal');
        };
    }
}

function showErrorModal(message) {
    document.getElementById('aysa-error-message').textContent = message;
    showModal('aysa-error-modal');
    
    document.querySelector('#aysa-error-modal .aysa-error-ok').onclick = function() {
        hideModal('aysa-error-modal');
    };
}

function showConfirmModal(title, message, confirmCallback) {
    document.getElementById('aysa-modal-title').textContent = title;
    document.getElementById('aysa-modal-content').textContent = message;
    showModal('aysa-modal-container');
    
    document.querySelector('#aysa-modal-container .aysa-modal-confirm').onclick = function() {
        hideModal('aysa-modal-container');
        if (confirmCallback) confirmCallback();
    };
    
    document.querySelector('#aysa-modal-container .aysa-modal-cancel').onclick = function() {
        hideModal('aysa-modal-container');
    };
}

jQuery(document).ready(function($) {
    // Normalize runtime params across legacy/new localized objects.
    window.aysa_params = window.aysa_params || window.aysaParams || window.aysa_ajax || {};
    var aysa_params = window.aysa_params;
    if (!aysa_params.ajax_url && typeof ajaxurl !== 'undefined') {
        aysa_params.ajax_url = ajaxurl;
    }
    if (!aysa_params.nonce) {
        if (window.aysa_ajax && window.aysa_ajax.nonce) {
            aysa_params.nonce = window.aysa_ajax.nonce;
        } else if (window.aysaParams && window.aysaParams.nonce) {
            aysa_params.nonce = window.aysaParams.nonce;
        } else {
            aysa_params.nonce = '';
        }
    }
    if (!aysa_params.api_base_url) {
        if (window.aysaParams && window.aysaParams.api_base_url) {
            aysa_params.api_base_url = window.aysaParams.api_base_url;
        } else if (window.aysaApiConfig && window.aysaApiConfig.baseUrl) {
            aysa_params.api_base_url = window.aysaApiConfig.baseUrl;
        } else {
            aysa_params.api_base_url = 'https://api.aysa.ai/';
        }
    }
    var aysaApiBaseUrl = String(aysa_params.api_base_url || 'https://api.aysa.ai').replace(/\/+$/, '');
    const technicalNonce = '<?php echo esc_attr(wp_create_nonce('aysa_internal_linking_nonce')); ?>';

    // Helper to retrieve saved project ID from wizard
    function getProjectId() {
        var hubProjectId = $('#aysa-schema-hub').data('project-id');
        if (hubProjectId && parseInt(hubProjectId, 10) > 0) {
            return parseInt(hubProjectId, 10);
        }
        var candidates = [
            window.aysaParams && window.aysaParams.canonical_project_id,
            window.aysaParams && window.aysaParams.project_id,
            window.aysaParams && window.aysaParams.wp_project_id,
            typeof aysaParams !== 'undefined' ? aysaParams.canonical_project_id : 0,
            typeof aysaParams !== 'undefined' ? aysaParams.project_id : 0,
            typeof aysaParams !== 'undefined' ? aysaParams.wp_project_id : 0
        ];
        for (var i = 0; i < candidates.length; i++) {
            var parsed = parseInt(candidates[i], 10);
            if (!isNaN(parsed) && parsed > 0) {
                return parsed;
            }
        }
        return 0;
    }
    
    // Update Project ID when the input changes
    $('#aysa-project-id').on('change', function() {
        var projectId = $(this).val();
        if (projectId) {
            $('#errors-301-panel').data('loaded', false);
            $('#errors-410-panel').data('loaded', false);
            if ($('.aysa-tab-btn[data-target="errors"]').hasClass('active')) {
                openErrorsSubtab($('.aysa-errors-subtab-btn.active').data('errors-target') || '404', true);
            }
        }
    });
    
    // Tab navigation
    $('.aysa-tab-btn').on('click', function() {
        // Remove active class from all buttons and content
        $('.aysa-tab-btn').removeClass('active');
        $('.aysa-tab-content').removeClass('active');
        
        // Add active class to clicked button
        $(this).addClass('active');
        
        // Show corresponding content
        var target = $(this).data('target');
        $('#' + target + '-content').addClass('active');
    });

    const aysaErrorsState = {
        active404: 0,
        active301: 0,
        active410: 0,
        redirectReady: 0,
        goneReady: 0,
        conflicts: 0,
        reviewPending: 0
    };

    function updateErrorsOverview(summary) {
        const next = summary && typeof summary === 'object' ? summary : {};
        if (typeof next.active404 !== 'undefined') aysaErrorsState.active404 = Number(next.active404 || 0);
        if (typeof next.active301 !== 'undefined') aysaErrorsState.active301 = Number(next.active301 || 0);
        if (typeof next.active410 !== 'undefined') aysaErrorsState.active410 = Number(next.active410 || 0);
        if (typeof next.redirectReady !== 'undefined') aysaErrorsState.redirectReady = Number(next.redirectReady || 0);
        if (typeof next.goneReady !== 'undefined') aysaErrorsState.goneReady = Number(next.goneReady || 0);
        if (typeof next.conflicts !== 'undefined') aysaErrorsState.conflicts = Number(next.conflicts || 0);
        if (typeof next.reviewPending !== 'undefined') aysaErrorsState.reviewPending = Number(next.reviewPending || 0);

        $('#aysa-errors-total-404').text(aysaErrorsState.active404);
        $('#aysa-errors-total-301').text(aysaErrorsState.active301);
        $('#aysa-errors-total-410').text(aysaErrorsState.active410);
        $('#aysa-errors-redirect-ready').text(aysaErrorsState.redirectReady);
        $('#aysa-errors-gone-ready').text(aysaErrorsState.goneReady);
        $('#aysa-errors-conflicts').text(aysaErrorsState.conflicts);
        $('#aysa-errors-review-pending').text(aysaErrorsState.reviewPending);
    }

    function showErrorsHubMessage(text, type) {
        var $box = $('#aysa-errors-summary-message');
        if (!$box.length) {
            return;
        }
        if (!text) {
            $box.hide().text('').removeClass('info success warning error');
            return;
        }
        $box.removeClass('info success warning error').addClass(type || 'info').html(text).show();
    }

    function openErrorsSubtab(target, forceReload) {
        const normalized = String(target || '404');
        $('.aysa-errors-subtab-btn').removeClass('active');
        $(`.aysa-errors-subtab-btn[data-errors-target="${normalized}"]`).addClass('active');
        $('.aysa-errors-subtab-panel').removeClass('active').hide();
        $('#errors-' + normalized + '-panel').addClass('active').show();

        if (normalized === '301') {
            loadRedirectsData(Boolean(forceReload));
        } else if (normalized === '410') {
            load410GoneData(Boolean(forceReload));
        } else {
            const projectId = getProjectId();
            const filter = $('#aysa-404-filter').val() || 'all';
            const search = $('#aysa-404-search').val() || '';
            load404Data(projectId, 1, filter, search);
        }
    }

    $('.aysa-errors-subtab-btn').on('click', function() {
        openErrorsSubtab($(this).data('errors-target'));
    });

    function aysaEscapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function setSitemapMessage(message, type) {
        var $box = $('#aysa-sitemap-message');
        if (!$box.length) {
            return;
        }
        if (!message) {
            $box.hide().text('');
            return;
        }
        $box.removeClass('info success warning error').addClass(type || 'info').html(message).show();
    }

    function sitemapStatusLabel(status) {
        var clean = String(status || '').toLowerCase();
        if (clean === 'error' || clean === 'failed') {
            return '<span class="aysa-issue-severity-error">Error</span>';
        }
        if (clean === 'warning' || clean === 'warn') {
            return '<span class="aysa-issue-severity-warning">Warning</span>';
        }
        if (clean === 'pass' || clean === 'ok' || clean === 'success') {
            return '<span class="aysa-issue-severity-notice">Pass</span>';
        }
        return '<span class="aysa-issue-severity-notice">Info</span>';
    }

    function renderSitemapRobotsAudit(payload, cached) {
        payload = payload || {};
        var checks = Array.isArray(payload.checks) ? payload.checks : [];
        var sitemaps = Array.isArray(payload.sitemaps) ? payload.sitemaps : [];
        var summary = payload.summary || {};
        var robots = payload.robots || {};
        var generation = payload.generation || {};
        var providers = Array.isArray(payload.providers) ? payload.providers : [];

        $('#aysa-robots-health').text(summary.robots_health || '-');
        $('#aysa-sitemap-health').text(summary.sitemap_health || '-');
        $('#aysa-sitemap-primary-url').text(payload.primary_sitemap || '-');
        $('#aysa-sitemap-mode').text(summary.sitemap_mode || generation.mode || '-');
        $('#aysa-robots-source').text(robots.source_label || '-');
        $('#aysa-sitemap-providers').text(providers.length ? providers.join(', ') : '-');
        $('#aysa-robots-editor').val(robots.content || '');

        var $status = $('#aysa-sitemap-cache-status');
        var statusText = cached ? 'cached' : 'fresh';
        $status.removeClass('is-idle is-running is-failed is-completed')
            .addClass(cached ? 'is-idle' : 'is-completed')
            .text(statusText);

        var $checksBody = $('#aysa-sitemap-checks-body');
        if (!checks.length) {
            $checksBody.html('<tr><td colspan="3">No checks available.</td></tr>');
        } else {
            var checksHtml = '';
            checks.forEach(function(check) {
                checksHtml += '<tr>' +
                    '<td><strong>' + aysaEscapeHtml(check.label || check.id || 'Check') + '</strong></td>' +
                    '<td>' + sitemapStatusLabel(check.status || 'info') + '</td>' +
                    '<td>' + aysaEscapeHtml(check.message || '-') + '</td>' +
                '</tr>';
            });
            $checksBody.html(checksHtml);
        }

        var $sitemapsBody = $('#aysa-sitemap-urls-body');
        if (!sitemaps.length) {
            $sitemapsBody.html('<tr><td colspan="4">No sitemap endpoints detected.</td></tr>');
        } else {
            var mapHtml = '';
            sitemaps.forEach(function(entry) {
                var countLabel = (entry.entries_count === null || entry.entries_count === undefined || entry.entries_count === '') ? '-' : entry.entries_count;
                var statusCode = entry.status_code ? (' (' + entry.status_code + ')') : '';
                var statusDetail = entry.message ? ('<div style="margin-top:4px;font-size:12px;color:#6b7280;">' + aysaEscapeHtml(entry.message) + '</div>') : '';
                var providerLabel = entry.provider_label || entry.provider || '-';
                var state = entry.reachable ? 'pass' : (((entry.type || '') === 'redirect') ? 'warning' : 'warning');
                mapHtml += '<tr>' +
                    '<td><a href="' + aysaEscapeHtml(entry.url || '#') + '" target="_blank" rel="noopener">' + aysaEscapeHtml(entry.url || '-') + '</a></td>' +
                    '<td>' + aysaEscapeHtml(providerLabel) + '</td>' +
                    '<td>' + sitemapStatusLabel(state) + statusCode + statusDetail + '</td>' +
                    '<td>' + aysaEscapeHtml(countLabel) + '</td>' +
                '</tr>';
            });
            $sitemapsBody.html(mapHtml);
        }
    }

    function generateAysaSitemap() {
        var projectId = getProjectId();
        if (!projectId) {
            setSitemapMessage('Project ID not found.', 'error');
            return;
        }
        $('#aysa-sitemap-generate').prop('disabled', true).text('Generating...');
        setSitemapMessage('Generating AYSA sitemap and refreshing audit...', 'info');

        $.ajax({
            url: (window.aysa_params && window.aysa_params.ajax_url) ? window.aysa_params.ajax_url : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_technical_sitemap_generate',
                nonce: technicalNonce,
                project_id: projectId
            },
            success: function(resp) {
                if (!resp || !resp.success) {
                    setSitemapMessage((resp && resp.data) ? resp.data : 'Failed to generate AYSA sitemap.', 'error');
                    return;
                }
                var payload = resp.data && resp.data.data ? resp.data.data : null;
                if (payload) {
                    renderSitemapRobotsAudit(payload, false);
                }
                var generation = resp.data && resp.data.generation ? resp.data.generation : {};
                var modeLabel = generation.mode ? (' Mode: ' + generation.mode + '.') : '';
                var entriesLabel = generation.entries_count ? (' Entries: ' + generation.entries_count + '.') : '';
                setSitemapMessage('AYSA sitemap generated successfully.' + modeLabel + entriesLabel, 'success');
                $('#sitemap-content').data('loaded', true);
            },
            error: function(xhr) {
                var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : 'Failed to generate AYSA sitemap.';
                setSitemapMessage(msg, 'error');
            },
            complete: function() {
                $('#aysa-sitemap-generate').prop('disabled', false).text('Generate AYSA Sitemap');
            }
        });
    }

    function loadSitemapRobotsData(forceRefresh) {
        var projectId = getProjectId();
        if (!projectId) {
            setSitemapMessage('Project ID not found.', 'error');
            return;
        }
        $('#aysa-sitemap-refresh').prop('disabled', true).text('Auditing...');
        setSitemapMessage('Running Sitemap + Robots audit...', 'info');

        $.ajax({
            url: (window.aysa_params && window.aysa_params.ajax_url) ? window.aysa_params.ajax_url : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_technical_sitemap_robots_audit',
                nonce: technicalNonce,
                project_id: projectId,
                refresh: forceRefresh ? 1 : 0
            },
            success: function(resp) {
                if (!resp || !resp.success || !resp.data || !resp.data.data) {
                    setSitemapMessage('Failed to load sitemap/robots audit.', 'error');
                    return;
                }
                renderSitemapRobotsAudit(resp.data.data, !!resp.data.cached);
                var refreshLabel = resp.data.cached ? 'Loaded cached local snapshot.' : 'Audit completed and cached in local DB.';
                setSitemapMessage(refreshLabel, 'success');
                $('#sitemap-content').data('loaded', true);
            },
            error: function(xhr) {
                var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : 'Could not load sitemap/robots audit.';
                setSitemapMessage(msg, 'error');
            },
            complete: function() {
                $('#aysa-sitemap-refresh').prop('disabled', false).text('Run Audit');
            }
        });
    }

    function saveRobotsTxt() {
        var projectId = getProjectId();
        if (!projectId) {
            setSitemapMessage('Project ID not found.', 'error');
            return;
        }
        var content = $('#aysa-robots-editor').val() || '';
        $('#aysa-robots-save').prop('disabled', true).text('Saving...');

        $.ajax({
            url: (window.aysa_params && window.aysa_params.ajax_url) ? window.aysa_params.ajax_url : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_technical_robots_save',
                nonce: technicalNonce,
                project_id: projectId,
                robots_content: content
            },
            success: function(resp) {
                if (!resp || !resp.success) {
                    setSitemapMessage((resp && resp.data) ? resp.data : 'Failed to save robots.txt.', 'error');
                    return;
                }
                var payload = resp.data && resp.data.data ? resp.data.data : null;
                if (payload) {
                    renderSitemapRobotsAudit(payload, false);
                }
                setSitemapMessage('robots.txt saved successfully.', 'success');
            },
            error: function(xhr) {
                var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : 'Failed to save robots.txt.';
                setSitemapMessage(msg, 'error');
            },
            complete: function() {
                $('#aysa-robots-save').prop('disabled', false).text('Save robots.txt');
            }
        });
    }

    function restoreRobotsRecommended() {
        var projectId = getProjectId();
        if (!projectId) {
            setSitemapMessage('Project ID not found.', 'error');
            return;
        }
        $('#aysa-robots-restore').prop('disabled', true).text('Restoring...');

        $.ajax({
            url: (window.aysa_params && window.aysa_params.ajax_url) ? window.aysa_params.ajax_url : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_technical_robots_restore_default',
                nonce: technicalNonce,
                project_id: projectId
            },
            success: function(resp) {
                if (!resp || !resp.success) {
                    setSitemapMessage((resp && resp.data) ? resp.data : 'Failed to restore recommended robots.txt.', 'error');
                    return;
                }
                var payload = resp.data && resp.data.data ? resp.data.data : null;
                if (payload) {
                    renderSitemapRobotsAudit(payload, false);
                }
                setSitemapMessage('Recommended robots.txt restored.', 'success');
            },
            error: function(xhr) {
                var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : 'Failed to restore recommended robots.txt.';
                setSitemapMessage(msg, 'error');
            },
            complete: function() {
                $('#aysa-robots-restore').prop('disabled', false).text('Restore Recommended');
            }
        });
    }

    $('.aysa-tab-btn[data-target="sitemap"]').on('click', function() {
        var $panel = $('#sitemap-content');
        if (!$panel.data('loaded')) {
            loadSitemapRobotsData(false);
        }
    });

    $(document).on('click', '#aysa-sitemap-refresh', function() {
        loadSitemapRobotsData(true);
    });

    $(document).on('click', '#aysa-sitemap-generate', function() {
        generateAysaSitemap();
    });

    $(document).on('click', '#aysa-robots-save', function() {
        saveRobotsTxt();
    });

    $(document).on('click', '#aysa-robots-restore', function() {
        restoreRobotsRecommended();
    });
    
    // Sub-tab navigation
    $('.aysa-subtab-btn').on('click', function() {
        // Remove active class from all buttons and content
        $('.aysa-subtab-btn').removeClass('active');
        $('.aysa-subtab-content').removeClass('active');
        
        // Add active class to clicked button
        $(this).addClass('active');
        
        // Show corresponding content
        var target = $(this).data('target');
        $('#' + target + '-content').addClass('active');
    });
    
    // Select all functionality
    $('.aysa-select-all').on('change', function() {
        var isChecked = $(this).prop('checked');
        $(this).closest('table').find('.aysa-select-item').prop('checked', isChecked);
    });
    
    // Function to load 301 redirects data
    function loadRedirectsData(forceReload = false) {
        var $panel = $('#errors-301-panel');
        var siteDomain = window.location.protocol + '//' + window.location.host;
        var updateRedirectsMessage = (typeof setRedirectsMessage === 'function')
            ? setRedirectsMessage
            : function(text, type) {
                var $box = $('#aysa-redirects-message');
                if (!$box.length) {
                    return;
                }
                if (!text) {
                    $box.hide().text('').removeClass('info success warning error');
                    return;
                }
                $box.removeClass('info success warning error').addClass(type || 'info').html(text).show();
            };
        var hiddenRedirectNeedles = [
            '/wp-admin/',
            '/wp-login.php',
            '/admin-ajax.php',
            '/xmlrpc.php',
            '/api/',
            'api/aysapluginuser/',
            'api/seo/',
            'api/redirect',
            'api/goneurl',
            'rest_route=',
            'wc-ajax='
        ];

        function shouldHideRedirectRow(sourceUrl, targetUrl) {
            var haystacks = [String(sourceUrl || '').toLowerCase(), String(targetUrl || '').toLowerCase()];
            return haystacks.some(function(haystack) {
                return hiddenRedirectNeedles.some(function(needle) {
                    return haystack.indexOf(needle) !== -1;
                });
            });
        }
        
        // Clear loaded flag if force reload
        if (forceReload) {
            $panel.data('loaded', false);
        }
        
        var $tbody = $panel.find('tbody');
        $('#aysa-redirect-refresh').prop('disabled', true);
        updateRedirectsMessage('Loading 301 redirects...', 'info');
        
        // Show loading state
        $tbody.html(`
            <tr class="aysa-loading-row">
                <td colspan="7" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Loading 301 redirects...</span>
                    </div>
                </td>
            </tr>
        `);
            
        $.ajax({
            url: aysa_params.ajax_url,
            type: 'GET',
            data: {
                action: 'aysa_get_local_redirects',
                nonce: aysa_params.nonce
            }
        }).done(function(response) {
            if (!response || !response.success) {
                console.error('Failed to load redirects:', response);
                $tbody.html(`
                    <tr>
                        <td colspan="7" class="aysa-empty-message">
                            Error loading 301 redirects. Please try again.
                            <button id="aysa-retry-redirects" class="aysa-btn aysa-btn-outline" style="margin-top:10px;">
                                <span class="dashicons dashicons-update"></span> Retry
                            </button>
                        </td>
                    </tr>
                `);
                $('#aysa-retry-redirects').on('click', function() {
                    loadRedirectsData(true);
                });
                updateRedirectsMessage('Could not load 301 redirects.', 'error');
                return;
            }

            var payload = response.data || {};
            var redirects = Array.isArray(payload.redirects) ? payload.redirects : [];
            redirects = redirects.filter(function(r) {
                var sourceUrl = r.source_url || r.sourceUrl || r.SourceUrl || '';
                var destUrl = r.target_url || r.destinationUrl || r.DestinationUrl || '';
                return !shouldHideRedirectRow(sourceUrl, destUrl);
            });
            $tbody.empty();

            if (!redirects.length) {
                $tbody.append('<tr><td colspan="7" style="text-align:center;">No 301 redirects found for this website.</td></tr>');
                updateErrorsOverview({ active301: 0 });
                updateRedirectsMessage('No 301 redirects were found for this website.', 'info');
                return;
            }

            redirects.forEach(function(r) {
                var sourceUrl = r.source_url || r.sourceUrl || r.SourceUrl || '';
                var destUrl = r.target_url || r.destinationUrl || r.DestinationUrl || '';
                var scope = r.scope || 'local';
                var hitCount = Number(r.hit_count || r.totalBacklinks || 0);
                var status = Number(r.is_active || 0) === 0 ? 'Inactive' : 'Active';
                var localId = r.local_id || r.id || '';

                if (sourceUrl && !sourceUrl.startsWith('http')) {
                    sourceUrl = siteDomain + (sourceUrl.startsWith('/') ? sourceUrl : '/' + sourceUrl);
                }
                if (destUrl && !destUrl.startsWith('http')) {
                    destUrl = siteDomain + (destUrl.startsWith('/') ? destUrl : '/' + destUrl);
                }

                $tbody.append(
                    '<tr data-local-id="' + String(localId) + '" data-source="' + String(sourceUrl) + '">' +
                        '<td><input type="checkbox" class="aysa-select-item" value="' + String(localId || sourceUrl) + '"></td>' +
                        '<td>' + sourceUrl + '</td>' +
                        '<td>' + destUrl + '</td>' +
                        '<td>' + status + '</td>' +
                        '<td>' + hitCount + '</td>' +
                        '<td>' + scope + '</td>' +
                        '<td><span class="aysa-muted-note">Managed automatically</span></td>' +
                    '</tr>'
                );
            });
            
            $panel.data('loaded', true);
            updateErrorsOverview({ active301: redirects.length });
            updateRedirectsMessage('Loaded ' + redirects.length + ' 301 redirect' + (redirects.length === 1 ? '' : 's') + '.', 'success');
        }).fail(function(err) {
            console.error('Failed to load redirects:', err);
            $tbody.html(`
                <tr>
                    <td colspan="7" class="aysa-empty-message">
                        Error loading 301 redirects. Please try again.
                        <button id="aysa-retry-redirects" class="aysa-btn aysa-btn-outline" style="margin-top:10px;">
                            <span class="dashicons dashicons-update"></span> Retry
                        </button>
                    </td>
                </tr>
            `);
            
            // Add retry handler
            $('#aysa-retry-redirects').on('click', function() {
                loadRedirectsData(true);
            });
            updateRedirectsMessage('Could not load 301 redirects. Please try again.', 'error');
        }).always(function() {
            $('#aysa-redirect-refresh').prop('disabled', false);
        });
    }

    // Refresh button for 301 redirects
    $(document).on('click', '#aysa-redirect-refresh', function() {
        loadRedirectsData(true);
    });
    
    // Search functionality for 301 redirects
    $(document).on('input', '#aysa-redirect-search', function() {
        const searchTerm = $(this).val().toLowerCase();
        const $table = $('#aysa-redirect-table tbody');
        
        $table.find('tr').each(function() {
            const $row = $(this);
            const oldUrl = $row.find('td').eq(1).text().toLowerCase();
            const newUrl = $row.find('td').eq(2).text().toLowerCase();
            
            if (oldUrl.includes(searchTerm) || newUrl.includes(searchTerm)) {
                $row.show();
            } else {
                $row.hide();
            }
        });
    });
    
    // Filter functionality for 301 redirects
    $(document).on('change', '#aysa-redirect-filter', function() {
        const filterValue = $(this).val();
        const $table = $('#aysa-redirect-table tbody');
        
        $table.find('tr').each(function() {
            const $row = $(this);
            const status = $row.find('td').eq(3).text().toLowerCase();
            
            if (filterValue === 'all' || 
                (filterValue === 'active' && status.includes('active')) ||
                (filterValue === 'recent' && isRecentRedirect($row))) {
                $row.show();
            } else {
                $row.hide();
            }
        });
    });
    
    // Helper function to check if redirect is recent (last 7 days)
    function isRecentRedirect($row) {
        // This would need to be implemented based on your redirect data structure
        // For now, we'll return true as a placeholder
        return true;
    }
    // Load and render 404 Errors
    $('.aysa-tab-btn[data-target="errors"]').on('click', function() {
        showErrorsHubMessage('Loading unified error data...', 'info');
        openErrorsSubtab($('.aysa-errors-subtab-btn.active').data('errors-target') || '404');
    });
    
    let aysa404CurrentPage = 1;
    let aysa404TotalPages = 1;
    const aysa404PerPage = 25;
    let aysa404SortBy = 'last_hit';
    let aysa404SortDir = 'desc';

    // Funcție pentru încărcarea datelor 404
    function load404Data(projectId, page = 1, filter = 'all', search = '', sortBy = aysa404SortBy, sortDir = aysa404SortDir) {
        const $tbody = $('#aysa-404-table tbody');
        
        // Arată starea de loading
        $tbody.html(`
            <tr class="aysa-loading-row">
                <td colspan="10" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Loading 404 errors...</span>
                    </div>
                </td>
            </tr>
        `);
        
        aysa404CurrentPage = Math.max(1, parseInt(page, 10) || 1);

        // Folosim AJAX WordPress pentru a obține datele locale în loc de API
        $.ajax({
            url: aysa_params.ajax_url,
            type: 'GET',
            data: {
                action: 'aysa_get_404_errors',
                nonce: aysa_params.nonce,
                project_id: projectId,
                page: aysa404CurrentPage,
                per_page: aysa404PerPage,
                filter: filter,
                search: search,
                sort_by: sortBy,
                sort_dir: sortDir
            },
            success: function(response) {
                if (response.success) {
                    // Actualizează statisticile
                    updateErrorStats(response.data);
                    
                    // Procesează și afișează datele
                    renderErrorData(response.data.errors, $tbody);
                    
                    // Actualizează paginarea
                    updatePagination(response.data);
                    if (response.data && response.data.sort_by) {
                        aysa404SortBy = String(response.data.sort_by);
                    }
                    if (response.data && response.data.sort_dir) {
                        aysa404SortDir = String(response.data.sort_dir);
                    }
                    update404SortHeaders();
                } else {
                    $tbody.html(`
                        <tr>
                            <td colspan="10" class="aysa-empty-message">
                                Error loading 404 data: ${response.data || 'Unknown error'}
                                <button id="aysa-retry-404" class="aysa-btn aysa-btn-outline" style="margin-top:10px;">
                                    <span class="dashicons dashicons-update"></span> Retry
                                </button>
                            </td>
                        </tr>
                    `);
                }
            },
            error: function(xhr, status, error) {
                $tbody.html(`
                    <tr>
                        <td colspan="10" class="aysa-empty-message">
                            Could not load 404 data: ${error || 'Request failed'} (Status: ${xhr.status})
                            <button id="aysa-retry-404" class="aysa-btn aysa-btn-outline" style="margin-top:10px;">
                                <span class="dashicons dashicons-update"></span> Retry
                            </button>
                        </td>
                    </tr>
                `);
            },
            complete: function() {
                // Adaugă handler pentru retry
                $('#aysa-retry-404').on('click', function() {
                    load404Data(projectId, page, filter, search);
                });
            }
        });
    }
    
    // Funcție pentru actualizarea statisticilor 404
    function updateErrorStats(data) {
        // Folosim datele reale furnizate de server
        const totalErrors = data.total || 0;
        const uniqueVisitors = data.unique_visitors || Math.round(totalErrors * 0.7); // fallback la estimare
        const trafficLoss = data.traffic_loss || (totalErrors > 0 ? Math.min(25, Math.round(totalErrors / 4)) : 0);
        const fixedErrors = data.fixed_errors || Math.round(totalErrors * 0.2); // fallback la estimare
        
        // Actualizează elementele UI
        $('#aysa-total-404').text(totalErrors);
        $('#aysa-unique-visitors-404').text(uniqueVisitors);
        $('#aysa-traffic-loss-404').text(trafficLoss + '%');
        $('#aysa-fixed-404').text(fixedErrors);

        const errors = Array.isArray(data.errors) ? data.errors : [];
        let redirectReady = 0;
        let goneReady = 0;
        let conflicts = 0;
        let reviewPending = 0;

        errors.forEach(function(error) {
            const bestAction = String(error.best_redirect_action || 'none');
            const confidence = Number(error.best_redirect_confidence || 0);
            const sourceUrl = String(error.url || '').toLowerCase();
            const referer = String(error.referer || '').toLowerCase();
            const bestTarget = String(error.best_redirect_url || '');
            const isNoise = sourceUrl.indexOf('/wp-admin/') !== -1
                || sourceUrl.indexOf('/wp-login.php') !== -1
                || sourceUrl.indexOf('/xmlrpc.php') !== -1
                || sourceUrl.indexOf('/.env') !== -1
                || referer.indexOf('/wp-admin/') !== -1;

            if (bestAction === 'redirect' && bestTarget && confidence >= 85) {
                redirectReady++;
            } else if (!bestTarget && isNoise === false && Number(error.hit_count || 0) <= 1) {
                goneReady++;
            } else {
                reviewPending++;
            }

            if (bestTarget && bestTarget.indexOf(String(error.url || '')) !== -1) {
                conflicts++;
            }
        });

        updateErrorsOverview({
            active404: totalErrors,
            redirectReady: redirectReady,
            goneReady: goneReady,
            conflicts: conflicts,
            reviewPending: reviewPending
        });

        const dataSources = data && typeof data.data_sources === 'object' ? data.data_sources : {};
        const siteAuditCount = Number(dataSources.site_audit || 0);
        const trackerCount = Number(dataSources.tracker || 0);
        showErrorsHubMessage(
            '404 review queue loaded: ' + totalErrors + ' URLs, ' + siteAuditCount + ' from Site Audit, ' + trackerCount + ' from live tracker, ' + redirectReady + ' redirect-ready, ' + goneReady + ' likely 410 candidates.',
            'success'
        );
    }
    
    // Funcție pentru afișarea datelor de eroare în tabel
    function renderErrorData(data, $tbody) {
        $tbody.empty();
        
        if (!data || data.length === 0) {
            $tbody.html(`
                <tr>
                    <td colspan="10" class="aysa-empty-message">
                        No 404 errors found. Your site appears to be working correctly.
                    </td>
                </tr>
            `);
            return;
        }
        
        // Transformă datele în formatul necesar pentru afișare
        const siteDomain = window.location.protocol + '//' + window.location.host;
        
        data.forEach(function(error) {
            // Format as relative time from timestamp (convert to milliseconds)
            const lastVisit = formatRelativeTime(error.timestamp * 1000);
            
            // Get hit count
            const hitCount = (error.hit_count === undefined || error.hit_count === null) ? 1 : Number(error.hit_count);
            const hitClass = hitCount > 10 ? 'high' : (hitCount > 5 ? 'medium' : '');
            
            // Determină tipul de vizitator (utilizator sau bot)
            const isBot = error.is_bot || (error.userAgent && (
                error.userAgent.includes('bot') || 
                error.userAgent.includes('crawl') || 
                error.userAgent.includes('spider')
            ));
            
            // Pregătește URL-ul pentru afișare
            let displayUrl = error.url || '';
            if (displayUrl.startsWith(siteDomain)) {
                displayUrl = displayUrl.replace(siteDomain, '');
            }
            if (!displayUrl) displayUrl = '/';
            
            const isReadOnly = Number(error.read_only || 0) === 1 || !Number(error.id || 0);
            const isAdminNoise = Number(error.is_admin_noise || 0) === 1;
            const bestRedirectUrl = String(error.best_redirect_url || '');
            const bestConfidence = Number(error.best_redirect_confidence || 0);
            const bestStatus = String(error.best_redirect_status || 'none');
            const bestAction = String(error.best_redirect_action || 'none');
            const bestTitle = String(error.best_redirect_match_title || '');
            const bestType = String(error.best_redirect_match_type || '');
            const source = String(error.source || 'tracker');
            const sourceBadge = source === 'site_audit'
                ? '<span class="aysa-inline-badge aysa-badge-neutral" title="Detected in latest Site Audit crawl">Site Audit</span>'
                : '<span class="aysa-inline-badge aysa-badge-good" title="Detected from live local 404 tracker">Live</span>';
            let bestMatchHtml = '<span class="aysa-muted-note">No reliable match</span>';
            if (bestAction === 'gone') {
                bestMatchHtml = '<span class="aysa-inline-badge aysa-badge-neutral">Recommend 410 Gone</span>';
            } else if (bestRedirectUrl) {
                const safeLabel = bestTitle ? `${bestTitle}` : bestRedirectUrl;
                const meta = bestType ? `<span class="aysa-muted-note" style="display:block;">${bestType}</span>` : '';
                bestMatchHtml = `<a href="${bestRedirectUrl}" target="_blank" title="${bestRedirectUrl}">${safeLabel}</a>${meta}`;
            }
            let confidenceHtml = '<span class="aysa-inline-badge aysa-badge-neutral">N/A</span>';
            if (bestAction === 'gone') {
                confidenceHtml = '<span class="aysa-inline-badge aysa-badge-neutral">Review</span>';
            } else if (bestConfidence > 0) {
                if (bestConfidence >= 85) {
                    confidenceHtml = `<span class="aysa-inline-badge aysa-badge-good">${bestConfidence}% high</span>`;
                } else if (bestConfidence >= 65) {
                    confidenceHtml = `<span class="aysa-inline-badge aysa-badge-warning">${bestConfidence}% review</span>`;
                } else {
                    confidenceHtml = `<span class="aysa-inline-badge aysa-badge-neutral">${bestConfidence}% low</span>`;
                }
            }
            const actionButtons = isReadOnly
                ? `<div class="aysa-action-buttons"><span class="aysa-muted-note">Audit only</span></div>`
                : `<div class="aysa-action-buttons">
                        <button class="aysa-btn-small aysa-404-redirect" data-id="${error.id || 0}" data-url="${displayUrl}">Redirect</button>
                        <button class="aysa-btn-small aysa-mark-gone" data-id="${error.id || 0}">Mark Gone</button>
                   </div>`;

            // Adaugă rândul în tabel
            $tbody.append(`
                <tr data-id="${error.id || 0}" data-url="${displayUrl}" data-best-redirect="${bestRedirectUrl}" data-best-confidence="${bestConfidence}" data-best-action="${bestAction}" data-best-status="${bestStatus}">
                    <td><input type="checkbox" class="aysa-select-item" value="${error.id || 0}"></td>
                    <td>
                        <div class="aysa-404-type-icon ${isBot ? 'bot' : 'user'}">
                            <span class="dashicons dashicons-${isBot ? 'admin-site' : 'admin-users'}"></span>
                        </div>
                    </td>
                    <td class="aysa-404-url-cell">${displayUrl} ${sourceBadge}</td>
                    <td><span class="aysa-hit-count ${hitClass}">${hitCount}</span></td>
                    <td>${lastVisit}</td>
                    <td>${error.referer ? `<a href="${error.referer}" target="_blank" class="aysa-referer-link">${error.referer}</a>${isAdminNoise ? ' <span class="aysa-inline-badge aysa-badge-neutral">Admin/Internal</span>' : ''}` : 'Direct'}</td>
                    <td>${bestMatchHtml}</td>
                    <td>${confidenceHtml}</td>
                    <td>${actionButtons}</td>
                </tr>
            `);
        });
        
        // Actualizează numărul de înregistrări afișate
        $('#aysa-404-showing').text(data.length);
    }
    
    // Format relative time in English but using Romanian timezone
    function formatRelativeTime(timestamp) {
        if (!timestamp) {
            return 'Unknown';
        }
        
        const now = new Date();
        const date = new Date(timestamp);
        
        // Check if date is valid
        if (isNaN(date.getTime())) {
            console.error('Invalid timestamp:', timestamp);
            return 'Invalid date';
        }
        
        const diff = Math.floor((now - date) / 1000); // difference in seconds
        
        // English language mapping
        if (diff < 60) {
            if (diff === 1) return '1 second ago';
            return diff + ' seconds ago';
        } else if (diff < 3600) {
            const minutes = Math.floor(diff / 60);
            if (minutes === 1) return '1 minute ago';
            return minutes + ' minutes ago';
        } else if (diff < 86400) {
            const hours = Math.floor(diff / 3600);
            if (hours === 1) return '1 hour ago';
            return hours + ' hours ago';
        } else if (diff < 2592000) {
            const days = Math.floor(diff / 86400);
            if (days === 1) return '1 day ago';
            return days + ' days ago';
        } else if (diff < 31536000) {
            const months = Math.floor(diff / 2592000);
            if (months === 1) return '1 month ago';
            return months + ' months ago';
        } else {
            const years = Math.floor(diff / 31536000);
            if (years === 1) return '1 year ago';
            return years + ' years ago';
        }
    }
    
    // Funcție pentru actualizarea paginării
    function updatePagination(data) {
        const payload = data && typeof data === 'object' ? data : {};
        const pagination = payload.pagination && typeof payload.pagination === 'object' ? payload.pagination : {};
        const total = Number(payload.total || payload.total_errors || 0);
        const errorsLen = Array.isArray(payload.errors) ? payload.errors.length : 0;
        const perPage = Number(pagination.per_page || payload.per_page || aysa404PerPage || 25);

        if (pagination.current_page || payload.page) {
            aysa404CurrentPage = Math.max(1, Number(pagination.current_page || payload.page || 1));
        }

        if (pagination.total_pages) {
            aysa404TotalPages = Math.max(1, Number(pagination.total_pages));
        } else if (total > 0 && perPage > 0) {
            aysa404TotalPages = Math.max(1, Math.ceil(total / perPage));
        } else {
            aysa404TotalPages = (errorsLen >= perPage) ? Math.max(1, aysa404CurrentPage + 1) : Math.max(1, aysa404CurrentPage);
        }

        $('#aysa-404-total').text(total);
        $('#aysa-404-page-info').text(`(page ${aysa404CurrentPage} of ${aysa404TotalPages})`);
        render404PageNumbers(aysa404CurrentPage, aysa404TotalPages);

        // Actualizează butoanele de paginare
        $('#aysa-404-prev').prop('disabled', aysa404CurrentPage <= 1);
        $('#aysa-404-next').prop('disabled', aysa404CurrentPage >= aysa404TotalPages);
    }

    function render404PageNumbers(current, total) {
        const $wrap = $('#aysa-404-page-numbers');
        if (!$wrap.length) {
            return;
        }
        $wrap.empty();
        if (total <= 1) {
            return;
        }

        function addPage(page) {
            const activeClass = page === current ? ' is-active' : '';
            $wrap.append(`<button type="button" class="aysa-page-number-btn${activeClass}" data-page="${page}">${page}</button>`);
        }
        function addEllipsis() {
            $wrap.append('<span class="aysa-page-number-ellipsis">…</span>');
        }

        if (total <= 7) {
            for (let p = 1; p <= total; p++) addPage(p);
            return;
        }

        addPage(1);
        if (current > 4) addEllipsis();

        const start = Math.max(2, current - 1);
        const end = Math.min(total - 1, current + 1);
        for (let p = start; p <= end; p++) addPage(p);

        if (current < total - 3) addEllipsis();
        addPage(total);
    }

    function update404SortHeaders() {
        const $headers = $('#aysa-404-table thead th.aysa-sortable-header');
        $headers.removeClass('is-sorted-asc is-sorted-desc');
        if (!aysa404SortBy) {
            return;
        }
        const $active = $headers.filter(`[data-sort="${aysa404SortBy}"]`);
        if (!$active.length) {
            return;
        }
        $active.addClass(aysa404SortDir === 'asc' ? 'is-sorted-asc' : 'is-sorted-desc');
    }
    
    // Funcție pentru generarea de sugestii de redirectare
    function generateSuggestions(url) {
        // Această funcție ar trebui să primească date de la API
        // Pentru moment, utilizăm o logică simplă pentru sugestii
        const suggestions = [];
        
        // Eliminăm extensiile de fișier pentru a găsi o pagină potențială
        if (url.includes('.')) {
            const withoutExtension = url.replace(/\.[^/.]+$/, '');
            suggestions.push(withoutExtension);
        }
        
        // Transformă URL-uri cu majuscule sau diacritice
        const normalized = url.toLowerCase()
            .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
            .replace(/[^a-z0-9\/\-\_]/g, '-');
        
        if (normalized !== url) {
            suggestions.push(normalized);
        }
        
        // Elimină numere sau ID-uri din URL
        const withoutNumbers = url.replace(/\/\d+\/?/, '/');
        if (withoutNumbers !== url) {
            suggestions.push(withoutNumbers);
        }
        
        // Corectează greșeli comune în URL-uri
        const commonMistakes = {
            'categoria': 'category',
            'categorii': 'categories',
            'pagina': 'page',
            'produse': 'products',
            'produs': 'product',
            'articol': 'article',
            'articole': 'articles',
            'blog-post': 'post'
        };
        
        for (const [mistake, correction] of Object.entries(commonMistakes)) {
            if (url.includes(mistake)) {
                suggestions.push(url.replace(mistake, correction));
            }
        }
        
        // Returnăm unic și filtrăm valorile vide
        return [...new Set(suggestions)].filter(s => s);
    }
    
    // Handler pentru butonul de auto-fix
    $('#aysa-404-auto-fix').on('click', function() {
        const selectedIds = $('#aysa-404-table tbody input:checked').map(function() {
            return $(this).val();
        }).get();
        
        if (selectedIds.length === 0) {
            showErrorModal('Please select at least one 404 error to fix.');
            return;
        }
        
        // Dacă e selectat doar unul, deschide dialogul de sugestii
        if (selectedIds.length === 1) {
            const $row = $('#aysa-404-table tbody input[value="' + selectedIds[0] + '"]').closest('tr');
            const url = $row.data('url');
            const bestUrl = String($row.data('best-redirect') || '');
            
            showFixDialog(selectedIds[0], url, bestUrl);
        } else {
            showErrorModal('For multiple rows, use "Bulk Redirect" or "Bulk Mark Gone".');
        }
    });
    
    // Funcție pentru afișarea dialogului de corecție
    function showFixDialog(id, url, bestUrl = '') {
        // Resetăm dialogul
        $('.aysa-404-url').text(url);
        $('.aysa-suggestion-options').empty();
        $('#aysa-custom-redirect').val('');
        
        // Generăm sugestii
        let suggestions = generateSuggestions(url);
        if (bestUrl) {
            suggestions = [bestUrl].concat(suggestions.filter(function(item) {
                return item !== bestUrl;
            }));
        }
        
        if (suggestions.length > 0) {
            suggestions.forEach(function(suggestion, index) {
                $('.aysa-suggestion-options').append(`
                    <div class="aysa-suggestion-option ${index === 0 ? 'selected' : ''}" data-url="${suggestion}">
                        <input type="radio" name="suggestion" value="${suggestion}" ${index === 0 ? 'checked' : ''}>
                        <span>${suggestion}</span>
                    </div>
                `);
            });
        } else {
            $('.aysa-suggestion-options').append(`
                <div class="aysa-no-suggestions">
                    No automatic suggestions available.
                </div>
            `);
        }
        
        // Setăm ID-ul curent pentru referință
        $('#aysa-404-autofix-dialog').data('id', id);
        
        // Arătăm dialogul
        $('#aysa-404-autofix-dialog').show();
    }

    // Bulk auto-redirect using best high-confidence suggestions from current table.
    function runBulkBestRedirects() {
        const selectedRows = $('#aysa-404-table tbody input:checked').map(function() {
            return $(this).closest('tr');
        }).get();

        if (!selectedRows.length) {
            showErrorModal('Select at least one row.');
            return;
        }

        const queue = [];
        selectedRows.forEach(function(rowEl) {
            const $row = $(rowEl);
            const id = parseInt($row.attr('data-id') || '0', 10);
            const target = String($row.attr('data-best-redirect') || '');
            const confidence = Number($row.attr('data-best-confidence') || 0);
            const action = String($row.attr('data-best-action') || '');
            if (id > 0 && target && action === 'redirect' && confidence >= 85) {
                queue.push({ id: id, target: target });
            }
        });

        if (!queue.length) {
            showErrorModal('No high-confidence redirect suggestions found in selected rows (need >= 85%).');
            return;
        }

        let done = 0;
        let failed = 0;

        function runNext() {
            if (!queue.length) {
                const projectId = getProjectId();
                const filter = $('#aysa-404-filter').val() || 'all';
                const search = $('#aysa-404-search').val() || '';
                load404Data(projectId, aysa404CurrentPage, filter, search);
                if (failed > 0) {
                    showErrorModal(`Applied ${done - failed} redirects, ${failed} failed.`);
                } else {
                    showSuccessModal(`Applied ${done} high-confidence redirects.`);
                }
                return;
            }

            const item = queue.shift();
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_create_redirect',
                    nonce: aysa_params.nonce,
                    error_id: item.id,
                    target_url: item.target
                },
                complete: function(xhr) {
                    done++;
                    if (!(xhr && xhr.responseJSON && xhr.responseJSON.success)) {
                        failed++;
                    }
                    runNext();
                }
            });
        }

        runNext();
    }

    $('#aysa-404-auto-best, #aysa-bulk-auto-best-redirects').on('click', function() {
        runBulkBestRedirects();
    });
    
    // Handler pentru opțiunile de sugestii
    $(document).on('click', '.aysa-suggestion-option', function() {
        $('.aysa-suggestion-option').removeClass('selected');
        $(this).addClass('selected');
        $(this).find('input[type="radio"]').prop('checked', true);
    });
    
    // Handler pentru închiderea dialogului
    $(document).on('click', '.aysa-dialog-close', function() {
        $('#aysa-404-autofix-dialog').hide();
    });
    
    // Handler pentru butonul de aplicare a redirectării
    $('#aysa-apply-suggestion').on('click', function() {
        const id = $('#aysa-404-autofix-dialog').data('id');
        const url = $('.aysa-404-url').text();
        
        // Verificăm dacă utilizatorul a introdus un URL personalizat
        let redirectUrl = $('#aysa-custom-redirect').val();
        
        // Dacă nu, folosim sugestia selectată
        if (!redirectUrl) {
            redirectUrl = $('input[name="suggestion"]:checked').val();
        }
        
        if (!redirectUrl) {
            showErrorModal('Please select a suggestion or enter a custom URL.');
            return;
        }
        
        // Aplicăm redirectarea
        applyFixToUrl(id, url, redirectUrl);
        
        // Închidem dialogul
        $('#aysa-404-autofix-dialog').hide();
    });
    
    // Handler pentru butonul "Mark as Gone" din dialog
    $('#aysa-mark-gone-dialog').on('click', function() {
        const $dialog = $('#aysa-404-autofix-dialog');
        const errorId = $dialog.data('error-id');
        // Deschide modalul modern pentru motiv
        $('#aysa-gone-source-url').text($('.aysa-404-url').text());
        $('#aysa-gone-reason').val('');
        $('#aysa-gone-modal').data('error-id', errorId);
        $dialog.hide();
        showModal('aysa-gone-modal');
    });
    
    // Funcție pentru aplicarea corecției la un URL
    function applyFixToUrl(id, sourceUrl, destUrl) {
        if (window.AYSA_DEBUG === true) {
            console.log('Applying fix:', {id, sourceUrl, destUrl});
        }
        
        // Obținem project ID
        const projectId = getProjectId();
        
        // Verifică dacă URL-urile sunt relative și adaugă domeniul dacă e necesar
        const siteDomain = window.location.protocol + '//' + window.location.host;
        const source = sourceUrl.startsWith('http') ? sourceUrl : siteDomain + (sourceUrl.startsWith('/') ? sourceUrl : '/' + sourceUrl);
        const dest = destUrl.startsWith('http') ? destUrl : siteDomain + (destUrl.startsWith('/') ? destUrl : '/' + destUrl);
        
        // Extrage căile relative pentru .htaccess
        const sourceRelative = sourceUrl.startsWith('http') ? new URL(sourceUrl).pathname : (sourceUrl.startsWith('/') ? sourceUrl : '/' + sourceUrl);
        const destRelative = destUrl.startsWith('http') ? new URL(destUrl).pathname : (destUrl.startsWith('/') ? destUrl : '/' + destUrl);
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('Redirect', { 
            SourceUrl: source, 
            DestinationUrl: dest, 
            Status: 'AutoFixed', 
            TotalBacklinks: 0, 
            ProjectId: projectId 
        })
        .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('Redirect created in API:', response);
            }
            
            // 2. Apoi adaugă redirect-ul în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_redirect',
                    source: sourceRelative,
                    destination: destRelative,
                    nonce: aysa_params.nonce
                },
                success: function(htaccessResponse) {
                    if (window.AYSA_DEBUG === true) {
                        console.log('Htaccess update response:', htaccessResponse);
                    }
                    
                    if (htaccessResponse.success) {
                        // Marcăm rândul ca fiind corectat
                        $('#aysa-404-table tbody tr[data-id="' + id + '"]').fadeOut(300, function() {
                            $(this).remove();
                            
                            // Actualizăm statisticile
                            const fixedCount = parseInt($('#aysa-fixed-404').text()) || 0;
                            $('#aysa-fixed-404').text(fixedCount + 1);
                            
                            // Actualizăm numărul de înregistrări afișate
                            const showing = parseInt($('#aysa-404-showing').text()) || 0;
                            if (showing > 0) {
                                $('#aysa-404-showing').text(showing - 1);
                            }
                        });
                    } else {
                        showErrorModal('Redirect created in API but failed to update .htaccess: ' + htaccessResponse.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to update .htaccess:', error);
                    showErrorModal('Redirect created in API but failed to update .htaccess');
                }
            });
              })
              .catch(function(err) {
            console.error('Error creating redirect:', err);
            showErrorModal('Error creating redirect');
        });
    }
    
    // Funcție pentru aplicarea statusului 410 Gone
    function markAsGone(id, url, reason) {
        if (window.AYSA_DEBUG === true) {
            console.log('Marking as gone:', {id, url, reason});
        }
        
        // Obținem project ID
        const projectId = getProjectId();
        
        // Verifică dacă URL-ul este relativ și adaugă domeniul dacă e necesar
        const siteDomain = window.location.protocol + '//' + window.location.host;
        const fullUrl = url.startsWith('http') ? url : siteDomain + (url.startsWith('/') ? url : '/' + url);
        
        // Extrage calea relativă pentru .htaccess
        const urlRelative = url.startsWith('http') ? new URL(url).pathname : (url.startsWith('/') ? url : '/' + url);
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('GoneUrl', { 
            Url: fullUrl, 
            Reason: reason || 'Content no longer available', 
            ProjectId: projectId 
        })
        .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('API Gone URL created:', response);
            }
            
            // 2. Apoi adaugă regula Gone în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_gone',
                    url: urlRelative,
                    nonce: aysa_params.nonce
                },
                success: function(htaccessResponse) {
                    if (window.AYSA_DEBUG === true) {
                        console.log('Htaccess update response:', htaccessResponse);
                    }
                    
                    if (htaccessResponse.success) {
                        // Marcăm rândul ca fiind tratat
                        $('#aysa-404-table tbody tr[data-id="' + id + '"]').fadeOut(300, function() {
                            $(this).remove();
                            
                            // Actualizăm statisticile
                            const fixedCount = parseInt($('#aysa-fixed-404').text()) || 0;
                            $('#aysa-fixed-404').text(fixedCount + 1);
                            
                            // Actualizăm numărul de înregistrări afișate
                            const showing = parseInt($('#aysa-404-showing').text()) || 0;
                            if (showing > 0) {
                                $('#aysa-404-showing').text(showing - 1);
                            }
                        });
                    } else {
                        showErrorModal('URL marked as Gone in API but failed to update .htaccess: ' + htaccessResponse.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to update .htaccess:', error);
                    showErrorModal('URL marked as Gone in API but failed to update .htaccess');
                }
            });
        })
        .catch(function(err) {
            console.error('Error marking URL as gone:', err);
            showErrorModal('Error marking URL as gone');
        });
    }
    
    // Eveniment pentru butonul de fix 404
    $(document).on('click', '.aysa-fix-404', function() {
        const id = $(this).data('id');
        const $row = $(this).closest('tr');
        const url = $row.find('.aysa-404-url-cell').text();
        const suggestedUrl = $row.find('.aysa-suggested-url').text();
        
        // Deschide dialog cu sugestia
        const $dialog = $('#aysa-404-autofix-dialog');
        $dialog.find('.aysa-404-url').text(url);
        
        // Populează opțiunile de sugestii
        const $options = $dialog.find('.aysa-suggestion-options').empty();
        
        // Adaugă URL-ul sugerat dacă există
        if (suggestedUrl && suggestedUrl !== '-') {
            $options.append(`
                <div class="aysa-suggestion-option">
                    <input type="radio" name="suggested_url" id="suggestion-auto" value="${suggestedUrl}" checked>
                    <label for="suggestion-auto">
                        <span class="aysa-suggestion-url">${suggestedUrl}</span>
                        <span class="aysa-suggestion-match">Algoritm automat</span>
                    </label>
                </div>
            `);
        }
        
        // Adaugă opțiunea pentru pagina principală
        $options.append(`
            <div class="aysa-suggestion-option">
                <input type="radio" name="suggested_url" id="suggestion-home" value="/" ${!suggestedUrl || suggestedUrl === '-' ? 'checked' : ''}>
                <label for="suggestion-home">
                    <span class="aysa-suggestion-url">/</span>
                    <span class="aysa-suggestion-match">Pagina principală</span>
                </label>
            </div>
        `);
        
        // Resetează input-ul pentru URL personalizat
        $dialog.find('#aysa-custom-redirect').val('');
        
        // Arată dialogul
        $dialog.show();
        
        // Salvează ID-ul curent în dialog pentru referință ulterioară
        $dialog.data('error-id', id);
    });
    
    // Eveniment pentru aplicarea sugestiei din dialog
    $(document).on('click', '#aysa-apply-suggestion', function() {
        const $dialog = $('#aysa-404-autofix-dialog');
        const errorId = $dialog.data('error-id');
        
        // Obține URL-ul țintă selectat sau introdus
        let targetUrl = $dialog.find('input[name="suggested_url"]:checked').val();
        const customUrl = $dialog.find('#aysa-custom-redirect').val().trim();
        
        if (customUrl) {
            targetUrl = customUrl;
        }
        
        // Validare URL
        if (!targetUrl) {
            showErrorModal('Please select or enter a target URL');
            return;
        }
        
        // Trimite cererea AJAX pentru a crea un redirect
        $.ajax({
            url: aysa_params.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_create_redirect',
                nonce: aysa_params.nonce,
                error_id: errorId,
                target_url: targetUrl
            },
            success: function(response) {
                if (response.success) {
                    showSuccessModal(response.data.message || 'Redirect created successfully');
                    
                    // Actualizează UI - ascunde rândul
                    $(`#aysa-404-table tbody tr[data-id="${errorId}"]`).fadeOut(300, function() {
                        $(this).remove();
                        
                        // Dacă nu mai sunt rânduri, afișează mesaj
                        if ($('#aysa-404-table tbody tr').length === 0) {
                            $('#aysa-404-table tbody').html(`
                                <tr>
                                    <td colspan="8" class="aysa-empty-message">
                                        No 404 errors found. Your site appears to be working correctly.
                                    </td>
                                </tr>
                            `);
                        }
                    });
                } else {
                    showErrorModal('Error: ' + (response.data || 'Failed to create redirect'));
                }
                
                // Închide dialogul
                $dialog.hide();
            },
            error: function() {
                showErrorModal('Error: Failed to communicate with the server');
            }
        });
    });
    
    // Eveniment pentru butonul "Mark as Gone" din dialog
    $(document).on('click', '#aysa-mark-gone-dialog', function() {
        const $dialog = $('#aysa-404-autofix-dialog');
        const errorId = $dialog.data('error-id');
        // Deschide modalul modern pentru motiv
        $('#aysa-gone-source-url').text($('.aysa-404-url').text());
        $('#aysa-gone-reason').val('');
        $('#aysa-gone-modal').data('error-id', errorId);
        $dialog.hide();
        showModal('aysa-gone-modal');
    });
    
    // Eveniment pentru butonul "Ignore"
    $(document).on('click', '.aysa-ignore-404', function() {
        const id = $(this).data('id');
        const $row = $(this).closest('tr');
        
        // Cere confirmare
        const confirmed = confirm('Are you sure you want to ignore this 404 error?');
        if (!confirmed) {
            return;
        }
        
        // Trimite cererea AJAX
        $.ajax({
            url: aysa_params.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_ignore_404',
                nonce: aysa_params.nonce,
                error_id: id
            },
            success: function(response) {
                if (response.success) {
                    // Actualizează UI - ascunde rândul
                    $row.fadeOut(300, function() {
                        $(this).remove();
                        
                        // Dacă nu mai sunt rânduri, afișează mesaj
                        if ($('#aysa-404-table tbody tr').length === 0) {
                            $('#aysa-404-table tbody').html(`
                                <tr>
                                    <td colspan="8" class="aysa-empty-message">
                                        No 404 errors found. Your site appears to be working correctly.
                                    </td>
                                </tr>
                            `);
                        }
                    });
                } else {
                    alert('Error: ' + (response.data || 'Failed to ignore 404 error'));
                }
            },
            error: function() {
                alert('Error: Failed to communicate with the server');
            }
        });
    });
    
    // Handler pentru butonul de bulk ignore
    $('#aysa-bulk-ignore').on('click', function() {
        const selectedIds = $('#aysa-404-table tbody input:checked').map(function() {
            return $(this).val();
        }).get();
        
        if (selectedIds.length === 0) {
            alert('Please select at least one 404 error to ignore.');
            return;
        }
        
        if (confirm(`Are you sure you want to ignore ${selectedIds.length} 404 error(s)?`)) {
            const realIds = selectedIds
                .map(id => parseInt(id, 10))
                .filter(id => id > 0);

            if (realIds.length === 0) {
                showErrorModal('Selected rows are read-only crawl findings. Only live tracked 404 rows can be ignored.');
                return;
            }

            let completed = 0;
            let failed = 0;
            realIds.forEach(function(id) {
                $.ajax({
                    url: aysa_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'aysa_ignore_404',
                        nonce: aysa_params.nonce,
                        error_id: id
                    },
                    complete: function(xhr) {
                        completed++;
                        if (!(xhr && xhr.responseJSON && xhr.responseJSON.success)) {
                            failed++;
                        }
                        if (completed === realIds.length) {
                            if (failed > 0) {
                                showErrorModal(`Ignored ${realIds.length - failed} rows, ${failed} failed. Reloading list.`);
                            }
                            const projectId = getProjectId();
                            const filter = $('#aysa-404-filter').val() || 'all';
                            const search = $('#aysa-404-search').val() || '';
                            load404Data(projectId, aysa404CurrentPage, filter, search);
                        }
                    }
                });
            });
        }
    });
    
    // Handler pentru refresh buton
    $('#aysa-404-refresh').on('click', function() {
        const projectId = getProjectId();
        const filter = $('#aysa-404-filter').val() || 'all';
        const search = $('#aysa-404-search').val() || '';
        
        load404Data(projectId, 1, filter, search);
    });
    
    // Handler pentru căutare
    let searchTimeout;
    $('#aysa-404-search').on('input', function() {
        clearTimeout(searchTimeout);
        
        searchTimeout = setTimeout(function() {
            const projectId = getProjectId();
            const filter = $('#aysa-404-filter').val() || 'all';
            const search = $('#aysa-404-search').val() || '';
            
            load404Data(projectId, 1, filter, search);
        }, 500);
    });
    
    // Handler pentru filtrare
    $('#aysa-404-filter').on('change', function() {
        const projectId = getProjectId();
        const filter = $(this).val() || 'all';
        const search = $('#aysa-404-search').val() || '';
        
        load404Data(projectId, 1, filter, search);
    });
    
    // Handler pentru paginare
    $('#aysa-404-prev, #aysa-404-next').on('click', function() {
        const projectId = getProjectId();
        const filter = $('#aysa-404-filter').val() || 'all';
        const search = $('#aysa-404-search').val() || '';
        const direction = $(this).attr('id') === 'aysa-404-prev' ? -1 : 1;
        
        // Determinăm pagina curentă reală și calculăm noua pagină
        const currentPage = aysa404CurrentPage || 1;
        const newPage = currentPage + direction;
        if (newPage < 1 || newPage > (aysa404TotalPages || 1)) {
            return;
        }
        
        load404Data(projectId, newPage, filter, search);
    });

    $(document).on('click', '#aysa-404-table thead th.aysa-sortable-header', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const nextSortBy = String($(this).data('sort') || '');
        if (!nextSortBy) {
            return;
        }
        if (aysa404SortBy === nextSortBy) {
            aysa404SortDir = (aysa404SortDir === 'asc') ? 'desc' : 'asc';
        } else {
            aysa404SortBy = nextSortBy;
            aysa404SortDir = (nextSortBy === 'last_hit' || nextSortBy === 'hits' || nextSortBy === 'confidence') ? 'desc' : 'asc';
        }
        const projectId = getProjectId();
        const filter = $('#aysa-404-filter').val() || 'all';
        const search = $('#aysa-404-search').val() || '';
        load404Data(projectId, 1, filter, search, aysa404SortBy, aysa404SortDir);
    });

    $(document).on('click', '#aysa-404-page-numbers .aysa-page-number-btn', function() {
        const page = Number($(this).data('page') || 1);
        if (!page || page < 1 || page > aysa404TotalPages) {
            return;
        }
        const projectId = getProjectId();
        const filter = $('#aysa-404-filter').val() || 'all';
        const search = $('#aysa-404-search').val() || '';
        load404Data(projectId, page, filter, search, aysa404SortBy, aysa404SortDir);
    });
    
    // Funcție pentru aplicarea corecțiilor în bulk
    function applyBulkFix(ids) {
        if (window.AYSA_DEBUG === true) {
            console.log('Applying bulk fix for IDs:', ids);
        }
        
        // Aici am adăuga codul pentru a aplica corecții automate în bulk
        // Pentru moment, doar le ascundem din interfață
        const $rows = ids.map(id => $('#aysa-404-table tbody input[value="' + id + '"]').closest('tr'));
        
        $rows.forEach($row => {
            $row.fadeOut(300, function() {
                $(this).remove();
                
                // Actualizăm statisticile
                const fixedCount = parseInt($('#aysa-fixed-404').text()) || 0;
                $('#aysa-fixed-404').text(fixedCount + 1);
            });
        });
        
        // Actualizăm numărul de înregistrări afișate
        const showing = parseInt($('#aysa-404-showing').text()) || 0;
        const newShowing = Math.max(0, showing - ids.length);
        $('#aysa-404-showing').text(newShowing);
        
        alert(`Successfully fixed ${ids.length} URLs.`);
    }
    
    // Handler pentru data de test
    $(document).on('click', '#aysa-seed-404', function() {
        const siteDomain = window.location.protocol + '//' + window.location.host;
        
        // Function to get a date in Romanian timezone
        function getRomanianDate(minutesAgo = 0) {
            // Current date in Romanian timezone
            const now = new Date();
            // Adjust for Romanian timezone (UTC+2 or UTC+3 depending on DST)
            const romanianTime = new Date(now.getTime() - minutesAgo * 60000);
            return romanianTime.toISOString();
        }
        
        // Generăm date de test
        const testData = [
            {
                id: 1001,
                url: siteDomain + '/old-product-page',
                hit_count: 15,
                dateLastDetected: getRomanianDate(5), // 5 minutes ago
                referer: siteDomain + '/catalog',
                userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            },
            {
                id: 1002,
                url: siteDomain + '/category/electronics/smartphones',
                hit_count: 8,
                dateLastDetected: getRomanianDate(15), // 15 minutes ago
                referer: 'https://www.google.com',
                userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)'
            },
            {
                id: 1003,
                url: siteDomain + '/blog-post-2022',
                hit_count: 3,
                dateLastDetected: getRomanianDate(30), // 30 minutes ago
                referer: 'https://facebook.com',
                userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'
            },
            {
                id: 1004,
                url: siteDomain + '/old-services-page',
                hit_count: 12,
                dateLastDetected: getRomanianDate(60), // 1 hour ago
                referer: null,
                userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            },
            {
                id: 1005,
                url: siteDomain + '/catalog/index.html',
                hit_count: 7,
                dateLastDetected: getRomanianDate(120), // 2 hours ago
                referer: siteDomain + '/home',
                userAgent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
                is_bot: 1
            },
            {
                id: 1006,
                url: siteDomain + '/old-product-page',
                hit_count: 4,
                dateLastDetected: getRomanianDate(10), // 10 minutes ago
                referer: 'https://www.bing.com',
                userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        ];
        
        // Afișăm datele de test
        renderErrorData(testData, $('#aysa-404-table tbody'));
        
        // Actualizăm statisticile
        updateErrorStats(testData);
        
        // Ascundem butonul de test
        $(this).closest('tr').remove();
    });
    // Function to load 410 Gone data
    function load410GoneData(forceReload = false, filter = 'all', search = '') {
        var $panel = $('#errors-410-panel');
        var $tbody = $panel.find('#aysa-gone-table tbody');
        
        if (forceReload) {
            $panel.data('loaded', false);
        }
        
        // Show loading state
        $tbody.html(`
            <tr class="aysa-loading-row">
                <td colspan="6" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Loading 410 Gone records...</span>
                    </div>
                </td>
            </tr>
        `);
        
        // Get project ID from localStorage
        var projectId = getProjectId();
        
        // Get site domain for full URLs
        var siteDomain = window.location.protocol + '//' + window.location.host;
    
        AysaAPI.getData('api/GoneUrl')
          .then(function(gones) {
            if (window.AYSA_DEBUG === true) {
                console.log('GONE items from API:', gones);
            }
            $tbody.empty();
            
            // Filter Gone URLs by project ID
            gones = gones.filter(function(g) {
                var gProjId = g.ProjectId || g.projectId || '';
                return gProjId == projectId; // Use loose equality to handle string/number conversion
            });
            
            // Apply search filter
            if (search.trim()) {
                gones = gones.filter(function(g) {
                    var goneUrl = (g.url || g.Url || '').toLowerCase();
                    var removalReason = (g.removalReason || g.RemovalReason || '').toLowerCase();
                    return goneUrl.includes(search.toLowerCase()) || removalReason.includes(search.toLowerCase());
                });
            }
            
            // Apply date filter
            if (filter === 'recent') {
                var sevenDaysAgo = new Date();
                sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
                gones = gones.filter(function(g) {
                    var dateMarkedRaw = g.markedAt || g.MarkedAt || '';
                    if (!dateMarkedRaw) return false;
                    var dateMarked = new Date(dateMarkedRaw);
                    return dateMarked >= sevenDaysAgo;
                });
            }
            
            if (!gones || gones.length === 0) {
              $tbody.append('<tr><td colspan="6" style="text-align:center;">No 410 Gone records found for the current project.</td></tr>');
              $panel.data('loaded', true);
              updateErrorsOverview({ active410: 0 });
              return;
            } else {
                gones.forEach(function(g) {
                    var projG = g.projectId || g.ProjectId || '';
                    // Safely get the marked date string (API may return 'markedAt' or 'MarkedAt')
                    var dateMarkedRaw = g.markedAt || g.MarkedAt || '';
                    var dateMarked = dateMarkedRaw ? dateMarkedRaw.split('T')[0] : '';
                    // Safely get URL and removal reason (handle casings)
                    var goneUrl = g.url || g.Url || '';
                    var removalReason = g.removalReason || g.RemovalReason || '';
                    
                    // Adaugă domeniul pentru URL-uri relative
                    if (goneUrl && !goneUrl.startsWith('http')) {
                        goneUrl = siteDomain + (goneUrl.startsWith('/') ? goneUrl : '/' + goneUrl);
                    }
                    
                    $tbody.append(
                      '<tr>' +
                        '<td><input type="checkbox" class="aysa-select-item" value="'+(g.id||g.Id)+'"></td>' +
                        '<td>'+ goneUrl +'</td>' +
                        '<td>'+ removalReason +'</td>' +
                        '<td>'+ dateMarked +'</td>' +
                        '<td>'+ projG +'</td>' +
                        '<td><span class="aysa-muted-note">Managed automatically</span></td>' +
                      '</tr>'
                    );
                });
            }
            $panel.data('loaded', true);
            updateErrorsOverview({ active410: gones.length });
          })
          .catch(function(err) {
            console.error('Failed to load gone urls:', err);
            $tbody.html(`
                <tr>
                    <td colspan="6" class="aysa-empty-message">
                        Error loading 410 Gone records. Please try again.
                        <button id="aysa-retry-gone" class="aysa-btn aysa-btn-outline" style="margin-top:10px;">
                            <span class="dashicons dashicons-update"></span> Retry
                        </button>
                    </td>
                </tr>
            `);
            
            // Add retry handler
            $('#aysa-retry-gone').on('click', function() {
                load410GoneData(true);
            });
          });
    }

    function aysaSchemaBadge(status) {
        const map = {
            active: '<span class="aysa-inline-badge aysa-badge-good">Active</span>',
            missing: '<span class="aysa-inline-badge aysa-badge-danger">Missing</span>',
            wrong_type: '<span class="aysa-inline-badge aysa-badge-warning">Wrong type</span>',
            incomplete: '<span class="aysa-inline-badge aysa-badge-warning">Incomplete</span>',
            conflict: '<span class="aysa-inline-badge aysa-badge-danger">Conflict</span>',
            blocked: '<span class="aysa-inline-badge aysa-badge-neutral">Blocked</span>',
            blocked_output: '<span class="aysa-inline-badge aysa-badge-neutral">Blocked output</span>',
            blocked_policy: '<span class="aysa-inline-badge aysa-badge-warning">Blocked by policy</span>',
            needs_takeover: '<span class="aysa-inline-badge aysa-badge-warning">Needs takeover</span>',
            needs_fields: '<span class="aysa-inline-badge aysa-badge-warning">Needs fields</span>',
            missing_target: '<span class="aysa-inline-badge aysa-badge-danger">Missing target</span>',
            not_applicable: '<span class="aysa-inline-badge aysa-badge-neutral">Not applicable</span>',
            ready: '<span class="aysa-inline-badge aysa-badge-good">Google-ready</span>',
            failed_post_validation: '<span class="aysa-inline-badge aysa-badge-danger">Failed post-validation</span>',
            skipped: '<span class="aysa-inline-badge aysa-badge-good">Skipped Google-ready</span>',
            generated: '<span class="aysa-inline-badge aysa-badge-good">Generated</span>',
            rewritten: '<span class="aysa-inline-badge aysa-badge-good">Rewritten</span>',
            autofilled_then_overwritten: '<span class="aysa-inline-badge aysa-badge-good">Autofilled + overwritten</span>',
            validated: '<span class="aysa-inline-badge aysa-badge-good">Validated</span>'
        };
        return map[status] || '<span class="aysa-inline-badge aysa-badge-neutral">' + String(status || 'unknown') + '</span>';
    }

    function aysaSchemaEscape(value) {
        return $('<div>').text(value == null ? '' : String(value)).html();
    }

    function aysaSchemaJoinList(list) {
        if (!Array.isArray(list) || !list.length) {
            return '<span class="aysa-muted-note">None</span>';
        }
        return list.map(function(item) {
            return '<span class="aysa-inline-badge aysa-badge-neutral">' + aysaSchemaEscape(item) + '</span>';
        }).join(' ');
    }

    function aysaSchemaGoogleTargetBadge(row) {
        const label = row && row.google_target_label ? String(row.google_target_label) : 'Not targeted';
        if (!row || !row.google_target_supported) {
            return '<span class="aysa-muted-note">' + aysaSchemaEscape(label) + '</span>';
        }
        return '<span class="aysa-inline-badge aysa-badge-good">' + aysaSchemaEscape(label) + '</span>';
    }

    function aysaSchemaGoogleReadiness(row) {
        if (!row || !row.google_target_supported) {
            return '<span class="aysa-muted-note">No primary Google target</span>';
        }
        if (row.google_rich_result_ready) {
            return '<span class="aysa-inline-badge aysa-badge-good">Ready for Google target</span>';
        }
        if (Array.isArray(row.google_required_missing) && row.google_required_missing.length) {
            return '<span class="aysa-inline-badge aysa-badge-warning">Missing: ' + aysaSchemaEscape(row.google_required_missing.join(', ')) + '</span>';
        }
        return '<span class="aysa-inline-badge aysa-badge-warning">Target missing in frontend</span>';
    }

    function aysaApplyGeneratedQueueFilters() {
        const targetFilter = String($('#aysa-schema-google-target-filter').val() || '');
        const statusFilter = String($('#aysa-schema-google-status-filter').val() || '');
        const actionFilter = String($('#aysa-schema-action-result-filter').val() || '');
        $('#aysa-schema-generated-table tbody tr').each(function() {
            const $row = $(this);
            const rowTarget = String($row.data('googleTarget') || '');
            const rowStatus = String($row.data('googleStatus') || '');
            const rowAction = String($row.data('lastAction') || '');
            const visible = (!targetFilter || rowTarget === targetFilter)
                && (!statusFilter || rowStatus === statusFilter)
                && (!actionFilter || rowAction === actionFilter);
            $row.toggle(visible);
        });
    }

    $(document).off('change.aysaSchemaQueueFilters', '#aysa-schema-google-target-filter, #aysa-schema-google-status-filter, #aysa-schema-action-result-filter')
        .on('change.aysaSchemaQueueFilters', '#aysa-schema-google-target-filter, #aysa-schema-google-status-filter, #aysa-schema-action-result-filter', function() {
            aysaApplyGeneratedQueueFilters();
        });

    function aysaRenderSchemaHub(snapshot) {
        snapshot = snapshot || {};
        const summary = snapshot.summary || {};
        const queuePreview = snapshot.queue_preview_summary || {};
        const coverageRows = Array.isArray(snapshot.coverage_rows) ? snapshot.coverage_rows : [];
        const validationRows = Array.isArray(snapshot.validation_rows) ? snapshot.validation_rows : [];
        const generatedRows = Array.isArray(snapshot.generated_rows) ? snapshot.generated_rows : [];
        const conflictRows = Array.isArray(snapshot.conflict_rows) ? snapshot.conflict_rows : [];
        const effectiveSummary = (summary.total_pages || 0) > 0 ? summary : {
            total_pages: coverageRows.length,
            active: coverageRows.filter(function(row) { return String(row.status || '') === 'active'; }).length,
            missing: coverageRows.filter(function(row) { return String(row.status || '') === 'missing'; }).length,
            wrong_type: coverageRows.filter(function(row) { return String(row.status || '') === 'wrong_type'; }).length,
            incomplete: coverageRows.filter(function(row) { return String(row.status || '') === 'incomplete'; }).length,
            conflict: coverageRows.filter(function(row) { return !!row.has_conflict || String(row.status || '') === 'conflict'; }).length,
            blocked_output: coverageRows.filter(function(row) { return String(row.status || '') === 'blocked_output'; }).length,
            google_target_pages: coverageRows.filter(function(row) { return !!row.google_target_supported; }).length,
            google_ready_pages: coverageRows.filter(function(row) { return !!row.google_rich_result_ready; }).length,
            safe_auto_generate: coverageRows.filter(function(row) { return !!row.can_auto_generate; }).length,
            needs_manual_review: coverageRows.filter(function(row) { return !!row.needs_manual_review; }).length
        };
        const overview = [
            ['Pages Evaluated', effectiveSummary.total_pages || 0],
            ['Active', effectiveSummary.active || 0],
            ['Missing', effectiveSummary.missing || 0],
            ['Wrong Type', effectiveSummary.wrong_type || 0],
            ['Incomplete', effectiveSummary.incomplete || 0],
            ['Conflicts', effectiveSummary.conflict || 0],
            ['Blocked Output', effectiveSummary.blocked_output || 0],
            ['Google Target Pages', effectiveSummary.google_target_pages || 0],
            ['Google Ready', effectiveSummary.google_ready_pages || 0],
            ['Safe Auto-Generate', effectiveSummary.safe_auto_generate || 0],
            ['Agent 8 Queue', effectiveSummary.needs_manual_review || 0]
        ];
        const $overview = $('#aysa-schema-hub-overview');
        $overview.empty();
        overview.forEach(function(card) {
            $overview.append(
                '<div class="postbox" style="padding:14px 16px;margin:0;">' +
                    '<div class="aysa-muted-note" style="margin-bottom:6px;">' + aysaSchemaEscape(card[0]) + '</div>' +
                    '<div style="font-size:28px;font-weight:700;line-height:1;">' + aysaSchemaEscape(card[1]) + '</div>' +
                '</div>'
            );
        });

        const $coverage = $('#aysa-schema-coverage-table tbody');
        $coverage.empty();
        if (!coverageRows.length) {
            $coverage.append('<tr><td colspan="11" class="aysa-empty-message">No schema coverage rows available yet.</td></tr>');
        } else {
            coverageRows.forEach(function(row) {
                $coverage.append(
                    '<tr>' +
                        '<td><a href="' + aysaSchemaEscape(row.url || '') + '" target="_blank">' + aysaSchemaEscape(row.url || '') + '</a></td>' +
                        '<td>' + aysaSchemaEscape(row.title || '') + '</td>' +
                        '<td>' + aysaSchemaEscape(row.page_family || '') + '</td>' +
                        '<td>' + aysaSchemaGoogleTargetBadge(row) + '</td>' +
                        '<td>' + aysaSchemaEscape(row.semantic_schema_label || '—') + '</td>' +
                        '<td>' + aysaSchemaEscape(row.website_wide_schema_label || '—') + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.recommended_nodes || []) + '</td>' +
                        '<td>' + aysaSchemaGoogleReadiness(row) + '</td>' +
                        '<td>' + aysaSchemaBadge(row.semantic_ready ? 'ready' : 'needs_update') + '</td>' +
                        '<td>' + aysaSchemaBadge(row.website_wide_ready ? 'ready' : ((row.website_wide_schema || []).length ? 'needs_update' : 'not_applicable')) + '</td>' +
                        '<td>' + aysaSchemaBadge(row.status || '') + '</td>' +
                    '</tr>'
                );
            });
        }

        const $validation = $('#aysa-schema-validation-table tbody');
        $validation.empty();
        if (!validationRows.length) {
            $validation.append('<tr><td colspan="12" class="aysa-empty-message">No validation rows available yet.</td></tr>');
        } else {
            validationRows.forEach(function(row) {
                $validation.append(
                    '<tr>' +
                        '<td><a href="' + aysaSchemaEscape(row.url || '') + '" target="_blank">' + aysaSchemaEscape(row.url || '') + '</a></td>' +
                        '<td>' + aysaSchemaEscape(row.page_family || '') + '</td>' +
                        '<td>' + aysaSchemaGoogleTargetBadge(row) + '</td>' +
                        '<td>' + aysaSchemaEscape(row.semantic_schema_label || '—') + '</td>' +
                        '<td>' + aysaSchemaEscape(row.website_wide_schema_label || '—') + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.detected_nodes || []) + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.google_required_missing || []) + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.semantic_required_missing || []) + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.website_required_missing || row.website_wide_required_missing || []) + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.source_summary || []) + '</td>' +
                        '<td>' + aysaSchemaBadge(row.status || '') + '</td>' +
                        '<td>' + aysaSchemaEscape((row.notes || []).join(' | ')) + '</td>' +
                        '<td>' + aysaSchemaEscape(row.last_checked_at || '') + '</td>' +
                    '</tr>'
                );
            });
        }

        const $conflicts = $('#aysa-schema-conflicts-table tbody');
        $conflicts.empty();
        if (!conflictRows.length) {
            $conflicts.append('<tr><td colspan="6" class="aysa-empty-message">No schema conflicts detected.</td></tr>');
        } else {
            conflictRows.forEach(function(row) {
                let actionText = 'Review frontend output';
                if (row.conflict_reason === 'parallel_schema_sources') {
                    actionText = 'Prioritize AYSA, remove duplicate external schema, then revalidate frontend output';
                } else if (row.status === 'blocked_output') {
                    actionText = 'Re-enable schema output or remove the URL block before rewrite.';
                } else if (row.status === 'wrong_type') {
                    actionText = 'Generate the correct primary schema for this family';
                } else if (row.status === 'incomplete') {
                    actionText = 'Complete the required fields before revalidation';
                }
                $conflicts.append(
                    '<tr>' +
                        '<td><a href="' + aysaSchemaEscape(row.url || '') + '" target="_blank">' + aysaSchemaEscape(row.url || '') + '</a></td>' +
                        '<td>' + aysaSchemaEscape(row.page_family || '') + '</td>' +
                        '<td>' + aysaSchemaEscape(row.conflict_reason || (row.status || '')) + '</td>' +
                        '<td>' + aysaSchemaJoinList(row.source_summary || []) + '</td>' +
                        '<td>' + aysaSchemaBadge(row.status || '') + '</td>' +
                        '<td>' + aysaSchemaEscape(actionText) + '</td>' +
                    '</tr>'
                );
            });
        }

        const visibleEntityGroups = ['page', 'product', 'ecommerce_category', 'article', 'business'];
        const visibleRows = (coverageRows || []).filter(function(row) {
            return visibleEntityGroups.includes(String(row.entity_group || ''));
        });

        const generatedActive = visibleRows.filter(function(row) { return !!row.is_aysa_present; }).length;
        const generatedSafe = visibleRows.filter(function(row) { return String(row.execution_eligibility || '') === 'generate_safe'; }).length;
        const generatedReview = visibleRows.filter(function(row) {
            return ['needs_fields', 'conflict', 'blocked_output', 'missing_target'].includes(String(row.google_status || ''))
                || String(row.execution_eligibility || '') === 'manual_review';
        }).length;
        $('#aysa-schema-generated-active-count').text(generatedActive);
        $('#aysa-schema-generated-safe-count').text(generatedSafe);
        $('#aysa-schema-generated-review-count').text(generatedReview);
        $('#aysa-schema-generated-google-ready-count').text(visibleRows.filter(function(row) { return !!row.google_rich_result_ready; }).length);
        $('#aysa-schema-generated-total-count').text(visibleRows.length);

        const $hubStatus = $('#aysa-schema-hub-status');
        const summaryTotal = parseInt(effectiveSummary.total_pages || 0, 10) || 0;
        if ($hubStatus.length && summaryTotal > 0 && summaryTotal !== visibleRows.length) {
            $hubStatus
                .text('Schema runtime warning: overview total (' + summaryTotal + ') does not match the 5 visible entity sections (' + visibleRows.length + '). The cached snapshot was built from mixed groups and should self-heal on reload.')
                .css('color', '#996800')
                .show();
        }

        aysaRenderSchemaEntitySections(snapshot, visibleRows);
    }

    function aysaSchemaEntityConfig() {
        return {
            page: {
                label: 'Normal Pages',
                description: 'Google target: Breadcrumb. Semantic schema: WebPage + BreadcrumbList.',
                generateMode: 'entity_page_generate',
                rewriteMode: 'entity_page_rewrite',
                validateMode: 'entity_page_validate',
                testMode: 'entity_page_test_selected'
            },
            product: {
                label: 'Products',
                description: 'Google target: Product. Semantic schema: Product + BreadcrumbList.',
                generateMode: 'entity_product_generate',
                rewriteMode: 'entity_product_rewrite',
                validateMode: 'entity_product_validate',
                testMode: 'entity_product_test_selected'
            },
            ecommerce_category: {
                label: 'Ecommerce Categories',
                description: 'Google target: Breadcrumb. Semantic schema: CollectionPage + ItemList + BreadcrumbList.',
                generateMode: 'entity_ecommerce_category_generate',
                rewriteMode: 'entity_ecommerce_category_rewrite',
                validateMode: 'entity_ecommerce_category_validate',
                testMode: 'entity_ecommerce_category_test_selected'
            },
            article: {
                label: 'Articles',
                description: 'Google target: Article. Semantic schema: Article + BreadcrumbList.',
                generateMode: 'entity_article_generate',
                rewriteMode: 'entity_article_rewrite',
                validateMode: 'entity_article_validate',
                testMode: 'entity_article_test_selected'
            },
            business: {
                label: 'Business Schema',
                description: 'Website-wide schema: WebSite + Organization (+ LocalBusiness on homepage/contact/location when valid).',
                generateMode: 'entity_business_generate',
                rewriteMode: 'entity_business_rewrite',
                validateMode: 'entity_business_validate',
                testMode: 'entity_business_test_selected'
            }
        };
    }

    function aysaSchemaNextStep(row) {
        let nextStep = 'Route to Agent 8';
        if (row.google_status === 'ready') {
            nextStep = row.semantic_ready
                ? ((row.website_wide_schema || []).length && !row.website_wide_ready ? 'Google-ready; website-wide schema still needs completion' : 'Already ready')
                : 'Google-ready; semantic schema still needs AYSA ownership';
        } else if (row.google_status === 'needs_takeover') {
            nextStep = 'External schema found. Rewrite will let AYSA replace it.';
        } else if (row.google_status === 'needs_fields') {
            nextStep = 'Fill the required content fields before rewrite';
        } else if (row.entity_group === 'ecommerce_category' && !row.semantic_ready) {
            nextStep = 'Google target is Breadcrumb; semantic ecommerce layer still needs CollectionPage + ItemList.';
        } else if (row.execution_eligibility === 'rewrite_existing_aysa') {
            nextStep = 'Rewrite existing AYSA schema';
        } else if (row.execution_eligibility === 'generate_safe' || row.can_auto_generate) {
            nextStep = 'Safe to generate with AYSA';
        } else if (row.google_status === 'not_applicable' && row.semantic_schema_label) {
            nextStep = 'Semantic schema only. Validate in Schema Markup Validator, not only Google.';
        } else if (row.status === 'blocked_output') {
            nextStep = 'Blocked output: re-enable or rewrite existing AYSA schema';
        } else if (row.execution_reason) {
            nextStep = row.execution_reason;
        }
        return nextStep;
    }

    function aysaRenderSchemaEntitySections(snapshot, visibleRows) {
        const config = aysaSchemaEntityConfig();
        const entitySummaries = snapshot && snapshot.entity_summaries ? snapshot.entity_summaries : {};
        const entityRows = snapshot && snapshot.entity_rows ? snapshot.entity_rows : {};
        const selectedUrls = window.aysaSchemaSelectedUrls = window.aysaSchemaSelectedUrls || {};
        const container = $('#aysa-schema-entity-sections');
        const needsRefresh = !!(snapshot && snapshot.needs_refresh);
        if (!container.length) {
            return;
        }

        const sectionsHtml = Object.keys(config).map(function(entityGroup) {
            const section = config[entityGroup];
            const summary = entitySummaries[entityGroup] || {};
            const rows = Array.isArray(entityRows[entityGroup])
                ? entityRows[entityGroup]
                : (Array.isArray(visibleRows) ? visibleRows.filter(function(row) { return String(row.entity_group || '') === entityGroup; }) : []);
            const stats = [
                ['Total', summary.total_pages || rows.length || 0],
                ['AYSA active', summary.active_generated || rows.filter(function(row) { return !!row.is_aysa_present; }).length || 0],
                ['Google ready', summary.google_ready_pages || rows.filter(function(row) { return !!row.google_rich_result_ready; }).length || 0],
                ['Semantic ready', summary.semantic_ready_pages || rows.filter(function(row) { return !!row.semantic_ready; }).length || 0],
                ['Website ready', summary.website_wide_ready_pages || rows.filter(function(row) { return (row.website_wide_schema || []).length && !!row.website_wide_ready; }).length || 0]
            ];
            const rowsHtml = rows.length ? rows.map(function(row) {
                return '<tr>' +
                    '<td><input type="checkbox" class="aysa-schema-row" data-entity-group="' + aysaSchemaEscape(entityGroup) + '" data-url="' + aysaSchemaEscape(row.url || '') + '" data-type="' + aysaSchemaEscape(row.primary_recommended_node || (row.recommended_nodes || [])[0] || '') + '"' + (selectedUrls[row.url] ? ' checked' : '') + '></td>' +
                    '<td><a href="' + aysaSchemaEscape(row.url || '') + '" target="_blank">' + aysaSchemaEscape(row.url || '') + '</a></td>' +
                    '<td>' + aysaSchemaEscape(row.title || '') + '</td>' +
                    '<td>' + aysaSchemaEscape(row.page_family || '') + '</td>' +
                    '<td>' + aysaSchemaGoogleTargetBadge(row) + '</td>' +
                    '<td>' + aysaSchemaEscape(row.semantic_schema_label || '—') + '</td>' +
                    '<td>' + aysaSchemaEscape((row.website_wide_schema || []).length ? (row.website_wide_schema_label || '—') : 'No website-wide schema target') + '</td>' +
                    '<td>' + aysaSchemaJoinList(row.generated_types || row.recommended_nodes || []) + '</td>' +
                    '<td>' + aysaSchemaBadge(row.google_status || row.status || '') + '</td>' +
                    '<td>' + aysaSchemaEscape(aysaSchemaNextStep(row)) + '</td>' +
                '</tr>';
            }).join('') : '<tr><td colspan="10" class="aysa-empty-message">' + aysaSchemaEscape(needsRefresh ? 'Schema snapshot cache is empty. Click Refresh Validation to load rows for this entity.' : 'No rows for this entity yet.') + '</td></tr>';
            const actionDisabled = needsRefresh ? ' disabled' : '';

            return '' +
                '<div class="postbox" style="margin:0 0 16px 0;" data-entity-group-section="' + aysaSchemaEscape(entityGroup) + '">' +
                    '<div class="inside">' +
                        '<div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap;">' +
                            '<div>' +
                                '<h3 style="margin-top:0;">' + aysaSchemaEscape(section.label) + '</h3>' +
                                '<p class="description" style="margin-top:4px;">' + aysaSchemaEscape(section.description) + '</p>' +
                            '</div>' +
                        '</div>' +
                        '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:14px 0;">' +
                            stats.map(function(card) {
                                return '<div><div class="description">' + aysaSchemaEscape(card[0]) + '</div><div style="font-size:24px;font-weight:700;">' + aysaSchemaEscape(card[1]) + '</div></div>';
                            }).join('') +
                        '</div>' +
                        '<p>' +
                            '<button class="button aysa-schema-entity-action" data-entity-group="' + aysaSchemaEscape(entityGroup) + '" data-mode="' + aysaSchemaEscape(section.testMode) + '" data-scope="selection" data-progress-prefix="Testing" data-pending-label="Queueing test..." data-status-label="Entity test queued..."' + actionDisabled + '>Test selected</button> ' +
                            '<button class="button button-primary aysa-schema-entity-action" data-entity-group="' + aysaSchemaEscape(entityGroup) + '" data-mode="' + aysaSchemaEscape(section.generateMode) + '" data-scope="selection" data-progress-prefix="Generating" data-pending-label="Queueing generation..." data-status-label="Entity generation queued..."' + actionDisabled + '>Generate safe</button> ' +
                            '<button class="button aysa-schema-entity-action" data-entity-group="' + aysaSchemaEscape(entityGroup) + '" data-mode="' + aysaSchemaEscape(section.rewriteMode) + '" data-scope="selection" data-progress-prefix="Rewriting" data-pending-label="Queueing rewrite..." data-status-label="Entity rewrite queued..."' + actionDisabled + '>Rewrite selected</button> ' +
                            '<button class="button aysa-schema-entity-action" data-entity-group="' + aysaSchemaEscape(entityGroup) + '" data-mode="' + aysaSchemaEscape(section.validateMode) + '" data-scope="selection" data-progress-prefix="Validating" data-pending-label="Queueing validation..." data-status-label="Entity validation queued..."' + actionDisabled + '>Validate selected</button>' +
                        '</p>' +
                        (needsRefresh ? '<p class="description" style="margin-top:-4px;color:#996800;">This entity section is waiting for the sitewide schema snapshot. Use <strong>Refresh Validation</strong> first.</p>' : '') +
                        '<div id="aysa-schema-job-status-' + aysaSchemaEscape(entityGroup) + '" class="aysa-muted-note" style="display:none;margin-top:10px;"></div>' +
                        '<div id="aysa-schema-job-progress-' + aysaSchemaEscape(entityGroup) + '" style="display:none;margin-top:12px;padding:14px;border:1px solid #dcdcde;border-radius:8px;background:#fff;">' +
                            '<div style="display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;">' +
                                '<div><strong id="aysa-schema-job-progress-label-' + aysaSchemaEscape(entityGroup) + '">Schema worker idle</strong><div id="aysa-schema-job-progress-meta-' + aysaSchemaEscape(entityGroup) + '" class="description" style="margin-top:4px;">Start a schema job to see live progress.</div></div>' +
                                '<div id="aysa-schema-job-progress-pill-' + aysaSchemaEscape(entityGroup) + '" style="display:none;padding:4px 10px;border-radius:999px;background:#f0f0f1;font-size:12px;font-weight:600;color:#1d2327;">Idle</div>' +
                            '</div>' +
                            '<div style="margin-top:12px;height:10px;background:#f0f0f1;border-radius:999px;overflow:hidden;"><div id="aysa-schema-job-progress-bar-' + aysaSchemaEscape(entityGroup) + '" style="width:0%;height:100%;background:linear-gradient(90deg,#2271b1 0%,#135e96 100%);transition:width .25s ease;"></div></div>' +
                            '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-top:12px;">' +
                                '<div><div class="description">Processed</div><div id="aysa-schema-job-count-processed-' + aysaSchemaEscape(entityGroup) + '" style="font-size:24px;font-weight:700;">0</div></div>' +
                                '<div><div class="description">Generated</div><div id="aysa-schema-job-count-generated-' + aysaSchemaEscape(entityGroup) + '" style="font-size:24px;font-weight:700;">0</div></div>' +
                                '<div><div class="description">Rewritten</div><div id="aysa-schema-job-count-rewritten-' + aysaSchemaEscape(entityGroup) + '" style="font-size:24px;font-weight:700;">0</div></div>' +
                                '<div><div class="description">Needs fields</div><div id="aysa-schema-job-count-needs-fields-' + aysaSchemaEscape(entityGroup) + '" style="font-size:24px;font-weight:700;">0</div></div>' +
                                '<div><div class="description">Failed</div><div id="aysa-schema-job-count-failed-' + aysaSchemaEscape(entityGroup) + '" style="font-size:24px;font-weight:700;">0</div></div>' +
                            '</div>' +
                            '<div style="margin-top:14px;"><strong style="display:block;margin-bottom:8px;">Latest processed URLs</strong><div class="aysa-table-responsive"><table class="widefat striped"><thead><tr><th>URL</th><th>Page family</th><th>Google target</th><th>Semantic schema</th><th>Website-wide schema</th><th>Before</th><th>Autofill</th><th>Planned</th><th>Result</th><th>After</th><th>Message</th></tr></thead><tbody id="aysa-schema-job-results-body-' + aysaSchemaEscape(entityGroup) + '"><tr><td colspan="11" class="description">No schema job activity yet.</td></tr></tbody></table></div></div>' +
                        '</div>' +
                        '<div class="aysa-table-responsive" style="margin-top:12px;">' +
                            '<table class="widefat striped aysa-schema-entity-table" id="aysa-schema-entity-table-' + aysaSchemaEscape(entityGroup) + '">' +
                                '<thead><tr><th style="width:34px;"><input type="checkbox" class="aysa-schema-entity-select-all" data-entity-group="' + aysaSchemaEscape(entityGroup) + '"></th><th>URL</th><th>Title</th><th>Page family</th><th>Google target</th><th>Semantic schema</th><th>Website-wide schema</th><th>AYSA nodes</th><th>Status</th><th>Next step</th></tr></thead>' +
                                '<tbody>' + rowsHtml + '</tbody>' +
                            '</table>' +
                        '</div>' +
                    '</div>' +
                '</div>';
        }).join('');

        const emptyState = needsRefresh
            ? '<div class="notice notice-warning inline" style="margin:0 0 16px 0;"><p>Schema runtime is split by entity now, but the sitewide snapshot cache is empty. Click <strong>Refresh Validation</strong> above to populate the 5 entity sections.</p></div>'
            : '';

        container.html(emptyState + sectionsHtml);
    }

    window.aysaSchemaV2State = window.aysaSchemaV2State || {
        snapshot: null,
        filter: 'inventory'
    };

    function aysaSchemaEscapeHtml(value) {
        return $('<div>').text(String(value == null ? '' : value)).html();
    }

    function aysaSchemaFilterRows(snapshot, filter) {
        const rows = Array.isArray(snapshot && snapshot.rows) ? snapshot.rows : [];
        return rows.filter(function(row) {
            switch (filter) {
                case 'google_eligible':
                    return !!parseInt(row.google_supported || 0, 10);
                case 'needs_action':
                    return !!parseInt(row.google_supported || 0, 10) && (
                        !!parseInt(row.needs_takeover || 0, 10)
                        || ['needs_action', 'needs_fields', 'validation_failed'].includes(String(row.google_readiness_status || ''))
                        || ['needs_takeover', 'needs_fields', 'pending_validation'].includes(String(row.generation_status || ''))
                    );
                case 'generated':
                    return !!parseInt(row.generated_by_aysa || 0, 10);
                case 'conflicts':
                    return !!parseInt(row.has_conflict || 0, 10);
                default:
                    return true;
            }
        });
    }

    function aysaSchemaNextStep(row) {
        if (!parseInt(row.google_supported || 0, 10)) {
            return String(row.not_applicable_reason || 'Inventory only in V1.');
        }
        if (parseInt(row.needs_takeover || 0, 10)) {
            return 'Rewrite to let AYSA become source of truth.';
        }
        if (String(row.google_readiness_status || '') === 'needs_fields') {
            const fields = Array.isArray(row.needs_fields) ? row.needs_fields : [];
            return fields.length ? ('Complete fields: ' + fields.join(', ')) : 'Complete required Google fields.';
        }
        if (!!parseInt(row.generated_by_aysa || 0, 10)) {
            return 'Validate frontend output and monitor Search Console.';
        }
        if (String(row.generation_status || '') === 'eligible') {
            return 'Generate AYSA schema.';
        }
        if (String(row.google_readiness_status || '') === 'ready') {
            return 'Already Google-ready.';
        }
        if (!!parseInt(row.has_conflict || 0, 10)) {
            return 'Resolve conflicting schema sources.';
        }
        return 'Validate this entity.';
    }

    function aysaRenderSchemaInventoryTable(snapshot, filter) {
        const rows = aysaSchemaFilterRows(snapshot, filter);
        const $tbody = $('#aysa-schema-v2-table tbody');
        const descriptions = {
            inventory: 'All discovered schema-relevant entities for this website.',
            google_eligible: 'Only entities with a supported Google Search policy in V1.',
            needs_action: 'Entities blocked by missing fields, takeover, or failed validation.',
            generated: 'Only entities currently generated by AYSA.',
            conflicts: 'Entities with conflicting schema sources or invalid ownership state.'
        };
        $('#aysa-schema-filter-description').text(descriptions[filter] || descriptions.inventory);
        if (!$tbody.length) {
            return;
        }
        if (!rows.length) {
            $tbody.html('<tr><td colspan="10" class="description">No rows for this view.</td></tr>');
            return;
        }
        $tbody.html(rows.map(function(row) {
            const payload = row.payload_snapshot || {};
            const legacy = payload.legacy_row || {};
            const url = String(row.url_normalized || '');
            const safeUrl = aysaSchemaEscapeHtml(url);
            const title = aysaSchemaEscapeHtml(row.title || url);
            const entityGroup = aysaSchemaEscapeHtml((snapshot.summary && snapshot.summary.entity_groups && snapshot.summary.entity_groups[row.entity_group] && snapshot.summary.entity_groups[row.entity_group].label) || String(row.entity_group || ''));
            const pageFamily = aysaSchemaEscapeHtml(String(row.page_family || ''));
            const policy = aysaSchemaEscapeHtml(String(row.google_policy_type || ''));
            const generation = aysaSchemaEscapeHtml(String(row.generation_status || 'inventory_only').replace(/_/g, ' '));
            const readiness = aysaSchemaEscapeHtml(String(row.google_readiness_status || 'not_applicable').replace(/_/g, ' '));
            const nextStep = aysaSchemaEscapeHtml(aysaSchemaNextStep(row));
            const checkedAt = aysaSchemaEscapeHtml(String(row.last_validated_at || ''));
            const schemaType = aysaSchemaEscapeHtml(String((legacy.primary_recommended_node || legacy.google_target || 'webpage')).toLowerCase());
            return '<tr>' +
                '<td><input type="checkbox" class="aysa-schema-row-select" data-url="' + safeUrl + '" data-type="' + schemaType + '" data-entity-group="' + aysaSchemaEscapeHtml(String(row.entity_group || 'page')) + '"></td>' +
                '<td><a href="' + safeUrl + '" target="_blank" rel="noopener noreferrer">' + safeUrl + '</a></td>' +
                '<td>' + title + '</td>' +
                '<td>' + entityGroup + '</td>' +
                '<td>' + pageFamily + '</td>' +
                '<td>' + policy + '</td>' +
                '<td>' + generation + '</td>' +
                '<td>' + readiness + '</td>' +
                '<td>' + nextStep + '</td>' +
                '<td>' + checkedAt + '</td>' +
            '</tr>';
        }).join(''));
    }

    function aysaRenderSchemaGeneratedSections(snapshot) {
        const groupRows = snapshot && snapshot.group_rows ? snapshot.group_rows : {};
        const groups = ['page', 'product', 'ecommerce_category', 'article', 'business'];
        const html = groups.map(function(group) {
            const rows = Array.isArray(groupRows[group]) ? groupRows[group].filter(function(row) {
                return !!parseInt(row.generated_by_aysa || 0, 10);
            }) : [];
            const summary = snapshot.summary && snapshot.summary.entity_groups ? (snapshot.summary.entity_groups[group] || {}) : {};
            const label = aysaSchemaEscapeHtml(String(summary.label || group));
            return '<div class="postbox" style="margin-bottom:16px;">' +
                '<div class="inside">' +
                    '<h3 style="margin-top:0;">' + label + '</h3>' +
                    '<p class="description">Total: ' + parseInt(summary.total || 0, 10) + ' · Generated: ' + parseInt(summary.generated || 0, 10) + ' · Google ready: ' + parseInt(summary.google_ready || 0, 10) + ' · Needs action: ' + parseInt(summary.needs_action || 0, 10) + '</p>' +
                    '<div class="aysa-table-responsive">' +
                        '<table class="widefat striped"><thead><tr><th>URL</th><th>Title</th><th>Generation State</th><th>Google Readiness</th><th>Next Step</th></tr></thead><tbody>' +
                        (rows.length ? rows.map(function(row) {
                            const url = aysaSchemaEscapeHtml(String(row.url_normalized || ''));
                            return '<tr>' +
                                '<td><a href="' + url + '" target="_blank" rel="noopener noreferrer">' + url + '</a></td>' +
                                '<td>' + aysaSchemaEscapeHtml(String(row.title || url)) + '</td>' +
                                '<td>' + aysaSchemaEscapeHtml(String(row.generation_status || '').replace(/_/g, ' ')) + '</td>' +
                                '<td>' + aysaSchemaEscapeHtml(String(row.google_readiness_status || '').replace(/_/g, ' ')) + '</td>' +
                                '<td>' + aysaSchemaEscapeHtml(aysaSchemaNextStep(row)) + '</td>' +
                            '</tr>';
                        }).join('') : '<tr><td colspan="5" class="description">No AYSA-generated rows in this chapter.</td></tr>') +
                        '</tbody></table>' +
                    '</div>' +
                '</div>' +
            '</div>';
        }).join('');
        $('#aysa-schema-entity-sections').html(html);
    }

    function aysaRenderSchemaHubV2(snapshot) {
        window.aysaSchemaV2State.snapshot = snapshot || {};
        const summary = snapshot && snapshot.summary ? snapshot.summary : {};
        const cards = [
            ['Inventory', summary.inventory_total || 0],
            ['Google Eligible', summary.google_eligible_total || 0],
            ['Needs Action', summary.needs_action_total || 0],
            ['Generated by AYSA', summary.generated_total || 0],
            ['Conflicts', summary.conflicts_total || 0],
            ['Google Ready', summary.google_ready_total || 0],
            ['Inventory Only', summary.inventory_only_total || 0]
        ];
        $('#aysa-schema-hub-overview').html(cards.map(function(card) {
            return '<div style="background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:16px 18px;">' +
                '<div class="description">' + aysaSchemaEscapeHtml(card[0]) + '</div>' +
                '<div style="font-size:22px;font-weight:700;margin-top:4px;">' + parseInt(card[1] || 0, 10) + '</div>' +
            '</div>';
        }).join(''));
        $('#aysa-schema-generated-active-count').text(parseInt(summary.generated_total || 0, 10));
        $('#aysa-schema-generated-google-ready-count').text(parseInt(summary.google_ready_total || 0, 10));
        $('#aysa-schema-generated-eligible-count').text(parseInt(summary.google_eligible_total || 0, 10));
        $('#aysa-schema-generated-review-count').text(parseInt(summary.needs_action_total || 0, 10));
        $('#aysa-schema-generated-total-count').text(parseInt(summary.inventory_total || 0, 10));
        aysaRenderSchemaInventoryTable(snapshot, window.aysaSchemaV2State.filter || 'inventory');
        aysaRenderSchemaGeneratedSections(snapshot);
    }

    function aysaLoadSchemaHub(refresh) {
        const $hub = $('#aysa-schema-hub');
        const $status = $('#aysa-schema-hub-status');
        if (!$hub.length) {
            return;
        }
        const projectId = parseInt($hub.attr('data-project-id') || $hub.data('project-id') || 0, 10)
            || (typeof getProjectId === 'function' ? getProjectId() : 0);
        if (!projectId) {
            $status.text('Schema Hub could not resolve a project context for this website.').css('color', '#b32d2e').show();
            return;
        }
        const $button = $('#aysa-schema-refresh-hub');
        $button.prop('disabled', true).text(refresh ? 'Loading...' : 'Loading...');
        if (!refresh) {
            $status.text('Loading schema inventory...').css('color', '#646970').show();
        }
        $.ajax({
            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_technical_schema_snapshot',
                nonce: '<?php echo esc_attr(wp_create_nonce('aysa_technical_audit_nonce')); ?>',
                project_id: projectId
            }
        }).done(function(response) {
            if (!(response && response.success && response.data && response.data.snapshot)) {
                throw new Error('Schema inventory could not be loaded.');
            }
            const snapshot = response.data.snapshot || {};
            if (snapshot && snapshot.resolved_project_id) {
                const resolvedProjectId = parseInt(snapshot.resolved_project_id, 10) || 0;
                if (resolvedProjectId > 0) {
                    $hub.attr('data-project-id', resolvedProjectId).data('project-id', resolvedProjectId);
                }
            }
            window.aysaSchemaHubLoaded = true;
            aysaRenderSchemaHubV2(snapshot);
            if (snapshot.status === 'reconciling') {
                $status.text('Schema inventory reconcile is running in the background. Last valid state remains visible below.').css('color', '#646970').show();
            } else if (snapshot.needs_reconcile) {
                $status.text('Schema inventory is empty. Run Reconcile Inventory to populate the DB-backed state.').css('color', '#996800').show();
            } else {
                $status.hide().text('');
            }
        }).fail(function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data : 'Schema inventory could not be loaded.';
            $status.text(message).css('color', '#b32d2e').show();
        }).always(function() {
            $button.prop('disabled', false).text('Reconcile Inventory');
        });
    }

    function aysaUpdateSchemaRefreshUi(job) {
        const $panel = $('#aysa-schema-refresh-progress');
        const $pill = $('#aysa-schema-refresh-progress-pill');
        const total = Math.max(0, parseInt(job && job.total ? job.total : 0, 10) || 0);
        const processed = Math.max(0, parseInt(job && job.processed ? job.processed : 0, 10) || 0);
        const cached = Math.max(0, parseInt(job && job.cached ? job.cached : 0, 10) || 0);
        const refetched = Math.max(0, parseInt(job && job.refetched ? job.refetched : 0, 10) || 0);
        const failed = Math.max(0, parseInt(job && job.failed ? job.failed : 0, 10) || 0);
        const status = String(job && job.status ? job.status : 'idle');
        const percent = total > 0 ? Math.max(0, Math.min(100, Math.round((processed / total) * 100))) : 0;
        const labelMap = { queued: 'Queued', running: 'Running', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' };
        const pillTone = status === 'completed'
            ? { bg: '#edfaef', color: '#0a7d33' }
            : (status === 'failed'
                ? { bg: '#fbeaea', color: '#b32d2e' }
                : (status === 'cancelled'
                    ? { bg: '#fff3cd', color: '#996800' }
                    : { bg: '#eaf3ff', color: '#135e96' }));

        if ($panel.length) {
            $panel.show();
        }
        $('#aysa-schema-refresh-progress-label').text(
            status === 'completed'
                ? 'Schema inventory reconcile completed'
                : (status === 'failed'
                    ? 'Schema inventory reconcile failed'
                    : (status === 'cancelled' ? 'Schema inventory reconcile cancelled' : 'Schema inventory reconcile running'))
        );
        $('#aysa-schema-refresh-progress-meta').text(
            total > 0
                ? `Job ${job.job_id || ''} · ${processed}/${total} processed · ${percent}% complete`
                : `Job ${job && job.job_id ? job.job_id : ''}`
        );
        $('#aysa-schema-refresh-progress-bar').css('width', `${percent}%`);
        if ($pill.length) {
            $pill.text(labelMap[status] || status).css({
                display: 'inline-block',
                background: pillTone.bg,
                color: pillTone.color
            });
        }
        $('#aysa-schema-refresh-count-processed').text(`${processed}/${total || 0}`);
        $('#aysa-schema-refresh-count-cached').text(cached);
        $('#aysa-schema-refresh-count-refetched').text(refetched);
        $('#aysa-schema-refresh-count-failed').text(failed);
    }

    async function aysaStartSchemaRefreshJob() {
        const $hub = $('#aysa-schema-hub');
        const $status = $('#aysa-schema-hub-status');
        const $button = $('#aysa-schema-refresh-hub');
        const projectId = parseInt($hub.attr('data-project-id') || $hub.data('project-id') || 0, 10)
            || (typeof getProjectId === 'function' ? getProjectId() : 0);
        if (!projectId) {
            $status.text('Schema Hub could not resolve a project context for this website.').css('color', '#b32d2e').show();
            return false;
        }

        $button.prop('disabled', true).text('Queueing reconcile...');
        $status.text('Queueing schema inventory reconcile...').css('color', '#646970').show();
        aysaUpdateSchemaRefreshUi({ job_id: '', status: 'queued', total: 0, processed: 0, cached: 0, refetched: 0, failed: 0 });

        try {
            const startResponse = await $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'aysa_technical_schema_refresh_start',
                    nonce: '<?php echo esc_attr(wp_create_nonce('aysa_technical_audit_nonce')); ?>',
                    project_id: projectId
                }
            });
            if (!startResponse || !startResponse.success || !startResponse.data || !startResponse.data.job) {
                throw new Error((startResponse && startResponse.data) ? startResponse.data : 'Schema refresh could not be started.');
            }

            let job = startResponse.data.job;
            aysaUpdateSchemaRefreshUi(job);
            while (job && (job.status === 'queued' || job.status === 'running')) {
                $button.text(`Reconciling... (${job.processed || 0}/${job.total || 0})`);
                $status.text(`Reconciling inventory ${job.processed || 0}/${job.total || 0}. Cached: ${job.cached || 0}, Refetched: ${job.refetched || 0}, Failed: ${job.failed || 0}.`).css('color', '#646970').show();
                await new Promise(resolve => setTimeout(resolve, 1200));
                const statusResponse = await $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    method: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'aysa_technical_schema_refresh_status',
                        nonce: '<?php echo esc_attr(wp_create_nonce('aysa_technical_audit_nonce')); ?>',
                        project_id: projectId,
                        job_id: job.job_id
                    }
                });
                if (!statusResponse || !statusResponse.success || !statusResponse.data || !statusResponse.data.job) {
                    throw new Error((statusResponse && statusResponse.data) ? statusResponse.data : 'Schema refresh status failed.');
                }
                job = statusResponse.data.job;
                aysaUpdateSchemaRefreshUi(job);
            }

            $button.prop('disabled', false).text('Reconcile Inventory');
            if (job && job.status === 'completed') {
                $status.text('Schema inventory reconcile completed. Loading the updated DB state...').css('color', '#0a7d33').show();
                window.aysaSchemaHubLoaded = false;
                aysaLoadSchemaHub(false);
            } else if (job && job.status === 'failed') {
                $status.text(job.last_error || 'Schema inventory reconcile failed.').css('color', '#b32d2e').show();
            } else if (job && job.status === 'cancelled') {
                $status.text('Schema inventory reconcile cancelled.').css('color', '#996800').show();
            }
            return false;
        } catch (error) {
            $button.prop('disabled', false).text('Reconcile Inventory');
            $status.text(error && error.message ? error.message : 'Schema inventory reconcile failed.').css('color', '#b32d2e').show();
            aysaUpdateSchemaRefreshUi({ job_id: '', status: 'failed', total: 0, processed: 0, cached: 0, refetched: 0, failed: 1 });
            return false;
        }
    }

    $(document).on('click', '#aysa-schema-refresh-hub', function(e) {
        e.preventDefault();
        aysaStartSchemaRefreshJob();
    });

    $(document).on('click', '#aysa-schema-hub-tabs .nav-tab', function(e) {
        e.preventDefault();
        const target = $(this).data('schema-hub-target');
        $('#aysa-schema-hub-tabs .nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        $('#schema-content [data-schema-hub-panel]').hide().removeClass('active');
        const panelTarget = target === 'generated' ? 'generated' : 'inventory';
        $('#schema-content [data-schema-hub-panel="' + panelTarget + '"]').show().addClass('active');
        window.aysaSchemaV2State.filter = String(target || 'inventory');
        if (target === 'generated') {
            return;
        }
        if (window.aysaSchemaV2State.snapshot) {
            aysaRenderSchemaInventoryTable(window.aysaSchemaV2State.snapshot, window.aysaSchemaV2State.filter);
        }
    });

    (function bootstrapSchemaHub() {
        const $hub = $('#aysa-schema-hub');
        const bootstrapNode = document.getElementById('aysa-schema-hub-bootstrap');
        if (!bootstrapNode || !$hub.length) {
            return;
        }
        try {
            const snapshot = JSON.parse(bootstrapNode.textContent || '{}');
            if (snapshot && snapshot.resolved_project_id) {
                const resolvedProjectId = parseInt(snapshot.resolved_project_id, 10) || 0;
                if (resolvedProjectId > 0) {
                    $hub.attr('data-project-id', resolvedProjectId).data('project-id', resolvedProjectId);
                }
            }
            aysaRenderSchemaHubV2(snapshot);
            window.aysaSchemaHubLoaded = false;
            const summary = snapshot && snapshot.summary ? snapshot.summary : {};
            const hasRows = (parseInt(summary.inventory_total || 0, 10) > 0) || ((snapshot.rows || []).length > 0);
            if (!hasRows && $('#aysa-schema-hub-status').length) {
                $('#aysa-schema-hub-status')
                    .text('Schema inventory is empty. Click Reconcile Inventory to build the DB-backed state.')
                    .css('color', '#996800')
                    .show();
            }
            const schemaTabActive = $('.aysa-tab-btn[data-target="schema"]').hasClass('active');
            if (schemaTabActive) {
                window.setTimeout(function() {
                    if (!window.aysaSchemaHubLoaded) {
                        aysaLoadSchemaHub(false);
                    }
                }, 0);
            }
        } catch (error) {
            console.error('Failed to bootstrap schema hub', error);
            if ($('#aysa-schema-hub-status').length) {
                $('#aysa-schema-hub-status')
                    .text('Schema inventory could not be bootstrapped. Click Reconcile Inventory to rebuild it.')
                    .css('color', '#996800')
                    .show();
            }
        }
    })();

    $(document).on('change', '#aysa-schema-select-all', function() {
        const checked = $(this).is(':checked');
        $('#aysa-schema-v2-table tbody .aysa-schema-row-select').prop('checked', checked);
    });

    async function aysaRunSchemaBulkAction(mode, buttonSelector, label) {
        const rows = $('#aysa-schema-v2-table tbody .aysa-schema-row-select:checked').closest('tr').toArray();
        if (!rows.length) {
            alert('Select at least one row.');
            return;
        }
        const items = aysaSchemaCollectItems(rows, '');
        if (!items.length) {
            alert('No valid URLs were selected.');
            return;
        }
        if (!confirm(label + ' for ' + items.length + ' selected page(s)?')) {
            return;
        }
        const $button = $(buttonSelector);
        const projectId = aysaSchemaResolvedProjectId();
        const originalText = $button.text();
        $button.prop('disabled', true).text('Queueing...');
        try {
            const startResponse = await $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'aysa_technical_schema_job_start',
                    nonce: '<?php echo esc_attr(wp_create_nonce('aysa_technical_audit_nonce')); ?>',
                    project_id: projectId,
                    mode: mode,
                    scope: 'selection',
                    items: JSON.stringify(items)
                }
            });
            if (!startResponse || !startResponse.success || !startResponse.data || !startResponse.data.job) {
                throw new Error((startResponse && startResponse.data) ? startResponse.data : 'Schema job could not be started');
            }
            let job = startResponse.data.job;
            while (job && (job.status === 'queued' || job.status === 'running')) {
                $button.text(`${label}... (${job.processed || 0}/${job.total || 0})`);
                await new Promise(resolve => setTimeout(resolve, 1200));
                const statusResponse = await $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    method: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'aysa_technical_schema_job_status',
                        nonce: '<?php echo esc_attr(wp_create_nonce('aysa_technical_audit_nonce')); ?>',
                        project_id: projectId,
                        job_id: job.job_id
                    }
                });
                if (!statusResponse || !statusResponse.success || !statusResponse.data || !statusResponse.data.job) {
                    throw new Error((statusResponse && statusResponse.data) ? statusResponse.data : 'Schema job status failed');
                }
                job = statusResponse.data.job;
            }
            alert(`Schema job finished.\nSuccessful: ${job.successful || 0}\nGenerated: ${job.generated || 0}\nRewritten: ${job.overwritten || job.rewritten || 0}\nNeeds fields: ${job.needs_fields || 0}\nFailed: ${job.failed || 0}`);
            window.aysaSchemaHubLoaded = false;
            aysaLoadSchemaHub(false);
        } catch (error) {
            alert('❌ ' + (error && error.message ? error.message : 'Schema job failed.'));
        } finally {
            $button.prop('disabled', false).text(originalText);
        }
    }

    $(document).on('click', '#aysa-schema-generate-selected', function(e) {
        e.preventDefault();
        aysaRunSchemaBulkAction('generate_safe', '#aysa-schema-generate-selected', 'Generate');
    });

    $(document).on('click', '#aysa-schema-rewrite-selected', function(e) {
        e.preventDefault();
        aysaRunSchemaBulkAction('rewrite_recommended', '#aysa-schema-rewrite-selected', 'Rewrite');
    });

    $(document).on('click', '#aysa-schema-validate-selected', function(e) {
        e.preventDefault();
        aysaRunSchemaBulkAction('validate', '#aysa-schema-validate-selected', 'Validate');
    });

    window.aysaRunSitewideSchemaOrchestrator = function() {
        window.alert('Global sitewide schema orchestrator is deprecated in the main UI. Use the entity sections inside Schema Markup.');
        return false;
    };

    // Load and render Schema Markup - Initialize buttons when tab is activated
    $('.aysa-tab-btn[data-target="schema"]').on('click', function() {
        var $panel = $('#schema-content');
        if (!window.aysaSchemaHubLoaded) {
            aysaLoadSchemaHub(false);
        }
        
        // Initialize schema buttons when tab is first activated
        if (!$panel.data('buttons-initialized')) {
            // Remove any existing handlers to avoid duplicates
            $(document).off('click', '#aysa-remove-all-schemas');
            $(document).off('click', '#aysa-clean-all-schemas');
            
            // Add fresh event handlers
            $(document).on('click', '#aysa-remove-all-schemas', function(e) {
                e.preventDefault();
                
                const button = $(this);
                const originalText = button.text();
                
                // Get all rows with schema
                const rowsWithSchema = $('#schema-content .aysa-data-table tbody tr').filter(function() {
                    return $(this).find('.aysa-status-label').text().includes('Schema Active');
                });
                
                if (rowsWithSchema.length === 0) {
                    alert('ℹ️ No schemas found to remove');
                    return;
                }
                
                if (!confirm(`⚠️ This will remove ALL schema markup from your website (${rowsWithSchema.length} manual schemas + any automatic schemas). This action cannot be undone. Are you sure?`)) {
                    return;
                }
                
                button.text('🗑️ Disabling All Schemas...').prop('disabled', true);
                
                // Use the new disable all schemas AJAX action
                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    method: 'POST',
                    data: {
                        action: 'aysa_disable_all_schemas',
                        nonce: '<?php echo esc_attr(wp_create_nonce('aysa_schema_nonce')); ?>'
                    },
                    dataType: 'json',
                    timeout: 30000
                })
                .done(function(result) {
                    if (result.success) {
                        // Update all table rows to show no schema
                        $('.aysa-data-table tbody tr').each(function() {
                            const row = $(this);
                            row.find('.aysa-status-label')
                                .removeClass('success')
                                .addClass('error')
                                .html('<span class="dashicons dashicons-warning" style="color: #dc3232; font-size: 16px; vertical-align: middle;"></span>No Schema');
                            row.find('.aysa-add-schema').text('Add Schema');
                            row.find('.aysa-remove-schema').remove(); // Remove all "Remove Schema" buttons
                        });
                        
                        button.text('✅ All Schemas Disabled').css('background', '#dc3545');
                        
                        // Show success message
                        setTimeout(() => {
                            location.reload(); // Refresh to update statistics
                        }, 2000);
                    } else {
                        button.text('❌ Failed').css('background', '#dc3545');
                    }
                })
                .fail(function(xhr, status, error) {
                    button.text('❌ Error').css('background', '#dc3545');
                })
                .always(function() {
                    setTimeout(() => {
                        button.text(originalText).css('background', '#dc3545').prop('disabled', false);
                    }, 3000);
                });
            });
            
            $(document).on('click', '#aysa-clean-all-schemas', function(e) {
                e.preventDefault();
                
                const button = $(this);
                const originalText = button.text();
                
                if (!confirm('🧹 This will physically scan and remove ALL <script type="application/ld+json"> elements from ALL pages on your website. This action cannot be undone. Are you sure?')) {
                    return;
                }
                
                button.text('🧹 Scanning Pages...').prop('disabled', true);
                
                // Get all pages to clean
                const allRows = $('#schema-content .aysa-data-table tbody tr');
                const totalPages = allRows.length;
                let completed = 0;
                let cleaned = 0;
                
                if (totalPages === 0) {
                    alert('No pages found to clean');
                    button.text(originalText).prop('disabled', false);
                    return;
                }
                
                allRows.each(function(index) {
                    const row = $(this);
                    const url = row.find('.aysa-btn-small.aysa-add-schema').data('url');
                    
                    // Delay each request to avoid overwhelming the server
                    setTimeout(() => {
                        button.text(`🧹 Cleaning... (${index + 1}/${totalPages})`);
                        
                        $.ajax({
                            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                            method: 'POST',
                            data: {
                                action: 'aysa_clean_page_schemas',
                                nonce: '<?php echo esc_attr(wp_create_nonce('aysa_schema_nonce')); ?>',
                                url: url
                            },
                            dataType: 'json',
                            timeout: 15000
                        })
                        .done(function(result) {
                            if (result.success && result.data.cleaned > 0) {
                                cleaned += result.data.cleaned;
                                // Update the table row
                                row.find('.aysa-status-label')
                                    .removeClass('success')
                                    .addClass('error')
                                    .html('<span class="dashicons dashicons-warning" style="color: #dc3232; font-size: 16px; vertical-align: middle;"></span>No Schema');
                                row.find('.aysa-add-schema').text('Add Schema');
                                row.find('.aysa-remove-schema').remove();
                            }
                        })
                        .fail(function(xhr, status, error) {
                            // Keep the batch running even if one page cleanup fails.
                        })
                        .always(function() {
                            completed++;
                            
                            if (completed === totalPages) {
                                setTimeout(() => {
                                    button.text(originalText).prop('disabled', false);
                                    alert(`✅ Cleaning completed! ${cleaned} schema elements removed from ${totalPages} pages.`);
                                    location.reload(); // Refresh to update statistics
                                }, 1000);
                            }
                        });
                    }, index * 300); // 300ms delay between each request
                });
            });
            
            // Mark as initialized
            $panel.data('buttons-initialized', true);
        }
    });
    
    // Refresh button for 410 Gone
    $(document).on('click', '#aysa-gone-refresh', function() {
        load410GoneData(true);
    });
    
    // Search functionality for 410 Gone
    $('#aysa-gone-search').on('input', function() {
        var searchTerm = $(this).val();
        var filter = $('#aysa-gone-filter').val();
        load410GoneData(true, filter, searchTerm);
    });
    
    // Filter functionality for 410 Gone
    $('#aysa-gone-filter').on('change', function() {
        var filter = $(this).val();
        var searchTerm = $('#aysa-gone-search').val();
        load410GoneData(true, filter, searchTerm);
    });
    // Action handlers for Redirect / Gone buttons
    $(document).on('click', '.aysa-create-redirect', function() {
        var $row = $(this).closest('tr');
        var sourceText = $row.find('td').eq(1).text();
        var destText = $row.find('td').eq(2).text();
        var origin = aysa_params.api_base_url.replace(/\/+$/, '');
        
        // Asigură-te că sourceUrl și destUrl sunt relative pentru .htaccess
        var source = sourceText.startsWith('http') ? new URL(sourceText).pathname : sourceText;
        var dest = destText.startsWith('http') ? new URL(destText).pathname : destText;
        
        // Get project ID from input or localStorage
        var projectId = getProjectId();
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('Redirect', { 
            SourceUrl: source, 
            DestinationUrl: dest, 
            Status: 'Manual', 
            TotalBacklinks: 0, 
            ProjectId: projectId 
        })
          .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('Redirect created in API:', response);
            }
            
            // 2. Apoi adaugă redirect-ul în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_redirect',
                    source: source,
                    destination: dest,
                    nonce: aysa_params.nonce
                },
                success: function(htaccessResponse) {
                    if (window.AYSA_DEBUG === true) {
                        console.log('Htaccess update response:', htaccessResponse);
                    }
                    
                    if (htaccessResponse.success) {
                        showSuccessModal('Redirect created successfully in API and .htaccess');
                        
                        // Golește formularul
                        $('#aysa-old-url').val('');
                        $('#aysa-new-url').val('');
                    } else {
                        showErrorModal('Redirect created in API but failed to update .htaccess: ' + htaccessResponse.data);
                    }
                    
              // Refresh the 301 Redirects tab to show the new record
              loadRedirectsData(true);
                },
                error: function(xhr, status, error) {
                    console.error('Failed to update .htaccess:', error);
                    showErrorModal('Redirect created in API but failed to update .htaccess');
                    
                    // Refresh the 301 Redirects tab anyways
                    loadRedirectsData(true);
                }
            });
          })
          .catch(function(err) {
              console.error('Error creating redirect:', err);
              showErrorModal('Error creating redirect');
          });
    });
    $(document).on('click', '.aysa-mark-gone', function() {
        const id = $(this).data('id');
        const $row = $(this).closest('tr');
        const url = $row.data('url');
        // Populează modalul cu URL-ul și resetează motivul
        $('#aysa-gone-source-url').text(url);
        $('#aysa-gone-reason').val('');
        $('#aysa-gone-modal').data('error-id', id);
        // Arată modalul
        showModal('aysa-gone-modal');
    });
    // Bulk Create Redirects in 301 Redirects tab
    $('#aysa-bulk-create-redirects').on('click', function() {
        var ids = $('#errors-301-panel tbody input:checked').map(function() { return $(this).val(); }).get();
        if (!ids.length) { showErrorModal('Select at least one item'); return; }
        
        // Get project ID from input or localStorage
        var projectId = getProjectId();
        
        var successCount = 0;
        var htaccessSuccessCount = 0;
        var errorCount = 0;
        var totalCount = ids.length;
        
        ids.forEach(function(id) {
            var $row = $('#errors-301-panel tbody input[value="'+id+'"]').closest('tr');
            var source = $row.find('td').eq(1).text();
            var domain = aysa_params.api_base_url.replace(/\/+$/, '');
            
            // First create redirect in API
            AysaAPI.postData('Redirect/auto-create?sourceUrl=' + encodeURIComponent(source) + '&projectId=' + projectId)
                .then(function(response) {
                    successCount++;
                    if (window.AYSA_DEBUG === true) {
                        console.log('API Redirect created:', response);
                    }
                    
                    // Get the created destination
                    var destination = response.destinationUrl;
                    
                    // Extract relative paths for .htaccess
                    var sourceRelative = source.startsWith('http') ? new URL(source).pathname : source;
                    var destRelative = destination.startsWith('http') ? new URL(destination).pathname : destination;
                    
                    // Then add to .htaccess
                    $.ajax({
                        url: aysa_params.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'aysa_add_htaccess_redirect',
                            source: sourceRelative,
                            destination: destRelative,
                            nonce: aysa_params.nonce
                        },
                        success: function(htaccessResponse) {
                            htaccessSuccessCount++;
                            checkIfAllComplete();
                        },
                        error: function() {
                            // Count only API success, note .htaccess error separately
                            checkIfAllComplete();
                        }
                    });
                })
                .catch(function(err) {
                    errorCount++;
                    console.error('Error creating redirect:', err);
                    checkIfAllComplete();
                });
        });
        
        function checkIfAllComplete() {
            if(successCount + errorCount === totalCount) {
                if (errorCount > 0) {
                    var message = successCount + ' redirects created successfully';
                    message += ', ' + htaccessSuccessCount + ' added to .htaccess';
                    if (errorCount > 0) message += ', ' + errorCount + ' failed';
                    showSuccessModal(message);
                } else {
                    var message = 'All ' + successCount + ' redirects created successfully';
                    message += ', ' + htaccessSuccessCount + ' added to .htaccess';
                    showSuccessModal(message);
                }
                // Refresh the 301 Redirects tab to show the new records
                loadRedirectsData(true);
            }
        }
    });
    // Bulk actions in 404 Errors tab
    $('#aysa-bulk-apply-redirects').on('click', function() {
        var ids = $('#errors-content tbody input:checked').map(function() { return $(this).val(); }).get();
        if (!ids.length) { showErrorModal('Select at least one item'); return; }
        // Bulk process 404 errors
        AysaAPI.postData('unprocessed/bulk-process', { UrlIds: ids, Action: '301 Redirect' })
          .then(function(processed) {
            processed.forEach(function(item) {
                $('#errors-content tbody input[value="'+item.Id+'"]').closest('tr').remove();
            });
            showSuccessModal('Bulk 301 redirects applied');
          })
          .catch(function() { showErrorModal('Error in bulk redirect'); });
    });
    // Bulk Mark As Gone in 404 Errors tab
    $('#aysa-bulk-mark-gone').on('click', function() {
        var ids = $('#errors-content tbody input:checked').map(function() { return $(this).val(); }).get();
        if (!ids.length) { showErrorModal('Select at least one item'); return; }
        showConfirmModal('Confirm Bulk Gone', 'Are you sure you want to mark these URLs as Gone (410)?', function() {
            // ... restul codului rămâne neschimbat ...
        });
    });
    // Handler for seeding test 404 data
    $(document).on('click', '#aysa-seed-404', function() {
      var $tbody = $('#errors-content tbody').empty();
      // Get site domain for full URLs
      var siteDomain = window.location.protocol + '//' + window.location.host;
      var test = [{
        id: 999,
        url: siteDomain + '/fake-404-page',
        suggestedRedirectUrl: siteDomain + '/home',
        action: 'Manual',
        totalBacklinks: 0,
        dateLastDetected: new Date().toISOString().split('T')[0]
      }];
      test.forEach(function(e) {
        $tbody.append(
          '<tr>' +
            '<td><input type="checkbox" class="aysa-select-item" value="'+e.id+'"></td>' +
            '<td>'+e.url+'</td>' +
            '<td>'+e.suggestedRedirectUrl+'</td>' +
            '<td>'+e.action+'</td>' +
            '<td>'+e.totalBacklinks+'</td>' +
            '<td>'+e.dateLastDetected+'</td>' +
            '<td>' +
              '<button class="button aysa-create-redirect" data-id="'+e.id+'">Redirect</button> ' +
              '<button class="button aysa-mark-gone" data-id="'+e.id+'">Gone</button>' +
            '</td>' +
          '</tr>'
        );
      });
    });
    // Handler pentru butonul de creare manuală a redirectului
    $('#aysa-add-manual-redirect').on('click', function() {
        var oldUrl = $('#aysa-old-url').val().trim();
        var newUrl = $('#aysa-new-url').val().trim();
        
        // Validare de bază
        if (!oldUrl || !newUrl) {
            showErrorModal('Both Old URL and New URL are required.');
            return;
        }
        
        // Curăță URL-urile de spații pentru a preveni problemele
        oldUrl = cleanUrl(oldUrl);
        newUrl = cleanUrl(newUrl);
        
        // Actualizează valorile în input-uri pentru feedback vizual
        $('#aysa-old-url').val(oldUrl);
        $('#aysa-new-url').val(newUrl);
        
        // Get project ID from input or localStorage
        var projectId = getProjectId();
        
        // Get site domain for full URLs
        var siteDomain = window.location.protocol + '//' + window.location.host;
        
        // Asigură-te că URL-urile încep cu / dacă nu sunt URL-uri complete
        if (!oldUrl.startsWith('http') && !oldUrl.startsWith('/')) {
            oldUrl = '/' + oldUrl;
        }
        
        if (!newUrl.startsWith('http') && !newUrl.startsWith('/')) {
            newUrl = '/' + newUrl;
        }
        
        // Adaugă domeniul pentru URL-uri relative (pentru a salva URL-uri complete în API)
        var fullOldUrl = oldUrl.startsWith('http') ? oldUrl : siteDomain + oldUrl;
        var fullNewUrl = newUrl.startsWith('http') ? newUrl : siteDomain + newUrl;
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('Redirect', { 
            SourceUrl: fullOldUrl, 
            DestinationUrl: fullNewUrl, 
            Status: 'Manual', 
            TotalBacklinks: 0, 
            ProjectId: projectId 
        })
        .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('Redirect created in API:', response);
            }
            
            // Pentru .htaccess folosim căi relative (necesare pentru RegEx matches)
            var sourceRelative = oldUrl.startsWith('http') ? new URL(oldUrl).pathname : oldUrl;
            var destRelative = newUrl.startsWith('http') ? new URL(newUrl).pathname : newUrl;
            
            // 2. Apoi adaugă redirect-ul în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_redirect',
                    source: sourceRelative,
                    destination: destRelative,
                    nonce: aysa_params.nonce
                },
                success: function(htaccessResponse) {
                    if (window.AYSA_DEBUG === true) {
                        console.log('Htaccess update response:', htaccessResponse);
                    }
                    
                    if (htaccessResponse.success) {
                        showSuccessModal('Redirect created successfully in API and .htaccess');
                        
                        // Golește formularul
                        $('#aysa-old-url').val('');
                        $('#aysa-new-url').val('');
                    } else {
                        showErrorModal('Redirect created in API but failed to update .htaccess: ' + htaccessResponse.data);
                    }
                    
                    // Refresh the 301 Redirects tab to show the new record
                    loadRedirectsData(true);
                },
                error: function(xhr, status, error) {
                    console.error('Failed to update .htaccess:', error);
                    showErrorModal('Redirect created in API but failed to update .htaccess');
                    
                    // Refresh the 301 Redirects tab anyways
                    loadRedirectsData(true);
                }
            });
        })
        .catch(function(err) {
            console.error('Error creating redirect:', err);
            showErrorModal('Error creating redirect in API');
        });
    });
    // Handler for adding manual gone URLs
    $('#aysa-add-manual-gone').on('click', function() {
        var url = $('#aysa-gone-url').val().trim();
        var reason = $('#aysa-gone-reason').val().trim();
        
        // Validare de bază
        if (!url || !reason) {
            showErrorModal('Both URL and Reason are required.');
            return;
        }
        
        // Curăță URL-ul de spații pentru a preveni problemele
        url = cleanUrl(url);
        
        // Actualizează valoarea în input pentru feedback vizual
        $('#aysa-gone-url').val(url);
        
        showConfirmModal('Confirm Mark as Gone', 'Are you sure you want to mark this URL as Gone (410)?', function() {
            // Get project ID from input or localStorage
            var projectId = getProjectId();
            
            // Get site domain for full URLs
            var siteDomain = window.location.protocol + '//' + window.location.host;
            
            // Asigură-te că URL-urile încep cu / dacă nu sunt URL-uri complete
            if (!url.startsWith('http') && !url.startsWith('/')) {
                url = '/' + url;
            }
            
            // Adaugă domeniul pentru URL-uri relative (pentru a salva URL-uri complete în API)
            var fullUrl = url.startsWith('http') ? url : siteDomain + url;
            
            // 1. Mai întâi salvează în API pentru sincronizare
            AysaAPI.postData('GoneUrl', { 
                Url: fullUrl, 
                Reason: reason, 
                ProjectId: projectId 
            })
            .then(function(response) {
                if (window.AYSA_DEBUG === true) {
                    console.log('API Gone URL created:', response);
                }
                
                // Extract relative path for .htaccess
                var urlRelative = url.startsWith('http') ? new URL(url).pathname : url;
                
                // 2. Apoi adaugă regula Gone în .htaccess folosind AJAX WordPress
                $.ajax({
                    url: aysa_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'aysa_add_htaccess_gone',
                        url: urlRelative,
                        nonce: aysa_params.nonce
                    },
                    success: function(htaccessResponse) {
                        if (window.AYSA_DEBUG === true) {
                            console.log('Htaccess update response:', htaccessResponse);
                        }
                        
                        if (htaccessResponse.success) {
                            showSuccessModal(htaccessResponse.data.message || 'URL marked as Gone successfully in API and .htaccess');
                            
                            // Golește formularul
                            $('#aysa-gone-url').val('');
                            $('#aysa-gone-reason').val('');
                        } else {
                            showErrorModal('URL marked as Gone in API but failed to update .htaccess: ' + htaccessResponse.data);
                        }
                        
                        // Refresh the 410 Gone tab to show the new record
                        $('#errors-410-panel').data('loaded', false);
                        openErrorsSubtab('410', true);
                    },
                    error: function(xhr, status, error) {
                        console.error('Failed to update .htaccess:', error);
                        showErrorModal('URL marked as Gone in API but failed to update .htaccess');
                        
                        // Refresh the 410 Gone tab anyways
                        $('#errors-410-panel').data('loaded', false);
                        openErrorsSubtab('410', true);
                    }
                });
            })
            .catch(function(err) {
                console.error('Error marking URL as gone:', err);
                showErrorModal('Error marking URL as gone');
          });
        });
    });
    // Eveniment pentru butonul "Redirect" din tabel
    $(document).on('click', '.aysa-404-redirect', function() {
        const id = $(this).data('id');
        const url = $(this).data('url');
        
        // Populate the modal
        $('#aysa-redirect-source-url').text(url);
        $('#aysa-redirect-target-url').val('/');
        $('#aysa-redirect-modal').data('error-id', id);
        
        // Show the modal
        showModal('aysa-redirect-modal');
    });
    
    // Redirect modal cancel button
    $('#aysa-redirect-cancel, #aysa-redirect-modal .aysa-modal-close').on('click', function() {
        hideModal('aysa-redirect-modal');
    });
    
    // Redirect modal confirm button
    $('#aysa-redirect-confirm').on('click', function() {
        const id = $('#aysa-redirect-modal').data('error-id');
        const url = $('#aysa-redirect-source-url').text();
        let destinationUrl = $('#aysa-redirect-target-url').val();
        
        if (!destinationUrl) {
            showErrorModal('Please enter a destination URL');
            return;
        }
        
        // Curăță URL-ul destinație de spații pentru a preveni problemele
        destinationUrl = cleanUrl(destinationUrl);
        
        // Actualizează valoarea în input pentru feedback vizual
        $('#aysa-redirect-target-url').val(destinationUrl);
        
        // Get project ID from localStorage
        var projectId = getProjectId();
        
        // Get site domain for full URLs
        const siteDomain = window.location.protocol + '//' + window.location.host;
        const sourceUrl = url.startsWith('http') ? url : siteDomain + (url.startsWith('/') ? url : '/' + url);
        
        // Format destination URL
        const destUrl = destinationUrl.startsWith('http') ? destinationUrl : 
                       (destinationUrl.startsWith('/') ? siteDomain + destinationUrl : siteDomain + '/' + destinationUrl);
        
        // Extract paths for .htaccess
        const sourcePath = url.startsWith('http') ? new URL(url).pathname : (url.startsWith('/') ? url : '/' + url);
        const destPath = destinationUrl.startsWith('http') ? new URL(destinationUrl).pathname : 
                        (destinationUrl.startsWith('/') ? destinationUrl : '/' + destinationUrl);
        
        // Hide the redirect modal
        hideModal('aysa-redirect-modal');
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('Redirect', { 
            SourceUrl: sourceUrl, 
            DestinationUrl: destUrl, 
            Status: 'AutoFixed', 
            TotalBacklinks: 0, 
            ProjectId: projectId 
        })
        .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('Redirect created in API:', response);
            }
            
            // 2. Apoi adaugă redirect-ul în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_redirect',
                    nonce: aysa_params.nonce,
                    source: sourcePath,
                    destination: destPath
                },
                success: function(response) {
                    if (response.success) {
                        // Show success modal
                        showSuccessModal(response.data.message || 'Redirect created successfully', function() {
                            // Remove row from table after modal is closed
                            $(`#aysa-404-table tbody tr[data-id="${id}"]`).fadeOut(300, function() {
                                $(this).remove();
                                
                                // Check if table is empty
                                if ($('#aysa-404-table tbody tr').length === 0) {
                                    $('#aysa-404-table tbody').html(`
                                        <tr>
                                            <td colspan="7" class="aysa-empty-message">
                                                No 404 errors found. Your site appears to be working correctly.
                                            </td>
                                        </tr>
                                    `);
                                }
                            });
                        });
                    } else {
                        showErrorModal(response.data || 'Failed to create redirect');
                    }
                },
                error: function() {
                    showErrorModal('Failed to communicate with the server');
                }
            });
        })
        .catch(function(err) {
            console.error('Error creating redirect:', err);
            showErrorModal('Failed to create redirect');
        });
    });
    
    // Setup the Mark Gone modal
    $(document).on('click', '.aysa-mark-gone', function() {
        const id = $(this).data('id');
        const $row = $(this).closest('tr');
        const url = $row.data('url');
        
        // Populate the modal
        $('#aysa-gone-source-url').text(url);
        $('#aysa-gone-reason').val('');
        $('#aysa-gone-modal').data('error-id', id);
        
        // Show the modal
        showModal('aysa-gone-modal');
    });
    
    // Mark Gone modal cancel button
    $('#aysa-gone-cancel, #aysa-gone-modal .aysa-modal-close').on('click', function() {
        hideModal('aysa-gone-modal');
    });
    
    // Mark Gone modal confirm button
    $('#aysa-gone-confirm').on('click', function() {
        const id = $('#aysa-gone-modal').data('error-id');
        const url = $('#aysa-gone-source-url').text();
        // Extrage reason din inputul din modalul curent, nu global
        const reason = $('#aysa-gone-modal').find('#aysa-gone-reason').val();

        if (!reason) {
            showErrorModal('Please enter a reason for marking as Gone');
            return;
        }
        
        // Get project ID from localStorage
        var projectId = getProjectId();
        
        // Get site domain for full URLs
        const siteDomain = window.location.protocol + '//' + window.location.host;
        const fullUrl = url.startsWith('http') ? url : siteDomain + (url.startsWith('/') ? url : '/' + url);
        
        // Hide the gone modal
        hideModal('aysa-gone-modal');
        
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('GoneUrl', { 
            Url: fullUrl, 
            Reason: reason, 
            ProjectId: projectId 
        })
        .then(function(response) {
            if (window.AYSA_DEBUG === true) {
                console.log('API Gone URL created:', response);
            }
            
            // 2. Apoi adaugă regula Gone în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_mark_gone',
                    nonce: aysa_params.nonce,
                    error_id: id,
                    reason: reason
                },
                success: function(response) {
                    if (response.success) {
                        // Show success modal
                        showSuccessModal(response.data.message || 'URL marked as gone successfully', function() {
                            // Remove row from table after modal is closed
                            $(`#aysa-404-table tbody tr[data-id="${id}"]`).fadeOut(300, function() {
                                $(this).remove();
                                
                                // Check if table is empty
                                if ($('#aysa-404-table tbody tr').length === 0) {
                                    $('#aysa-404-table tbody').html(`
                                        <tr>
                                            <td colspan="7" class="aysa-empty-message">
                                                No 404 errors found. Your site appears to be working correctly.
                                            </td>
                                        </tr>
                                    `);
                                }
                            });
                        });
                    } else {
                        showErrorModal(response.data || 'Failed to mark URL as gone');
                    }
                },
                error: function() {
                    showErrorModal('Failed to communicate with the server');
                }
            });
        })
        .catch(function(err) {
            console.error('Error marking URL as gone:', err);
            showErrorModal('Failed to mark URL as gone');
        });
    });

    // Modal close handlers
    $('.aysa-modal-close').on('click', function() {
        $(this).closest('.aysa-modal-overlay').hide();
    });

    // General modal close handlers - clicking outside the modal
    $('.aysa-modal-overlay').on('click', function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    // Success modal OK button
    $('.aysa-success-ok').on('click', function() {
        $(this).closest('.aysa-modal-overlay').hide();
    });

    // Error modal OK button
    $('.aysa-error-ok').on('click', function() {
        $(this).closest('.aysa-modal-overlay').hide();
    });

    // === REAL-TIME URL VALIDATION: Clean spaces and invalid characters ===
    // Function to clean URL properly - preserve intentional dashes but fix invalid starts
    function cleanUrl(url) {
        var cleaned = url
            .trim()                     // Elimină spațiile de la început și sfârșit
            .replace(/\s+/g, '-')       // Înlocuiește doar spațiile cu liniuțe
            .replace(/-+/g, '-');       // Înlocuiește liniuțele multiple cu una singură
        
        // Dacă nu începe cu / sau http, elimină liniuțele de la început
        if (!cleaned.startsWith('/') && !cleaned.startsWith('http')) {
            cleaned = cleaned.replace(/^-+/, '');
        }
        
        return cleaned;
    }
    
    // Validare în timp real pentru input-urile de redirect manual
    $('#aysa-old-url, #aysa-new-url').on('input', function() {
        var $this = $(this);
        var value = $this.val();
        var cleanValue = cleanUrl(value);
        
        if (value !== cleanValue) {
            $this.val(cleanValue);
        }
    });
    
    // Validare în timp real pentru input-ul din modal
    $('#aysa-redirect-target-url').on('input', function() {
        var $this = $(this);
        var value = $this.val();
        var cleanValue = cleanUrl(value);
        
        if (value !== cleanValue) {
            $this.val(cleanValue);
        }
    });
    
    // Validare în timp real pentru input-ul Gone URL
    $('#aysa-gone-url').on('input', function() {
        var $this = $(this);
        var value = $this.val();
        var cleanValue = cleanUrl(value);
        
        if (value !== cleanValue) {
            $this.val(cleanValue);
        }
    });
    
    // === 404 Redirect Modal: Dropdown & Suggestions Logic ===
    $('#aysa-redirect-type').on('change', function() {
        var type = $(this).val();
        if (!type) {
            $('#aysa-redirect-suggestion-group').hide();
            $('#aysa-redirect-suggestion').empty();
            return;
        }
        // Arată dropdown-ul de sugestii
        $('#aysa-redirect-suggestion-group').show();
        $('#aysa-redirect-suggestion').html('<option>Loading...</option>');
        // AJAX către WordPress pentru a obține lista
        $.ajax({
            url: aysa_params.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_redirect_suggestions',
                type: type,
                nonce: aysa_params.nonce
            },
            success: function(response) {
                if (response.success && response.data.length) {
                    var options = '<option value="">Choose...</option>';
                    response.data.forEach(function(item) {
                        options += '<option value="' + item.url + '">' + item.title + '</option>';
                    });
                    $('#aysa-redirect-suggestion').html(options);
                } else {
                    $('#aysa-redirect-suggestion').html('<option value="">No suggestions found</option>');
                }
            }
        });
    });
    $('#aysa-redirect-suggestion').on('change', function() {
        var val = $(this).val();
        if (val) {
            $('#aysa-redirect-target-url').val(val);
        }
    });
    $('#aysa-redirect-type').on('change', function() {
        // Reset inputul manual când schimbi tipul
        $('#aysa-redirect-target-url').val('');
    });
    
    // === Manual Redirect: Choose from Pages Button ===
    $('#aysa-choose-page-manual').on('click', function() {
        // Creează modalul cu opțiuni complete (ca la 404 errors)
        var modalHtml = `
            <div id="aysa-manual-page-modal" class="aysa-modal-overlay" style="display:block; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:999999;">
                <div class="aysa-modal aysa-modal-short" style="position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); background:white; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.3); max-width:500px; width:90%;">
                    <div class="aysa-modal-header" style="padding:20px 20px 0 20px; border-bottom:1px solid #e0e0e0; margin-bottom:20px;">
                        <h3 style="margin:0; font-size:18px; font-weight:600;">Choose Destination</h3>
                        <button class="aysa-modal-close" onclick="$('#aysa-manual-page-modal').remove();" style="position:absolute; top:15px; right:15px; background:none; border:none; font-size:24px; cursor:pointer; color:#666;">&times;</button>
                    </div>
                    <div class="aysa-modal-body" style="padding:0 20px;">
                        <div class="aysa-form-group" style="margin-bottom:15px;">
                            <label for="aysa-manual-destination-type" style="display:block; margin-bottom:5px; font-weight:500;">Destination type:</label>
                            <select id="aysa-manual-destination-type" class="aysa-form-control" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                                <option value="">Choose type...</option>
                                <option value="post">Article</option>
                                <option value="page">Page</option>
                                <option value="product">Product</option>
                                <option value="category">Category</option>
                            </select>
                        </div>
                        <div class="aysa-form-group" id="aysa-manual-suggestion-group" style="display:none; margin-bottom:15px;">
                            <label for="aysa-manual-suggestion" style="display:block; margin-bottom:5px; font-weight:500;">Select destination:</label>
                            <select id="aysa-manual-suggestion" class="aysa-form-control" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                                <option value="">Choose...</option>
                            </select>
                        </div>
                    </div>
                    <div class="aysa-modal-footer" style="padding:20px; border-top:1px solid #e0e0e0; text-align:right;">
                        <button class="aysa-btn aysa-btn-secondary" onclick="$('#aysa-manual-page-modal').remove();" style="margin-right:10px; padding:8px 16px; background:#f1f1f1; border:1px solid #ddd; border-radius:4px; cursor:pointer;">Cancel</button>
                        <button class="aysa-btn aysa-btn-primary" id="aysa-confirm-manual-selection" style="padding:8px 16px; background:#0073aa; color:white; border:none; border-radius:4px; cursor:pointer;">Select</button>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
        
        // Handler pentru schimbarea tipului de destinație
        $('#aysa-manual-destination-type').on('change', function() {
            var type = $(this).val();
            if (!type) {
                $('#aysa-manual-suggestion-group').hide();
                $('#aysa-manual-suggestion').empty();
                return;
            }
            
            // Arată dropdown-ul de sugestii
            $('#aysa-manual-suggestion-group').show();
            $('#aysa-manual-suggestion').html('<option>Loading...</option>');
            
            // AJAX către WordPress pentru a obține lista
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_redirect_suggestions',
                    type: type,
                    nonce: aysa_params.nonce
                },
                success: function(response) {
                    if (response.success && response.data.length) {
                        var options = '<option value="">Choose...</option>';
                        response.data.forEach(function(item) {
                            options += '<option value="' + item.url + '">' + item.title + '</option>';
                        });
                        $('#aysa-manual-suggestion').html(options);
                    } else {
                        $('#aysa-manual-suggestion').html('<option value="">No suggestions found</option>');
                    }
                },
                error: function() {
                    $('#aysa-manual-suggestion').html('<option value="">Error loading suggestions</option>');
                }
            });
        });
        
        // Handler pentru confirmarea selecției
        $('#aysa-confirm-manual-selection').on('click', function() {
            var selectedUrl = $('#aysa-manual-suggestion').val();
            if (selectedUrl) {
                $('#aysa-new-url').val(selectedUrl);
                $('#aysa-manual-page-modal').remove();
            } else {
                alert('Please select a destination first.');
            }
        });
        
        // Handler pentru închiderea modalului prin X
        $('.aysa-modal-close').on('click', function() {
            $('#aysa-manual-page-modal').remove();
        });
        
        // Handler specific pentru butonul de Cancel
        $(document).on('click', '#aysa-manual-page-modal .aysa-btn-secondary', function(e) {
            e.preventDefault();
            $('#aysa-manual-page-modal').remove();
        });
        
        // Închide modalul când se click în afara lui
        $('#aysa-manual-page-modal').on('click', function(e) {
            if (e.target === this) {
                $(this).remove();
            }
        });
    });
    // La deschiderea modalului, resetează controalele
    $(document).on('click', '.aysa-404-redirect', function() {
        $('#aysa-redirect-type').val('');
        $('#aysa-redirect-suggestion-group').hide();
        $('#aysa-redirect-suggestion').empty();
        $('#aysa-redirect-target-url').val('');
    });
    // La confirmare, folosește sugestia sau inputul manual
    $('#aysa-redirect-confirm').off('click').on('click', function() {
        const id = $('#aysa-redirect-modal').data('error-id');
        const url = $('#aysa-redirect-source-url').text();
        const selectedSuggestion = $('#aysa-redirect-suggestion').val();
        const manualUrl = $('#aysa-redirect-target-url').val();
        const destinationUrl = selectedSuggestion || manualUrl;
        if (!destinationUrl) {
            showErrorModal('Please select or enter a destination URL!');
            return;
        }
        // Get project ID from localStorage
        var projectId = getProjectId();
        // Get site domain for full URLs
        const siteDomain = window.location.protocol + '//' + window.location.host;
        const sourceUrl = url.startsWith('http') ? url : siteDomain + (url.startsWith('/') ? url : '/' + url);
        // Format destination URL
        const destUrl = destinationUrl.startsWith('http') ? destinationUrl : 
                       (destinationUrl.startsWith('/') ? siteDomain + destinationUrl : siteDomain + '/' + destinationUrl);
        // Extract paths for .htaccess
        const sourcePath = url.startsWith('http') ? new URL(url).pathname : (url.startsWith('/') ? url : '/' + url);
        const destPath = destinationUrl.startsWith('http') ? new URL(destinationUrl).pathname : 
                        (destinationUrl.startsWith('/') ? destinationUrl : '/' + destinationUrl);
        // Hide the redirect modal
        hideModal('aysa-redirect-modal');
        // 1. Mai întâi salvează în API pentru sincronizare
        AysaAPI.postData('Redirect', { 
            SourceUrl: sourceUrl, 
            DestinationUrl: destUrl, 
            Status: 'AutoFixed', 
            TotalBacklinks: 0, 
            ProjectId: projectId 
        })
        .then(function(response) {
            // 2. Apoi adaugă redirect-ul în .htaccess folosind AJAX WordPress
            $.ajax({
                url: aysa_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_add_htaccess_redirect',
                    nonce: aysa_params.nonce,
                    source: sourcePath,
                    destination: destPath
                },
                success: function(response) {
                    if (response.success) {
                        showSuccessModal(response.data.message || 'Redirect created successfully!', function() {
                            $(`#aysa-404-table tbody tr[data-id="${id}"]`).fadeOut(300, function() {
                                $(this).remove();
                                if ($('#aysa-404-table tbody tr').length === 0) {
                                    $('#aysa-404-table tbody').html(`
                                        <tr>
                                            <td colspan="7" class="aysa-empty-message">
                                                No 404 errors found. Your site appears to be working correctly.
                                            </td>
                                        </tr>
                                    `);
                                }
                            });
                        });
                    } else {
                        showErrorModal(response.data || 'Failed to create redirect');
                    }
                },
                error: function() {
                    showErrorModal('Failed to communicate with the server');
                }
            });
        })
        .catch(function(err) {
            console.error('Error creating redirect:', err);
            showErrorModal('Failed to create redirect');
        });
    });

    // === 404 Redirect Modal: Checkbox logic ===
    $('#aysa-redirect-manual-checkbox').on('change', function() {
        if ($(this).is(':checked')) {
            $('#aysa-redirect-suggestion-area').hide();
            $('#aysa-redirect-manual-group').show();
        } else {
            $('#aysa-redirect-suggestion-area').show();
            $('#aysa-redirect-manual-group').hide();
        }
    });
    // La deschiderea modalului, resetăm starea
    $(document).on('click', '.aysa-404-redirect', function() {
        $('#aysa-redirect-manual-checkbox').prop('checked', false);
        $('#aysa-redirect-suggestion-area').show();
        $('#aysa-redirect-manual-group').hide();
        $('#aysa-redirect-type').val('');
        $('#aysa-redirect-suggestion-group').hide();
        $('#aysa-redirect-suggestion').empty();
        $('#aysa-redirect-target-url').val('');
    });

    // PageSpeed test button click handler removed as the button was removed
    /*
    $('#aysa-run-pagespeed').on('click', function() {
        var button = $(this);
        button.prop('disabled', true).text('Running Test...');

        var siteUrl = '<?php echo esc_js(get_site_url()); ?>';

        function runTest(strategy) {
            // Use AysaAPI to get the correct endpoint URL (including localhost routing)
            const metricsUrl = AysaAPI.getEndpointUrl('pagespeed_metrics');
            
            return $.ajax({
                url: metricsUrl,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    url: siteUrl,
                    strategy: strategy
                })
            });
        }

        Promise.all([
            runTest('desktop'),
            runTest('mobile')
        ])
        .then(function([desktop, mobile]) {
            function renderTable(selector, metrics) {
                var rows = '';
                var map = {
                    firstContentfulPaint: 'First Contentful Paint',
                    timeToInteractive: 'Time to Interactive',
                    speedIndex: 'Speed Index',
                    totalBlockingTime: 'Total Blocking Time',
                    largestContentfulPaint: 'Largest Contentful Paint',
                    cumulativeLayoutShift: 'Cumulative Layout Shift'
                };
                for (var key in map) {
                    var value = metrics[key];
                    var unit = (key === 'cumulativeLayoutShift') ? '' : 's';
                    if (key === 'totalBlockingTime') unit = 'ms';
                    rows += '<tr>' +
                        '<td>' + map[key] + '</td>' +
                        '<td>' + value + unit + '</td>' +
                        '<td></td>' +
                    '</tr>';
                }
                $(selector).find('tbody').html(rows);
            }
            renderTable('.aysa-pagespeed-desktop .aysa-metrics-table', desktop);
            renderTable('.aysa-pagespeed-mobile .aysa-metrics-table', mobile);
        })
        .catch(function(error) {
            alert('Error running PageSpeed test: ' + (error.responseJSON?.message || error.statusText || 'Unknown error'));
        })
        .always(function() {
            button.prop('disabled', false).text('Run PageSpeed Test');
        });
    });
    */

    // Helper pentru generare tabel metrici
    function renderMetricsTable(metrics) {
        if (!metrics) {
            console.error("Metrics is undefined or null");
            return '<tr><td colspan="3">No data available</td></tr>';
        }
        
        var map = {
            firstContentfulPaint: 'First Contentful Paint',
            timeToInteractive: 'Time to Interactive',
            speedIndex: 'Speed Index',
            totalBlockingTime: 'Total Blocking Time',
            largestContentfulPaint: 'Largest Contentful Paint',
            cumulativeLayoutShift: 'Cumulative Layout Shift'
        };
        var rows = '';
        for (var key in map) {
            var value = (metrics && metrics[key] !== undefined) ? metrics[key] : '-';
            var unit = (key === 'cumulativeLayoutShift') ? '' : 's';
            if (key === 'totalBlockingTime') unit = 'ms';
            rows += '<tr>' +
                '<td>' + map[key] + '</td>' +
                '<td>' + value + unit + '</td>' +
                '<td></td>' +
            '</tr>';
        }
        return rows;
    }
    
    // Helper pentru generare checklist opportunities
    function renderOpportunities(opps, totalByteWeight) {
        if (!opps || !Array.isArray(opps)) {
            console.error("Opportunities is undefined, null, or not an array");
            return '<div class="aysa-checklist-item">No optimization opportunities available</div>';
        }
        
        var html = '';
        opps.forEach(function(opp) {
            // Calculează procentul dacă nu există deja
            var percent = null;
            if (opp.savingsPercent != null) {
                percent = opp.savingsPercent;
            } else if (opp.savingsBytes != null && totalByteWeight) {
                percent = Math.round((opp.savingsBytes / totalByteWeight) * 100);
            }
            
            // Determină statusul bazat pe procent și importanță
            // LOGICĂ INVERSATĂ: Procent mare = status pozitiv (verde)
            var status = 'info'; // Default este info (albastru)
            var icon = 'dashicons-info';
            
            // Status bazat pe procent
            if (percent !== null) {
                if (percent >= 5) {
                    status = 'success'; // Verde pentru oportunități bune
                    icon = 'dashicons-yes-alt';
                }
                if (percent >= 15) {
                    status = 'warning'; // Portocaliu pentru oportunități importante
                    icon = 'dashicons-marker';
                }
                if (percent >= 25) {
                    status = 'success'; // Verde pentru oportunități foarte importante
                    icon = 'dashicons-star-filled';
                }
                
                // Dar dacă procentul e foarte mic (sub 1%), doar informativ
                if (percent < 1) {
                    status = 'info';
                    icon = 'dashicons-info';
                }
            } else {
                // În lipsa procentului, bazează-te pe ID
                if (opp.id && (opp.id.includes('error') || opp.id.includes('critical'))) {
                    status = 'error';
                    icon = 'dashicons-warning';
                }
            }
            
            // Crează badge cu clasa potrivită pentru procent
            var percentBadge = '';
            if (percent !== null) {
                var badgeClass = '';
                if (percent >= 25) badgeClass = 'aysa-badge-success'; // Verde pentru economii mari
                else if (percent >= 15) badgeClass = 'aysa-badge-warning'; // Portocaliu pentru economii medii
                else if (percent >= 5) badgeClass = 'aysa-badge-info'; // Albastru pentru economii mici
                else badgeClass = 'aysa-badge-neutral'; // Neutru pentru economii foarte mici
                
                percentBadge = '<span class="aysa-badge ' + badgeClass + '">' + percent + '%</span>';
            } else {
                percentBadge = '<span class="aysa-badge">-</span>';
            }

            html += '<div class="aysa-checklist-item">' +
                '<div class="aysa-checklist-status ' + status + '"><span class="dashicons ' + icon + '"></span></div>' +
                '<div class="aysa-checklist-content">' +
                    '<div class="aysa-checklist-title">' + opp.title + '</div>' +
                    '<div class="aysa-checklist-desc">' + opp.description + '<br><strong>' + opp.displayValue + '</strong></div>' +
                '</div>' +
                '<div class="aysa-checklist-percentage">' + percentBadge + '</div>' +
            '</div>';
        });
        return html;
    }

    var siteUrl = '<?php echo esc_js(get_site_url()); ?>';
    var localPageSpeedUrl = '<?php
        $aysa_local_pagespeed_url = defined('AYSA_LOCAL_PAGESPEED_URL') ? AYSA_LOCAL_PAGESPEED_URL : get_site_url();
        echo esc_js($aysa_local_pagespeed_url);
    ?>';
    var isPageSpeedLegacyDisabled = false;
    var desktopData = null, mobileData = null, overviewData = null;
    var dataLoaded = {
        desktop: false,
        mobile: false,
        overview: false
    };

    function showPageSpeedNotice(text, type) {
        var cssClass = 'info';
        if (type === 'error') {
            cssClass = 'error';
        } else if (type === 'success') {
            cssClass = 'success';
        }
        $('#overview-data').show().html(
            '<div class="aysa-site-audit-message ' + cssClass + '">' + String(text || '') + '</div>'
        );
    }
    window.aysaShowPageSpeedNotice = showPageSpeedNotice;

    // Unified function to load all PageSpeed data
    function loadAllPageSpeedData(options = {}) {
        if (isPageSpeedLegacyDisabled) {
            console.warn('PageSpeed legacy endpoints are disabled on local environment (WIP broker migration).');
            hideAllLoadingStates();
            showPageSpeedNotice('PageSpeed legacy endpoint is disabled in local mode (WIP). Use Site Audit above.', 'info');
            return Promise.resolve();
        }

        const { 
            refreshDesktop = true, 
            refreshMobile = true, 
            refreshOverview = true,
            desktopButton = null,
            mobileButton = null,
            overviewButton = null
        } = options;
        
        // Function to get Project ID from multiple sources
        function getProjectId() {
            const candidates = [
                typeof aysaParams !== 'undefined' ? aysaParams.canonical_project_id : 0,
                typeof aysaParams !== 'undefined' ? aysaParams.project_id : 0,
                typeof aysaParams !== 'undefined' ? aysaParams.wp_project_id : 0,
                window.aysaParams && window.aysaParams.canonical_project_id,
                window.aysaParams && window.aysaParams.project_id,
                window.aysaParams && window.aysaParams.wp_project_id
            ];
            for (let i = 0; i < candidates.length; i++) {
                const parsed = parseInt(candidates[i], 10);
                if (!isNaN(parsed) && parsed > 0) {
                    return parsed;
                }
            }
            return 0;
        }
        
        // Get the project ID using the unified function
        const projectId = getProjectId();
        
        if (!projectId) {
            console.error('No project ID found');
            alert('Project ID not found. Please configure your project in Settings.');
            return;
        }
        
        // Keep track of pending requests
        let pendingRequests = 0;
        let completedRequests = 0;
        let loadingTimeout = null;

        // Function to hide all loading states
        function hideAllLoadingStates() {
            $('#overview-loading').hide();
            $('#optimization-loading').hide();
            $('#desktop-metrics-loading').hide();
            $('#mobile-metrics-loading').hide();
            $('#mobile-optimization-loading').hide();
            $('.aysa-loading-container').hide();
            $('.aysa-checklist-loading-text').hide();
            $('.aysa-table-loading').hide();
            $('.aysa-loading-item').hide();
        }

        // Function to check if all requests are completed
        function checkAllCompleted() {
            completedRequests++;
            if (completedRequests === pendingRequests) {
                // Clear timeout since all requests completed
                if (loadingTimeout) {
                    clearTimeout(loadingTimeout);
                    loadingTimeout = null;
                }
                // Hide all loading states
                hideAllLoadingStates();
                // Re-enable all buttons (mobile button removed)
                if (desktopButton) desktopButton.prop('disabled', false).text('Run PageSpeed Test');
                // Mobile button removed: if (mobileButton) mobileButton.prop('disabled', false).text('Run Mobile PageSpeed Test');
                if (overviewButton) overviewButton.prop('disabled', false).text('Refresh Overview');
            }
        }

        
        // Function to check if data is older than 7 days
        function isDataStale(dateString) {
            const recordDate = new Date(dateString);
            const currentDate = new Date();
            
            // If record date is in the future, consider it fresh
            if (recordDate > currentDate) {
                return false;
            }
            
            const diffTime = Math.abs(currentDate - recordDate);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            return diffDays > 7;
        }
        
        // Function to convert metrics data to overview format
        function convertMetricsToOverview(metricsRecord) {
            // Calculate performance score from metrics (simplified scoring)
            const metrics = metricsRecord.metrics;
            
            // Basic performance scoring based on key metrics
            let performanceScore = 100;
            
            // Deduct points for poor metrics
            if (metrics.firstContentfulPaint > 1.8) performanceScore -= 15;
            if (metrics.firstContentfulPaint > 3.0) performanceScore -= 20;
            if (metrics.largestContentfulPaint > 2.5) performanceScore -= 20;
            if (metrics.largestContentfulPaint > 4.0) performanceScore -= 25;
            if (metrics.totalBlockingTime > 200) performanceScore -= 15;
            if (metrics.totalBlockingTime > 300) performanceScore -= 25;
            if (metrics.cumulativeLayoutShift > 0.1) performanceScore -= 10;
            
            // Ensure score is between 0-100
            performanceScore = Math.max(0, Math.min(100, performanceScore));
            
            return {
                pageSpeedDesktop: performanceScore,
                pageSpeedMobile: performanceScore, // Use same score for both
                mobileFriendly: 95, // Default high score
                indexability: 90, // Default high score
                requestedAt: metricsRecord.requestedAt,
                convertedFromMetrics: true,
                originalMetrics: metricsRecord // Keep original for reference
            };
        }
        
        // Overview request handling - try GET first, fall back to POST
        if (refreshOverview) {
            pendingRequests++;
            if (overviewButton) overviewButton.prop('disabled', true).text('Refreshing...');
            
            // Use AysaAPI to get the correct endpoint URL (including localhost routing)
            const overviewGetUrl = AysaAPI.getEndpointUrl('pagespeed_overview_get', { projectId: projectId });
            
            // First, try to get existing data
            $.ajax({
                url: overviewGetUrl,
                type: 'GET',
                contentType: 'application/json',
                timeout: 8000, // Reduced timeout for faster loading
                success: function(response) {
                    // Check if we actually received data
                    // Response can be either an array or a single object
                    let dataToProcess = null;
                    
                    if (Array.isArray(response) && response.length > 0) {
                        // Check if this is an array of overview records, metrics, or opportunities
                        const firstItem = response[0];
                        
                        if (firstItem.pageSpeedDesktop !== undefined) {
                            // This is an array of overview records
                            dataToProcess = firstItem;
                        } else if (firstItem.requestedAt && firstItem.metrics && firstItem.opportunities) {
                            // This is an array of metrics records - convert to overview format
                            dataToProcess = convertMetricsToOverview(response[0]);
                        } else if (firstItem.id && firstItem.title) {
                            // This is an array of opportunities, not overview data
                            dataToProcess = null;
                        } else {
                            // Try to use the first item anyway
                            dataToProcess = firstItem;
                        }
                    } else if (response && typeof response === 'object' && response.requestedAt) {
                        // Single object response
                        if (response.metrics && response.opportunities) {
                            // Convert metrics to overview format
                            dataToProcess = convertMetricsToOverview(response);
                        } else {
                            dataToProcess = response;
                        }
                    }
                    
                    if (dataToProcess && (dataToProcess.pageSpeedDesktop !== undefined || dataToProcess.convertedFromMetrics)) {
                        // Use the data we found (must have overview properties)
                        const latestRecord = dataToProcess;
                        const dataAge = isDataStale(latestRecord.requestedAt);
                        
                        if (dataAge) {
                            setTimeout(function() {
                                fetchAndSaveOverviewData();
                            }, 2000);
                        } else {
                            // Data is fresh enough, use it
                            if (latestRecord.convertedFromMetrics) {
                                // Already converted from metrics format
                                overviewData = latestRecord;
                            } else {
                                // Original overview format
                                overviewData = {
                                    pageSpeedDesktop: latestRecord.pageSpeedDesktop,
                                    pageSpeedMobile: latestRecord.pageSpeedMobile,
                                    mobileFriendly: latestRecord.mobileFriendly,
                                    indexability: latestRecord.indexability,
                                    requestedAt: latestRecord.requestedAt
                                };
                            }
                            dataLoaded.overview = true;
                            updateOverviewUI(overviewData);
                            // Hide overview loading state
                            $('#overview-loading').hide();
                            $('#overview-data').show();
                            
                            // Update mobile overview section if we have the data
                            if (overviewData.pageSpeedMobile) {
                                updateMobileOverview(overviewData.pageSpeedMobile);
                            }
                            
                            // If we got data from GET, we're done with overview
                            checkAllCompleted();
                        }
                    } else {
                        // No data found, need to fetch fresh data and save it
                        setTimeout(function() {
                            fetchAndSaveOverviewData();
                        }, 500);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Error fetching stored PageSpeed data:", error, xhr.responseText);
                        // Fetch fresh data immediately
                        fetchAndSaveOverviewData();
                }
            });
            
            // Function to fetch fresh overview data and save it
            function fetchAndSaveOverviewData() {
                // Use AysaAPI to get the correct endpoint URL (including localhost routing)
                const overviewPostUrl = AysaAPI.getEndpointUrl('pagespeed_overview');
                
                $.ajax({
                    url: overviewPostUrl,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ 
                        url: siteUrl,
                        projectId: projectId
                    }),
                    success: function(response) {
                        overviewData = response;
                        overviewData.requestedAt = new Date().toISOString(); // Add current date for future staleness checks
                        dataLoaded.overview = true;
                        updateOverviewUI(response);
                        // Hide overview loading state
                        $('#overview-loading').hide();
                        $('#overview-data').show();
                        
                        // Update mobile overview section if we have the data
                        if (response.pageSpeedMobile) {
                            updateMobileOverview(response.pageSpeedMobile);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Overview Error:", error, xhr.responseText);
                        // Hide loading state on error
                        $('#overview-loading').hide();
                        showPageSpeedNotice('PageSpeed overview endpoint failed. Legacy endpoint is being replaced.', 'error');
                    },
                    complete: checkAllCompleted
                });
            }
        }
        
        // Desktop PageSpeed request
        if (refreshDesktop) {
            pendingRequests++;
            if (desktopButton) desktopButton.prop('disabled', true).text('Running Test...');
            
            // First check if we already have recent data in the overview
            if (dataLoaded.overview && overviewData && !isDataStale(overviewData.requestedAt)) {
                // Hide desktop loading state
                $('#desktop-metrics-loading').hide();
                $('#optimization-loading').hide();
                // We already have fresh overview data which includes desktop scores
                checkAllCompleted();
            } else {
                // Use AysaAPI to get the correct endpoint URL (including localhost routing)
                const desktopMetricsGetUrl = AysaAPI.getEndpointUrl('pagespeed_metrics_get', { projectId: projectId });
                
                // Check if we have existing metrics in the database first
                $.ajax({
                    url: desktopMetricsGetUrl,
                    type: 'GET',
                    contentType: 'application/json',
                    timeout: 8000, // Reduced timeout for faster loading
                    success: function(response) {
                        // Check if we actually received data
                        // Response can be either an array or a single object
                        let dataToProcess = null;
                        
                        if (Array.isArray(response) && response.length > 0) {
                            // Check if this is an array of metrics records or opportunities
                            const firstItem = response[0];
                            if (firstItem.requestedAt && firstItem.metrics && firstItem.opportunities) {
                                // This is an array of metrics records - use all of them for desktop
                                dataToProcess = response;
                            } else if (firstItem.id && firstItem.title) {
                                // This is an array of opportunities, not metrics data
                                dataToProcess = null;
                            } else {
                                // Try to use the response anyway
                                dataToProcess = response;
                            }
                        } else if (response && typeof response === 'object' && response.requestedAt && response.metrics) {
                            // Single object response with metrics data
                            dataToProcess = [response]; // Wrap in array for consistent processing
                        }
                        
                        if (dataToProcess && dataToProcess.length > 0) {
                            // Use the desktop metrics we found
                            const desktopMetrics = dataToProcess;
                            
                            if (desktopMetrics.length > 0) {
                                // Use the most recent record
                                const latestDesktopRecord = desktopMetrics[0];
                                const dataAge = isDataStale(latestDesktopRecord.requestedAt);
                                
                                if (dataAge) {
                                    // Show cached data immediately, then update with fresh data
                                    desktopData = latestDesktopRecord;
                                    dataLoaded.desktop = true;
                                    renderDesktop();
                                    
                                    // Fetch fresh data in background
                                    setTimeout(function() {
                                        fetchDesktopMetrics();
                                    }, 100);
                                } else {
                                    // Data is fresh enough, use it
                                    desktopData = latestDesktopRecord;
                                    dataLoaded.desktop = true;
                                    renderDesktop();
                                    // Hide loading states
                                    $('#desktop-metrics-loading').hide();
                                    $('#optimization-loading').hide();
                                    checkAllCompleted();
                                }
                            } else {
                                fetchDesktopMetrics();
                            }
                        } else {
                            fetchDesktopMetrics();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Error fetching stored desktop metrics:", error, xhr.responseText);
                        // Fetch fresh desktop data immediately
                        fetchDesktopMetrics();
                    }
                });
                
                // Function to fetch fresh desktop metrics and save it
                function fetchDesktopMetrics() {
                    // Use AysaAPI to get the correct endpoint URL (including localhost routing)
                    const desktopMetricsPostUrl = AysaAPI.getEndpointUrl('pagespeed_metrics');
                    
                    $.ajax({
                        url: desktopMetricsPostUrl,
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ 
                            url: siteUrl, 
                            strategy: 'desktop',
                            projectId: projectId
                        }),
                        success: function(response) {
                            desktopData = response;
                            dataLoaded.desktop = true;
                            renderDesktop();
                            // Hide loading states
                            $('#desktop-metrics-loading').hide();
                            $('#optimization-loading').hide();
                        },
                        error: function(xhr, status, error) {
                            console.error("Desktop API Error:", error, xhr.responseText);
                            // Hide loading states on error
                            $('#desktop-metrics-loading').hide();
                            $('#optimization-loading').hide();
                            showPageSpeedNotice('Desktop PageSpeed endpoint failed. Legacy endpoint is being replaced.', 'error');
                        },
                        complete: checkAllCompleted
                    });
                }
            }
        }
        
        // Mobile PageSpeed request
        if (refreshMobile) {
            pendingRequests++;
            // Mobile button removed: if (mobileButton) mobileButton.prop('disabled', true).text('Running Test...');
            
            // First check if we already have recent data in the overview
            if (dataLoaded.overview && overviewData && !isDataStale(overviewData.requestedAt)) {
                // Hide mobile loading state
                $('#mobile-metrics-loading').hide();
                $('#mobile-optimization-loading').hide();
                // We already have fresh overview data which includes mobile scores
                checkAllCompleted();
            } else {
                // Use AysaAPI to get the correct endpoint URL (including localhost routing)
                const mobileMetricsGetUrl = AysaAPI.getEndpointUrl('pagespeed_metrics_get', { projectId: projectId });
                
                // Check if we have existing metrics in the database first
                $.ajax({
                    url: mobileMetricsGetUrl,
                    type: 'GET',
                    contentType: 'application/json',
                    timeout: 8000, // Reduced timeout for faster loading
                    success: function(response) {
                        // Check if we actually received data
                        // Response can be either an array or a single object
                        let dataToProcess = null;
                        
                        if (Array.isArray(response) && response.length > 0) {
                            // Check if this is an array of metrics records or opportunities
                            const firstItem = response[0];
                            if (firstItem.requestedAt && firstItem.metrics && firstItem.opportunities) {
                                // This is an array of metrics records - use all of them for mobile
                                dataToProcess = response;
                            } else if (firstItem.id && firstItem.title) {
                                // This is an array of opportunities, not metrics data
                                dataToProcess = null;
                            } else {
                                // Try to use the response anyway
                                dataToProcess = response;
                            }
                        } else if (response && typeof response === 'object' && response.requestedAt && response.metrics) {
                            // Single object response with metrics data
                            dataToProcess = [response]; // Wrap in array for consistent processing
                        }
                        
                        if (dataToProcess && dataToProcess.length > 0) {
                            // Use the mobile metrics we found
                            const mobileMetrics = dataToProcess;
                            
                            if (mobileMetrics.length > 0) {
                                // Use the most recent record
                                const latestMobileRecord = mobileMetrics[0];
                                const dataAge = isDataStale(latestMobileRecord.requestedAt);
                                
                                if (dataAge) {
                                    // Show cached data immediately, then update with fresh data
                                    mobileData = latestMobileRecord;
                                    dataLoaded.mobile = true;
                                    renderMobile();
                                    
                                    // Fetch fresh data in background
                                    setTimeout(function() {
                                        fetchMobileMetrics();
                                    }, 100);
                                } else {
                                    // Data is fresh enough, use it
                                    mobileData = latestMobileRecord;
                                    dataLoaded.mobile = true;
                                    renderMobile();
                                    // Hide loading states
                                    $('#mobile-metrics-loading').hide();
                                    $('#mobile-optimization-loading').hide();
                                    
                                    // If we have mobile data, update the mobile overview section too
                                    if (mobileData.metrics && mobileData.metrics.performance) {
                                        var performanceScore = mobileData.metrics.performance.score * 100;
                                        updateMobileOverview(performanceScore);
                                    }
                                    
                                    checkAllCompleted();
                                }
                            } else {
                                fetchMobileMetrics();
                            }
                        } else {
                            fetchMobileMetrics();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Error fetching stored mobile metrics:", error, xhr.responseText);
                        // Fetch fresh mobile data immediately
                        fetchMobileMetrics();
                    }
                });
                
                // Function to fetch fresh mobile metrics and save it
                function fetchMobileMetrics() {
                    // Use AysaAPI to get the correct endpoint URL (including localhost routing)
                    const mobileMetricsPostUrl = AysaAPI.getEndpointUrl('pagespeed_metrics');
                    
                    $.ajax({
                        url: mobileMetricsPostUrl,
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ 
                            url: siteUrl, 
                            strategy: 'mobile',
                            projectId: projectId
                        }),
                        success: function(response) {
                            mobileData = response;
                            dataLoaded.mobile = true;
                            renderMobile();
                            // Hide loading states
                            $('#mobile-metrics-loading').hide();
                            $('#mobile-optimization-loading').hide();
                            
                            // If we have mobile data, update the mobile overview section too
                            if (response.metrics && response.metrics.performance) {
                                var performanceScore = response.metrics.performance.score * 100;
                                updateMobileOverview(performanceScore);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("Mobile API Error:", error, xhr.responseText);
                            // Hide loading states on error
                            $('#mobile-metrics-loading').hide();
                            $('#mobile-optimization-loading').hide();
                            showPageSpeedNotice('Mobile PageSpeed endpoint failed. Legacy endpoint is being replaced.', 'error');
                        },
                        complete: checkAllCompleted
                    });
                }
            }
        }
        
        // Set timeout fallback: hide loading states after 30 seconds if requests don't complete
        if (pendingRequests > 0) {
            loadingTimeout = setTimeout(function() {
                if (completedRequests < pendingRequests) {
                    console.warn('⚠️ Timeout reached! Some requests did not complete. Hiding loading states...');
                    hideAllLoadingStates();
                    // Force complete all pending requests
                    completedRequests = pendingRequests;
                }
            }, 30000);
        }

        // If no requests were made, ensure buttons are re-enabled and loading states are hidden (mobile button removed)
        if (pendingRequests === 0) {
            hideAllLoadingStates();
            if (desktopButton) desktopButton.prop('disabled', false).text('Run PageSpeed Test');
            // Mobile button removed: if (mobileButton) mobileButton.prop('disabled', false).text('Run Mobile PageSpeed Test');
            if (overviewButton) overviewButton.prop('disabled', false).text('Refresh Overview');
        }
        
        return new Promise(resolve => {
            const checkInterval = setInterval(() => {
                if (completedRequests === pendingRequests) {
                    clearInterval(checkInterval);
                    resolve();
                }
            }, 100);
        });
    }

    function renderDesktop() {
        if (!desktopData) {
            console.error("Desktop data is undefined or null");
            return;
        }
        
        // Cache the data in localStorage for immediate display on next load
        localStorage.setItem('aysa_cached_desktop', JSON.stringify(desktopData));
        
        // Metrics table
        if (desktopData.metrics) {
            var metricsRows = renderMetricsTable(desktopData.metrics);
            $('.aysa-pagespeed-desktop .aysa-metrics-table tbody').html(metricsRows);
        }
        
        // Hide loading and show data
        $('#desktop-metrics-loading').hide();
        
        // Opportunities checklist
        if (desktopData.opportunities && Array.isArray(desktopData.opportunities)) {
            var totalByteWeight = (desktopData.metrics && desktopData.metrics.totalByteWeight) 
                                ? desktopData.metrics.totalByteWeight 
                                : null;
            var oppHtml = renderOpportunities(desktopData.opportunities, totalByteWeight);
            $('#speed-content .aysa-checklist').html(oppHtml);
        }
    }
    
    function renderMobile() {
        if (!mobileData) {
            console.error("Mobile data is undefined or null");
            return;
        }
        
        // Cache the data in localStorage for immediate display on next load
        localStorage.setItem('aysa_cached_mobile', JSON.stringify(mobileData));
        
        // Create mobile metrics table if it doesn't exist
        if ($('#aysa-mobile-metrics-table').length === 0) {
            var metricsTable = '<div class="aysa-panel"><h2 class="aysa-section-title">Mobile PageSpeed Metrics</h2>' +
                '<table class="aysa-metrics-table" id="aysa-mobile-metrics-table"><thead><tr><th>Metric</th><th>Value</th><th>Status</th></tr></thead><tbody></tbody></table></div>';
            $('#mobile-content .aysa-panel').first().after(metricsTable);
        }
        
        // Populate mobile metrics
        if (mobileData.metrics) {
            var metricsRows = renderMetricsTable(mobileData.metrics);
            $('#aysa-mobile-metrics-table tbody').html(metricsRows);
        }
        
        // Hide loading and show data
        $('#mobile-metrics-loading').hide();
        
        // Create mobile opportunities if it doesn't exist
        if ($('#aysa-mobile-opportunities').length === 0) {
            var oppBox = '<div class="aysa-panel"><h2 class="aysa-section-title">Mobile Optimization Opportunities</h2>' +
                '<div class="aysa-checklist" id="aysa-mobile-opportunities"></div></div>';
            $('#mobile-content .aysa-panel').last().after(oppBox);
        }
        
        // Populate mobile opportunities
        if (mobileData.opportunities && Array.isArray(mobileData.opportunities)) {
            var totalByteWeight = (mobileData.metrics && mobileData.metrics.totalByteWeight) 
                                ? mobileData.metrics.totalByteWeight 
                                : null;
            var oppHtml = renderOpportunities(mobileData.opportunities, totalByteWeight);
            $('#aysa-mobile-opportunities').html(oppHtml);
        }
    }

    // Function to show cached data immediately if available
    function showCachedDataImmediately() {
        // Check localStorage for cached data
        const cachedOverview = localStorage.getItem('aysa_cached_overview');
        const cachedDesktop = localStorage.getItem('aysa_cached_desktop');
        const cachedMobile = localStorage.getItem('aysa_cached_mobile');
        
        if (cachedOverview) {
            try {
                const overviewData = JSON.parse(cachedOverview);
                updateOverviewUI(overviewData);
                $('#overview-loading').hide();
                $('#overview-data').show();
            } catch (e) {
                // Ignore malformed cached overview payloads.
            }
        }
        
        if (cachedDesktop) {
            try {
                const parsedDesktopData = JSON.parse(cachedDesktop);
                // Assign to global desktopData variable
                desktopData = parsedDesktopData;
                renderDesktop();
                $('#desktop-metrics-loading').hide();
            } catch (e) {
                // Ignore malformed cached desktop payloads.
            }
        }
        
        if (cachedMobile) {
            try {
                const parsedMobileData = JSON.parse(cachedMobile);
                // Assign to global mobileData variable
                mobileData = parsedMobileData;
                renderMobile();
                $('#mobile-metrics-loading').hide();
            } catch (e) {
                // Ignore malformed cached mobile payloads.
            }
        }
    }
    
    // IMMEDIATE: Hide all loading states as soon as possible
    $(document).ready(function() {
        // Hide all loading states immediately
        $('#overview-loading').hide();
        $('#optimization-loading').hide();
        $('#desktop-metrics-loading').hide();
        $('#mobile-metrics-loading').hide();
        $('#mobile-optimization-loading').hide();
        
        // Also hide any other loading elements that might exist
        $('.aysa-loading-container').hide();
        $('.aysa-checklist-loading-text').hide();
        $('.aysa-table-loading').hide();
        $('.aysa-loading-item').hide();
        
        // Show cached data immediately if available
        showCachedDataImmediately();
        
        if (isPageSpeedLegacyDisabled) {
            console.warn('Skipping automatic PageSpeed loading in local mode.');
            showPageSpeedNotice('PageSpeed module is in migration to broker/local API. For now, use Site Audit.', 'info');
        } else {
            showPageSpeedNotice('PageSpeed loads only when you open the relevant tab or request a refresh.', 'info');
        }
        
        // Load data when tabs are clicked for the first time
        $('.aysa-tab-btn').on('click', function() {
            var target = $(this).data('target');
            
            if (target === 'speed' && !dataLoaded.desktop) {
                loadAllPageSpeedData({ refreshDesktop: true, refreshMobile: false, refreshOverview: false });
            } else if (target === 'mobile' && !dataLoaded.mobile) {
                loadAllPageSpeedData({ refreshDesktop: false, refreshMobile: true, refreshOverview: false });
            }
        });
    });

    // Run PageSpeed Test button - removed as the button was removed
    /*
    $('#aysa-run-pagespeed').on('click', function() {
        var button = $(this);
        loadAllPageSpeedData({ 
            refreshDesktop: true, 
            refreshMobile: false, 
            refreshOverview: false,
            desktopButton: button
        });
    });
    */
    
    // Run Mobile PageSpeed Test button - removed as the button was removed
    /*
    $('#aysa-run-mobile-pagespeed').on('click', function() {
        var button = $(this);
        loadAllPageSpeedData({ 
            refreshDesktop: false, 
            refreshMobile: true, 
            refreshOverview: false,
            mobileButton: button
        });
    });
    */
    
    // Refresh Overview button - only refreshes overview data
    $('#aysa-refresh-overview').on('click', function() {
        if (isPageSpeedLegacyDisabled) {
            showPageSpeedNotice('Refresh Overview is temporarily disabled in local mode until PageSpeed is moved to broker endpoint.', 'info');
            return;
        }
        var button = $(this);
        loadAllPageSpeedData({ 
            refreshDesktop: false, 
            refreshMobile: false, 
            refreshOverview: true,
            overviewButton: button
        });
    });

    $('#aysa-download-pagespeed-pdf').on('click', function(event) {
        if (event && typeof event.preventDefault === 'function') {
            event.preventDefault();
        }
        if (typeof window.aysaRequestPageSpeedDetailedReport === 'function') {
            window.aysaRequestPageSpeedDetailedReport(this);
        }
    });
    
    // Function to update the UI with the overview data
    function updateOverviewUI(data) {
        // Cache the data in localStorage for immediate display on next load
        localStorage.setItem('aysa_cached_overview', JSON.stringify(data));
        
        // Calculate the overall score (average of the 4 values)
        var overallScore = Math.round((data.pageSpeedDesktop + data.pageSpeedMobile + 
                                       data.mobileFriendly + data.indexability) / 4);
        
        // If it's the first load, clone the template and replace the loader
        if ($('#overview-content .aysa-performance-score').length === 0) {
            var template = $('.aysa-overview-template').html();
            $('#overview-content').html(template);
        }
        
        // Update the overall score
        $('.aysa-performance-score .aysa-percentage').text(overallScore + '%');
        $('.aysa-performance-score .aysa-circle').attr('stroke-dasharray', overallScore + ', 100');
        
        // Update individual values and set color classes based on values
        updateMetricCard(0, data.pageSpeedDesktop, getScoreClass(data.pageSpeedDesktop));  // Page Speed (Desktop)
        updateMetricCard(1, data.pageSpeedMobile, getScoreClass(data.pageSpeedMobile));    // Page Speed (Mobile)
        updateMetricCard(2, data.mobileFriendly, getScoreClass(data.mobileFriendly));      // Mobile-Friendly
        updateMetricCard(3, data.indexability, getScoreClass(data.indexability));          // Indexability
        
        // Set color class for the overall score
        var chartClass = getScoreClass(overallScore);
        $('.aysa-circular-chart').removeClass('red orange green blue').addClass(chartClass);
        
        // Update mobile overview section with the PageSpeed Mobile score
        updateMobileOverview(data.pageSpeedMobile);
        
        // Hide loading and show data
        $('#overview-loading').hide();
        $('#overview-data').show();
    }
    
    // Helper function to get color class based on score
    function getScoreClass(score) {
        if (score < 50) return 'red';
        if (score < 70) return 'orange';
        if (score < 90) return 'green';
        return 'blue';
    }
    
    // Helper function to update an individual metric card
    function updateMetricCard(index, value, colorClass) {
        var cards = $('.aysa-metric-card');
        if (index < cards.length) {
            var card = $(cards[index]);
            
            // Update the value
            card.find('.aysa-metric-value').html(
                Math.round(value) + '<span class="aysa-metric-unit">/100</span>'
            );
            
            // Update the icon color
            var icon = card.find('.aysa-metric-icon');
            icon.removeClass('aysa-red aysa-orange aysa-green aysa-blue');
            icon.addClass('aysa-' + colorClass);
            
            // Trend indicator - for simplicity, you could add logic here to compare with previous values
        }
    }
    
    // Function to update the Mobile Optimization Overview section
    function updateMobileOverview(mobileScore) {
        var roundedScore = Math.round(mobileScore);
        var colorClass = getScoreClass(roundedScore);
        
        // Update the score and dasharray of the circle
        $('#mobile-content .aysa-mobile-score .aysa-percentage').text(roundedScore + '%');
        $('#mobile-content .aysa-mobile-score .aysa-circle').attr('stroke-dasharray', roundedScore + ', 100');
        
        // Update the color class of the circle
        $('#mobile-content .aysa-mobile-score .aysa-circular-chart')
            .removeClass('red orange green blue')
            .addClass(colorClass);
        
        // Update the warning text based on score
        var warningTitle = 'Mobile Optimization ';
        var warningText = '';
        
        if (roundedScore < 50) {
            warningTitle += 'Needs Significant Improvement';
            warningText = 'Your website requires urgent optimization for mobile devices. Address the critical issues below to improve mobile experience and rankings.';
        } else if (roundedScore < 70) {
            warningTitle += 'Needs Improvement';
            warningText = 'Your website requires optimization for mobile devices. Address the issues below to improve mobile experience and rankings.';
        } else if (roundedScore < 90) {
            warningTitle += 'is Good';
            warningText = 'Your website performs well on mobile devices, but there is still room for improvement.';
        } else {
            warningTitle += 'is Excellent';
            warningText = 'Your website is highly optimized for mobile devices. Keep up the good work!';
        }
        
        // Update the warning message
        $('#mobile-content .aysa-info-box strong').text(warningTitle);
        $('#mobile-content .aysa-info-box p:not(:has(strong))').text(warningText);
        
        // Update the class of the info box
        $('#mobile-content .aysa-info-box')
            .removeClass('warning success')
            .addClass(roundedScore >= 70 ? 'success' : 'warning');
        
        // Update the icon in the info box
        var iconClass = roundedScore >= 70 ? 'dashicons-yes-alt' : 'dashicons-warning';
        $('#mobile-content .aysa-info-icon .dashicons')
            .removeClass('dashicons-warning dashicons-yes-alt')
            .addClass(iconClass);
    }

    function renderPageSpeedConclusion(conclusion) {
        var box = $('#aysa-pagespeed-conclusion');
        if (!box.length) {
            return;
        }
        pageSpeedConclusionData = conclusion && typeof conclusion === 'object' ? conclusion : null;
        if (!conclusion || typeof conclusion !== 'object') {
            box.attr('class', 'aysa-site-audit-message info').html('No conclusion data available yet.');
            return;
        }
        var status = String(conclusion.status || 'good').toLowerCase();
        var cls = 'info';
        if (status === 'critical' || status === 'needs_improvement') {
            cls = 'warning';
        } else if (status === 'excellent' || status === 'good') {
            cls = 'success';
        }
        var actions = Array.isArray(conclusion.priority_actions) ? conclusion.priority_actions : [];
        var actionsHtml = '';
        if (actions.length) {
            actionsHtml = '<ul style="margin:8px 0 0 18px;">';
            actions.slice(0, 5).forEach(function(action) {
                actionsHtml += '<li><strong>' + String(action.title || 'Action') + '</strong>' +
                    (action.displayValue ? ' - ' + String(action.displayValue) : '') + '</li>';
            });
            actionsHtml += '</ul>';
        }
        var warningHtml = '';
        if (conclusion.warning) {
            warningHtml = '<div style="margin-top:8px;color:#8a1f11;"><strong>Diagnostic:</strong> ' + String(conclusion.warning) + '</div>';
        }
        box.attr('class', 'aysa-site-audit-message ' + cls).html(
            '<strong>Overall: ' + String((conclusion.overall_score === 0 || conclusion.overall_score) ? conclusion.overall_score : '-') + '/100</strong><br>' +
            String(conclusion.summary || 'No summary available.') +
            actionsHtml +
            warningHtml
        );
    }

    // Override legacy PageSpeed loader with broker/local endpoint.
    function loadAllPageSpeedData(options = {}) {
        // Important: default tab loads must NOT force refresh (and must NOT spend credits).
        // Refresh is only enabled by explicit UI actions that pass refresh flags.
        const refreshOverview = !!options.refreshOverview;
        const shouldRefresh = refreshOverview || !!options.refreshDesktop || !!options.refreshMobile;
        const desktopButton = options.desktopButton || null;
        const overviewButton = options.overviewButton || null;

        const projectId = getProjectId();
        if (!projectId) {
            showPageSpeedNotice('Project ID not found.', 'error');
            return Promise.resolve();
        }

        $('#overview-loading').show();
        $('#desktop-metrics-loading').show();
        $('#optimization-loading').show();
        if (overviewButton) {
            overviewButton.prop('disabled', true).text('Refreshing...');
        }
        if (desktopButton) {
            desktopButton.prop('disabled', true).text('Loading...');
        }

        return new Promise(function(resolve) {
            jQuery.ajax({
                url: (window.aysa_params && window.aysa_params.ajax_url) ? window.aysa_params.ajax_url : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'aysa_technical_pagespeed_summary',
                    nonce: '<?php echo esc_attr(wp_create_nonce('aysa_internal_linking_nonce')); ?>',
                    project_id: projectId,
                    target_url: siteUrl,
                    refresh: shouldRefresh ? 1 : 0
                },
                success: function(resp) {
                    if (!resp || !resp.success || !resp.data || !resp.data.data || resp.data.data.ok !== true) {
                        var failMessage = 'Google Page Speed request failed.';
                        if (resp && resp.data && typeof resp.data === 'string') {
                            failMessage = resp.data;
                        } else if (resp && resp.data && resp.data.message) {
                            failMessage = resp.data.message;
                        }
                        showPageSpeedNotice(failMessage, 'error');
                        resolve();
                        return;
                    }
                    var payload = resp.data.data;
                    overviewData = payload.overview || null;
                    desktopData = payload.desktop || null;
                    mobileData = payload.mobile || null;

                    if (overviewData) {
                        updateOverviewUI(overviewData);
                    }
                    if (desktopData) {
                        renderDesktop();
                        dataLoaded.desktop = true;
                    }
                    if (mobileData) {
                        renderMobile();
                        dataLoaded.mobile = true;
                    }
                    var conclusionPayload = payload.conclusion || {};
                    if (payload.warning) {
                        conclusionPayload.warning = payload.warning;
                    }
                    renderPageSpeedConclusion(conclusionPayload);
                    if (payload.warning) {
                        showPageSpeedNotice(String(payload.warning), 'error');
                    } else {
                        showPageSpeedNotice(resp.data.cached ? 'Loaded from local cache.' : 'Fresh Google Page Speed data loaded.', 'success');
                    }
                },
                error: function(xhr) {
                    var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data) ? xhr.responseJSON.data : 'Google Page Speed endpoint error.';
                    showPageSpeedNotice(msg, 'error');
                },
                complete: function() {
                    $('#overview-loading').hide();
                    $('#desktop-metrics-loading').hide();
                    $('#optimization-loading').hide();
                    if (overviewButton) {
                        overviewButton.prop('disabled', false).text('Refresh Overview');
                    }
                    if (desktopButton) {
                        desktopButton.prop('disabled', false).text('Run PageSpeed Test');
                    }
                    resolve();
                }
            });
        });
    }

    // ... existing code ...
});
</script> 

<!-- Modal Dialog Templates -->
<div id="aysa-modal-container" style="display:none;" class="aysa-modal-overlay">
    <div class="aysa-modal aysa-modal-short">
        <div class="aysa-modal-header">
            <h3 id="aysa-modal-title">Title</h3>
            <button class="aysa-modal-close">&times;</button>
        </div>
        <div class="aysa-modal-body" id="aysa-modal-content">
            Content goes here
        </div>
        <div class="aysa-modal-footer">
            <button class="aysa-btn aysa-btn-secondary aysa-modal-cancel">Cancel</button>
            <button class="aysa-btn aysa-btn-primary aysa-modal-confirm">OK</button>
        </div>
    </div>
</div>

<!-- Redirect Modal -->
<div id="aysa-redirect-modal" style="display:none;" class="aysa-modal-overlay">
    <div class="aysa-modal aysa-modal-short">
        <div class="aysa-modal-header">
            <h3 id="aysa-redirect-modal-title">Create Redirect</h3>
            <button class="aysa-modal-close">&times;</button>
        </div>
        <div class="aysa-modal-body">
            <p>Enter the destination URL for the redirect:</p>
            <div class="aysa-form-group">
                <label>Source URL:</label>
                <div id="aysa-redirect-source-url" class="aysa-form-static"></div>
            </div>
            <div class="aysa-form-group">
                <label><input type="checkbox" id="aysa-redirect-manual-checkbox"> Manually enter the URL</label>
            </div>
            <div id="aysa-redirect-suggestion-area">
                <div class="aysa-form-group">
                    <label for="aysa-redirect-type">Destination type:</label>
                    <select id="aysa-redirect-type" class="aysa-form-control">
                        <option value="">Choose type...</option>
                        <option value="post">Article</option>
                        <option value="page">Page</option>
                        <option value="product">Product</option>
                        <option value="category">Category</option>
                    </select>
                </div>
                <div class="aysa-form-group" id="aysa-redirect-suggestion-group" style="display:none;">
                    <label for="aysa-redirect-suggestion">Select destination:</label>
                    <select id="aysa-redirect-suggestion" class="aysa-form-control">
                        <option value="">Choose...</option>
                    </select>
                </div>
            </div>
            <div class="aysa-form-group" id="aysa-redirect-manual-group" style="display:none;">
                <label for="aysa-redirect-target-url">Manually enter URL:</label>
                <input type="text" id="aysa-redirect-target-url" class="aysa-form-control" placeholder="e.g. /noua-pagina">
            </div>
        </div>
        <div class="aysa-modal-footer">
            <button class="aysa-btn aysa-btn-secondary" id="aysa-redirect-cancel">Cancel</button>
            <button class="aysa-btn aysa-btn-primary" id="aysa-redirect-confirm">Create Redirect</button>
        </div>
    </div>
</div>

<!-- Mark Gone Modal -->
<div id="aysa-gone-modal" style="display:none;" class="aysa-modal-overlay">
    <div class="aysa-modal aysa-modal-short">
        <div class="aysa-modal-header">
            <h3 id="aysa-gone-modal-title">Mark URL as Gone (410)</h3>
            <button class="aysa-modal-close">&times;</button>
        </div>
        <div class="aysa-modal-body">
            <p>Are you sure you want to mark this URL as Gone (410)?</p>
            <div class="aysa-form-group">
                <label>URL:</label>
                <div id="aysa-gone-source-url" class="aysa-form-static"></div>
            </div>
            <div class="aysa-form-group">
                <label for="aysa-gone-reason">Reason:</label>
                <input type="text" id="aysa-gone-reason" class="aysa-form-control" placeholder="Reason for marking as Gone">
            </div>
        </div>
        <div class="aysa-modal-footer">
            <button class="aysa-btn aysa-btn-secondary" id="aysa-gone-cancel">Cancel</button>
            <button class="aysa-btn aysa-btn-primary" id="aysa-gone-confirm">Mark as Gone</button>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div id="aysa-success-modal" style="display:none;" class="aysa-modal-overlay">
    <div class="aysa-modal aysa-modal-short">
        <div class="aysa-modal-header">
            <h3>Success</h3>
            <button class="aysa-modal-close">&times;</button>
        </div>
        <div class="aysa-modal-body">
            <p id="aysa-success-message">Operation completed successfully.</p>
        </div>
        <div class="aysa-modal-footer">
            <button class="aysa-btn aysa-btn-primary aysa-success-ok">OK</button>
        </div>
    </div>
</div>

<!-- Error Modal -->
<div id="aysa-error-modal" style="display:none;" class="aysa-modal-overlay">
    <div class="aysa-modal aysa-modal-short">
        <div class="aysa-modal-header">
            <h3>Error</h3>
            <button class="aysa-modal-close">&times;</button>
        </div>
        <div class="aysa-modal-body">
            <p id="aysa-error-message">An error occurred.</p>
        </div>
        <div class="aysa-modal-footer">
            <button class="aysa-btn aysa-btn-primary aysa-error-ok">OK</button>
        </div>
    </div>
</div>

<script type="text/javascript">
    // Configure API for Internal Linking
    <?php
        $aysa_base_url = class_exists('Aysa_API_Config')
            ? rtrim((string) Aysa_API_Config::get_api_base_url(), '/')
            : 'https://api.aysa.ai';
        $aysa_internal_linking_api_base = $aysa_base_url . '/api/aysa-plugin/internal-linking';
    ?>
    window.aysaInternalLinking = {
        apiBaseUrl: '<?php echo esc_js($aysa_internal_linking_api_base); ?>',
        wpUserId: <?php echo absint(get_current_user_id()); ?>,
        projectId: (function() {
            try {
                var candidates = [
                    typeof aysaParams !== 'undefined' ? aysaParams.canonical_project_id : 0,
                    typeof aysaParams !== 'undefined' ? aysaParams.project_id : 0,
                    typeof aysaParams !== 'undefined' ? aysaParams.wp_project_id : 0
                ];
                for (var i = 0; i < candidates.length; i++) {
                    var parsed = parseInt(candidates[i], 10);
                    if (!isNaN(parsed) && parsed > 0) {
                        return parsed;
                    }
                }
            } catch (e) {}
            return null;
        })(),
        ajaxUrl: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
        nonce: '<?php echo esc_attr(wp_create_nonce('aysa_internal_linking_nonce')); ?>'
    };

    document.addEventListener('DOMContentLoaded', function() {
        if (window.AYSA_DEBUG === true) {
            console.log('🔧 Internal Linking API configured:', window.aysaInternalLinking);
        }

        // Enforce agreed preset values in Rules & Scope inputs.
        function enforceInternalLinkingPresetInputs() {
            var keywordInput = document.getElementById('aysa-max-links-per-keyword');
            var entityInput = document.getElementById('aysa-max-links-per-entity');
            if (keywordInput) {
                keywordInput.value = '1';
                keywordInput.setAttribute('readonly', 'readonly');
            }
            if (entityInput) {
                entityInput.value = '3';
                entityInput.setAttribute('readonly', 'readonly');
            }
        }
        enforceInternalLinkingPresetInputs();
        jQuery(document).on('click', '.aysa-tab-btn[data-target="internal-linking"]', function() {
            setTimeout(enforceInternalLinkingPresetInputs, 20);
        });
        
        // Prevent clicks on disabled tabs
        const disabledTabs = document.querySelectorAll('.aysa-tab-btn.disabled');
        disabledTabs.forEach(function(tab) {
            tab.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
        });
    });
</script>

<style>
/* Disabled Tab Styles */
.aysa-tab-btn.disabled {
    color: #ccc !important;
    background-color: #f5f5f5 !important;
    border-color: #e0e0e0 !important;
    cursor: not-allowed !important;
    opacity: 0.6;
    position: relative;
}

.aysa-tab-btn.disabled:hover {
    color: #ccc !important;
    background-color: #f5f5f5 !important;
    transform: none !important;
    box-shadow: none !important;
}

.aysa-tab-btn.disabled:active,
.aysa-tab-btn.disabled:focus {
    color: #ccc !important;
    background-color: #f5f5f5 !important;
    outline: none !important;
}

/* Tooltip for disabled tabs */
.aysa-tab-btn.disabled[title]:hover::after {
    content: attr(title);
    position: absolute;
    bottom: -40px;
    left: 50%;
    transform: translateX(-50%);
    background-color: #333;
    color: white;
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 1000;
    opacity: 0.9;
}

.aysa-tab-btn.disabled[title]:hover::before {
    content: "";
    position: absolute;
    bottom: -30px;
    left: 50%;
    transform: translateX(-50%);
    border: 5px solid transparent;
    border-bottom-color: #333;
    z-index: 999;
}

/* Internal Linking Settings Styles */
.aysa-internal-linking-settings {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.aysa-settings-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.aysa-settings-header h3 {
    margin: 0;
    color: #2271b1;
    font-size: 18px;
}

.aysa-master-toggle {
    display: flex;
    align-items: center;
    gap: 10px;
}

.aysa-switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

.aysa-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.aysa-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 34px;
}

.aysa-slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

input:checked + .aysa-slider {
    background-color: #2271b1;
}

input:checked + .aysa-slider:before {
    transform: translateX(26px);
}

.aysa-settings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.aysa-setting-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.aysa-setting-group label {
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
}

.aysa-setting-group input,
.aysa-setting-group select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.aysa-checkbox-group label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: normal;
    margin-bottom: 0;
}

.aysa-checkbox-group input[type="checkbox"] {
    appearance: none;
    -webkit-appearance: none;
    width: 18px;
    height: 18px;
    border: 2px solid #2271b1;
    border-radius: 3px;
    background: white;
    margin: 0;
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;
}

.aysa-checkbox-group input[type="checkbox"]:checked {
    background: #2271b1;
    border-color: #2271b1;
}

.aysa-checkbox-group input[type="checkbox"]:checked::after {
    content: '✓';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-size: 12px;
    font-weight: bold;
}

/* Advanced Settings Checkboxes */
.aysa-advanced-settings input[type="checkbox"] {
    appearance: none;
    -webkit-appearance: none;
    width: 18px;
    height: 18px;
    border: 2px solid #2271b1;
    border-radius: 3px;
    background: white;
    margin: 0 8px 0 0;
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;
    vertical-align: middle;
}

.aysa-advanced-settings input[type="checkbox"]:checked {
    background: #2271b1;
    border-color: #2271b1;
}

.aysa-advanced-settings input[type="checkbox"]:checked::after {
    content: '✓';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.aysa-advanced-settings label {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-weight: normal;
}

.aysa-advanced-settings {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 20px;
}

.aysa-advanced-settings h4 {
    margin: 0 0 15px 0;
    color: #2271b1;
    font-size: 16px;
}

.aysa-settings-actions {
    display: flex;
    gap: 10px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}

/* Internal Linking UX Redesign */
.aysa-il-shell {
    background: linear-gradient(180deg, #f9fbff 0%, #ffffff 26%);
    border: 1px solid #e4e9f2;
    border-radius: 12px;
    padding: 18px;
}

.aysa-il-hero {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
    margin-bottom: 16px;
    padding: 12px 14px;
    background: #eef4ff;
    border: 1px solid #d7e3fb;
    border-radius: 10px;
}

.aysa-il-hero-copy .aysa-section-title {
    margin: 0 0 6px;
}

.aysa-il-subtitle {
    margin: 0;
    color: #4a5973;
    font-size: 13px;
}

.aysa-il-hero-status {
    min-width: 180px;
    text-align: right;
}

.aysa-il-subtabs {
    display: flex;
    gap: 10px;
    margin: 0 0 14px;
}

.aysa-il-subtab-btn {
    border: 1px solid #d6e1f5;
    background: #f4f8ff;
    color: #39567f;
    padding: 8px 14px;
    border-radius: 999px;
    font-weight: 600;
    cursor: pointer;
}

.aysa-il-subtab-btn.active {
    background: #2271b1;
    border-color: #2271b1;
    color: #fff;
}

.aysa-il-subtab-panel {
    display: none;
}

.aysa-il-subtab-panel.active {
    display: block;
}

.aysa-il-subtab-panels .aysa-il-settings-card,
.aysa-il-subtab-panels .aysa-il-reports-card {
    width: 100%;
    max-width: 100%;
}

.aysa-il-status-label {
    display: block;
    font-size: 11px;
    color: #5f6f8b;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    margin-bottom: 6px;
}

.aysa-il-grid {
    display: grid;
    grid-template-columns: minmax(320px, 1fr) minmax(460px, 1.6fr);
    gap: 16px;
    align-items: start;
}

.aysa-il-settings-card,
.aysa-il-reports-card {
    border: 1px solid #e4e9f2;
    box-shadow: 0 1px 3px rgba(13, 33, 60, 0.06);
}

.aysa-il-reports-card {
    min-height: 100%;
}

.aysa-il-ops-header h3 {
    margin: 0 0 6px;
}

.aysa-il-ops-header p {
    margin: 0 0 14px;
    color: #5f6f8b;
    font-size: 13px;
}

.aysa-il-actions {
    border: 1px solid #e6ecf5;
    background: #fafcff;
    border-radius: 10px;
    padding: 12px;
    margin-bottom: 14px;
}

.aysa-il-stats .aysa-stat-card {
    background: #fff;
    border: 1px solid #e8edf6;
}

.aysa-il-chip {
    display: inline-block;
    margin-top: 8px;
    padding: 5px 8px;
    background: #edf4ff;
    color: #2d5baf;
    border-radius: 999px;
    font-size: 11px;
    line-height: 1;
}

.aysa-il-table-wrap {
    border: 1px solid #e6ecf5;
    border-radius: 10px;
    padding: 12px;
    background: #fff;
    overflow-x: auto;
}

.aysa-il-table-wrap .aysa-table {
    width: 100%;
    min-width: 1100px;
    table-layout: fixed;
}

.aysa-il-table-wrap .aysa-table th:nth-child(1),
.aysa-il-table-wrap .aysa-table td:nth-child(1) {
    width: 14%;
}

.aysa-il-table-wrap .aysa-table th:nth-child(2),
.aysa-il-table-wrap .aysa-table td:nth-child(2) {
    width: 22%;
}

.aysa-il-table-wrap .aysa-table th:nth-child(3),
.aysa-il-table-wrap .aysa-table td:nth-child(3) {
    width: 34%;
}

.aysa-il-table-wrap .aysa-table th:nth-child(4),
.aysa-il-table-wrap .aysa-table td:nth-child(4) {
    width: 9%;
}

.aysa-il-table-wrap .aysa-table th:nth-child(5),
.aysa-il-table-wrap .aysa-table td:nth-child(5) {
    width: 11%;
}

.aysa-il-table-wrap .aysa-table th:nth-child(6),
.aysa-il-table-wrap .aysa-table td:nth-child(6) {
    width: 10%;
}

.aysa-source-links {
    max-height: 180px;
    overflow-y: auto;
}

.aysa-il-table-wrap h4 {
    margin: 0 0 10px;
}

.aysa-setting-group small {
    color: #68788f;
    font-size: 11px;
}

.aysa-setting-group-wide {
    grid-column: 1 / -1;
}

.aysa-setting-group textarea {
    width: 100%;
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    font-size: 12px;
    border: 1px solid #d8e0ee;
    border-radius: 6px;
    padding: 10px;
    box-sizing: border-box;
}

.aysa-il-rule-summary {
    margin: 14px 0 0;
    padding: 12px 14px;
    border: 1px solid #d7e6d7;
    border-radius: 8px;
    background: #f3fbf3;
}

.aysa-il-rule-summary h4 {
    margin: 0 0 8px;
    color: #1e5d2f;
    font-size: 13px;
}

.aysa-il-rule-summary ul {
    margin: 0;
    padding-left: 18px;
}

.aysa-il-rule-summary li {
    margin: 4px 0;
    color: #25433a;
    font-size: 12px;
    line-height: 1.35;
}

@media (max-width: 1200px) {
    .aysa-il-grid {
        grid-template-columns: 1fr;
    }
    .aysa-il-hero {
        flex-direction: column;
    }
    .aysa-il-hero-status {
        text-align: left;
    }
}

/* Enhanced button styles - ensure full clickable area */
.aysa-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    transition: all 0.3s ease;
    display: inline-block;
    text-align: center;
    text-decoration: none;
    min-height: 38px;
    line-height: 1.4;
    box-sizing: border-box;
    position: relative;
    z-index: 1;
}

.aysa-btn:focus {
    outline: 2px solid #2271b1;
    outline-offset: 2px;
}

.aysa-btn-primary {
    background: #2271b1;
    color: white;
}

.aysa-btn-primary:hover {
    background: #135e96;
    color: white;
}

.aysa-btn-secondary {
    background: #f1f1f1;
    color: #333;
    border: 1px solid #ddd;
}

.aysa-btn-secondary:hover {
    background: #e1e1e1;
    color: #333;
}

/* Preview Modal Styles */
.aysa-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-modal-content {
    background: white;
    border-radius: 8px;
    width: 90%;
    max-width: 1000px;
    max-height: 90vh;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
}

.aysa-modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e1e5e9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8f9fa;
}

.aysa-modal-header h3 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.3em;
}

.aysa-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.aysa-modal-close:hover {
    background: #e9ecef;
    color: #333;
}

.aysa-modal-body {
    padding: 24px;
    overflow-y: auto;
    flex: 1;
}

.aysa-modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #e1e5e9;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: #f8f9fa;
}

.aysa-preview-summary {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 24px;
    border: 1px solid #e9ecef;
}

.aysa-preview-summary h4 {
    margin: 0 0 16px 0;
    color: #2c3e50;
    font-size: 1.1em;
}

.aysa-preview-stats {
    display: flex;
    gap: 24px;
    flex-wrap: wrap;
}

.aysa-preview-stats .aysa-stat {
    background: white;
    padding: 12px 16px;
    border-radius: 6px;
    border: 1px solid #e1e5e9;
    font-size: 14px;
    color: #495057;
}

.aysa-preview-stats .aysa-stat strong {
    color: #2271b1;
    font-size: 1.2em;
}

.aysa-preview-details h4 {
    margin: 0 0 16px 0;
    color: #2c3e50;
    font-size: 1.1em;
}

.aysa-preview-change-item {
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 12px;
}

.aysa-preview-change-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.aysa-preview-change-title {
    font-weight: 600;
    color: #2c3e50;
}

.aysa-preview-change-count {
    background: #2271b1;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
}

.aysa-preview-content-diff {
    background: #f8f9fa;
    border-left: 4px solid #2271b1;
    padding: 12px;
    font-family: monospace;
    font-size: 13px;
    line-height: 1.4;
    overflow-x: auto;
}

.aysa-preview-added-link {
    background: #d4edda;
    color: #155724;
    padding: 2px 4px;
    border-radius: 3px;
}

.aysa-loader {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #2271b1;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 0 auto 16px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Site Audit */
.aysa-site-audit-panel {
    border: 1px solid #dbe4f4;
    background: #f9fbff;
}

.aysa-site-audit-subtitle {
    margin-top: -6px;
    color: #4f607d;
}

.aysa-site-audit-controls {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 14px 0;
    flex-wrap: wrap;
}

.aysa-site-audit-status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 88px;
    padding: 6px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    border: 1px solid #c8d4ea;
    background: #eef3fb;
    color: #3f5274;
}

.aysa-site-audit-status-badge.is-running {
    background: #fff5e8;
    border-color: #ffd7a2;
    color: #8d4d00;
}

.aysa-site-audit-status-badge.is-completed {
    background: #e9f8ec;
    border-color: #bce6c6;
    color: #216a32;
}

.aysa-site-audit-status-badge.is-failed {
    background: #ffecec;
    border-color: #ffc8c8;
    color: #9f2e2e;
}

.aysa-site-audit-meta {
    display: grid;
    grid-template-columns: repeat(3, minmax(180px, 1fr));
    gap: 10px;
    margin: 10px 0 14px;
}

.aysa-site-audit-meta > div {
    background: #fff;
    border: 1px solid #e3eaf7;
    border-radius: 6px;
    padding: 8px 10px;
    font-size: 13px;
}

.aysa-site-audit-message {
    margin: 8px 0 14px;
    padding: 9px 12px;
    border-radius: 6px;
    font-size: 13px;
}

.aysa-site-audit-message.info {
    background: #eef5ff;
    border: 1px solid #d8e6ff;
    color: #1e4b88;
}

.aysa-site-audit-message.success {
    background: #eaf8ed;
    border: 1px solid #caeacb;
    color: #1f6a30;
}

.aysa-site-audit-message.error {
    background: #fff0f0;
    border: 1px solid #f5cccc;
    color: #8e2e2e;
}

.aysa-site-audit-kpis {
    display: grid;
    grid-template-columns: repeat(4, minmax(150px, 1fr));
    gap: 10px;
    margin: 10px 0 16px;
}

.aysa-site-audit-kpi {
    background: #fff;
    border: 1px solid #d9e6fb;
    border-radius: 10px;
    padding: 12px;
}

.aysa-site-audit-kpi .label {
    display: block;
    font-size: 12px;
    color: #637692;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}

.aysa-site-audit-kpi strong {
    display: block;
    margin-top: 6px;
    font-size: 26px;
    color: #0f2947;
}

.aysa-site-audit-subtabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

.aysa-site-audit-subtab-btn {
    border: 1px solid #c9d8ef;
    border-radius: 8px;
    background: #fff;
    color: #1f3c62;
    font-weight: 600;
    padding: 8px 12px;
    cursor: pointer;
}

.aysa-site-audit-subtab-btn.is-active {
    background: #1e63c7;
    border-color: #1e63c7;
    color: #fff;
}

.aysa-site-audit-subtab-content {
    display: none;
}

.aysa-site-audit-subtab-content.is-active {
    display: block;
}

.aysa-site-audit-issue-row {
    cursor: pointer;
}

.aysa-site-audit-issue-row:hover td {
    background: #f6fbff;
}

.aysa-site-audit-modal {
    position: fixed;
    inset: 0;
    z-index: 100000;
}

.aysa-site-audit-modal-backdrop {
    position: absolute;
    inset: 0;
    background: rgba(18, 30, 52, 0.55);
}

.aysa-site-audit-modal-dialog {
    position: relative;
    margin: 2vh auto;
    width: 96vw;
    height: 96vh;
    max-width: 96vw;
    max-height: 96vh;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 20px 60px rgba(8, 24, 52, 0.3);
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.aysa-site-audit-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e7edf5;
    flex: 0 0 auto;
}

.aysa-site-audit-modal-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 700;
    color: #13294b;
}

.aysa-site-audit-modal-close {
    border: 0;
    background: #f1f5fb;
    color: #2a3f66;
    width: 34px;
    height: 34px;
    border-radius: 999px;
    font-size: 23px;
    line-height: 34px;
    cursor: pointer;
}

.aysa-site-audit-modal-meta {
    display: flex;
    gap: 14px;
    align-items: center;
    padding: 12px 20px;
    border-bottom: 1px solid #edf2f8;
    flex-wrap: wrap;
    flex: 0 0 auto;
}

.aysa-site-audit-modal-description {
    margin: 0;
    padding: 14px 20px 8px;
    color: #3b4b63;
    flex: 0 0 auto;
}

.aysa-site-audit-modal-table-wrap {
    padding: 0 20px 18px;
    overflow-x: auto;
    overflow-y: auto;
    flex: 1 1 auto;
    position: relative;
    background: #fff;
}

.aysa-site-audit-modal-table-wrap table td,
.aysa-site-audit-modal-table-wrap table th {
    white-space: normal;
    vertical-align: top;
}

.aysa-site-audit-modal-table-wrap table {
    width: 100%;
    table-layout: auto;
    border-collapse: separate;
    border-spacing: 0;
    background: #fff;
}

.aysa-site-audit-modal-table-wrap thead th {
    position: sticky;
    top: 0;
    background: #f6f7f7;
    z-index: 3;
    box-shadow: inset 0 -1px 0 #dcdcde;
}

.aysa-site-audit-modal-table-wrap tbody td {
    background: #fff;
}

.aysa-site-audit-modal-table-wrap tbody tr:first-child td {
    border-top: 0;
}

.aysa-site-audit-modal-table-wrap td:first-child,
.aysa-site-audit-modal-table-wrap th:first-child {
    min-width: 360px;
}

.aysa-site-audit-modal-table-wrap td a {
    word-break: break-word;
    overflow-wrap: anywhere;
}

body.aysa-site-audit-modal-open {
    overflow: hidden;
}

.aysa-site-audit-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(260px, 1fr));
    gap: 12px;
}

.aysa-site-audit-card {
    background: #fff;
    border: 1px solid #dbe6f8;
    border-radius: 10px;
    padding: 12px;
}

.aysa-site-audit-card h4 {
    margin: 0 0 8px;
    font-size: 15px;
    color: #20395e;
}

.aysa-site-audit-card-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 10px;
}

.aysa-site-audit-card-head h4 {
    margin-bottom: 0;
}

.aysa-site-audit-card-span-2 {
    grid-column: 1 / -1;
}

.aysa-site-audit-conclusion-summary {
    margin: 0 0 12px;
    color: #2a3d59;
    font-size: 14px;
    line-height: 1.5;
}

.aysa-site-audit-conclusion-panel {
    background: #f7faff;
    border: 1px solid #dce7f8;
    border-radius: 10px;
    padding: 12px;
}

.aysa-site-audit-conclusion-copy {
    margin: 8px 0 0;
    color: #314966;
    line-height: 1.5;
}

.aysa-site-audit-conclusion-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(240px, 1fr));
    gap: 14px;
}

.aysa-site-audit-conclusion-list {
    margin: 8px 0 0;
    padding-left: 18px;
}

.aysa-site-audit-conclusion-list li {
    margin: 4px 0;
}

.aysa-site-audit-conclusion-ordered {
    padding-left: 22px;
}

.aysa-site-audit-recommended-actions {
    margin-top: 16px;
    padding-top: 14px;
    border-top: 1px solid #dbe6f8;
}

.aysa-site-audit-recommended-actions-list {
    display: grid;
    grid-template-columns: repeat(2, minmax(260px, 1fr));
    gap: 12px;
}

.aysa-site-audit-action-card {
    background: #fff;
    border: 1px solid #dbe6f8;
    border-radius: 10px;
    padding: 12px;
}

.aysa-site-audit-action-card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 10px;
}

.aysa-site-audit-action-card h5 {
    margin: 0 0 8px;
    color: #173659;
    font-size: 14px;
}

.aysa-site-audit-action-card p {
    margin: 0 0 10px;
    color: #425770;
    line-height: 1.45;
}

.aysa-site-audit-action-meta {
    margin: 4px 0;
    color: #36506f;
    font-size: 13px;
    line-height: 1.45;
}

.aysa-site-audit-action-breakdown {
    margin: 10px 0;
    padding: 10px 12px;
    border: 1px solid #dbe6f8;
    border-radius: 8px;
    background: #f8fbff;
}

.aysa-site-audit-action-breakdown strong {
    color: #20395e;
}

.aysa-site-audit-action-breakdown ul {
    margin: 8px 0 0;
    padding-left: 18px;
}

.aysa-site-audit-action-breakdown li {
    margin: 4px 0;
    color: #3d5470;
    font-size: 13px;
}

.aysa-site-audit-action-state {
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 999px;
    background: #edf2f8;
    border: 1px solid #d4deed;
    color: #355170;
    font-size: 12px;
    font-weight: 600;
    text-transform: capitalize;
}

.aysa-site-audit-action-state.is-prepared {
    background: #eef7f0;
    border-color: #cfe5d4;
    color: #2f6a3c;
}

.aysa-site-audit-action-state.is-dismissed {
    background: #fff1f1;
    border-color: #f0c8c8;
    color: #8d3a3a;
}

.aysa-site-audit-action-footer {
    margin-top: 12px;
}

.aysa-site-audit-top-problems {
    margin-bottom: 14px;
    padding: 14px;
    border: 1px solid #dbe6f8;
    border-radius: 10px;
    background: linear-gradient(180deg, #f8fbff 0%, #f3f7fd 100%);
}

.aysa-site-audit-top-problems-list {
    display: grid;
    grid-template-columns: repeat(3, minmax(220px, 1fr));
    gap: 12px;
}

.aysa-site-audit-top-problem {
    background: #fff;
    border: 1px solid #dbe6f8;
    border-radius: 10px;
    padding: 12px;
}

.aysa-site-audit-top-problem-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.aysa-site-audit-top-problem h5 {
    margin: 0 0 8px;
    font-size: 14px;
    color: #173659;
}

.aysa-site-audit-top-problem p {
    margin: 0 0 10px;
    color: #425770;
    line-height: 1.45;
}

.aysa-site-audit-top-problem-fix {
    color: #1c3a61;
    font-size: 13px;
    line-height: 1.45;
}

.aysa-site-audit-top-problem-count {
    color: #516784;
    font-size: 12px;
    font-weight: 600;
}

.aysa-site-audit-top-problem-empty {
    color: #4f607d;
    font-size: 13px;
}

.aysa-site-audit-toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
    margin: 0 0 14px;
}

.aysa-site-audit-issues-help {
    margin: 0 0 12px;
}

.aysa-site-audit-issues-toolbar .actions {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-right: 10px;
    margin-bottom: 8px;
}

.aysa-site-audit-issues-toolbar select {
    min-width: 180px;
}

.aysa-site-audit-search-wrap {
    min-width: 240px;
    flex: 1 1 280px;
}

.aysa-site-audit-search {
    width: 100%;
    min-height: 40px;
    border: 1px solid #cad7ea;
    border-radius: 10px;
    padding: 0 14px;
    background: #fff;
}

.aysa-site-audit-filter-pills {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.aysa-site-audit-filter-pill {
    appearance: none;
    border: 1px solid #cfdbed;
    background: #fff;
    color: #214365;
    border-radius: 999px;
    padding: 7px 12px;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
}

.aysa-site-audit-filter-pill span {
    color: #5c7290;
}

.aysa-site-audit-filter-pill.is-active {
    background: #eaf3ff;
    border-color: #9fc0ef;
    color: #17437c;
}

.aysa-site-audit-issue-groups {
    display: flex;
    flex-direction: column;
    gap: 14px;
    width: 100%;
}

.aysa-site-audit-issue-group {
    border: 1px solid #dbe6f8;
    border-radius: 12px;
    overflow: hidden;
    background: #fff;
    width: 100%;
    max-width: none;
    clear: both;
}

#aysa-site-audit-issues-groups .postbox,
#aysa-site-audit-issues-groups .inside,
#aysa-site-audit-issues-groups table.widefat {
    width: 100%;
    max-width: none;
    box-sizing: border-box;
}

#aysa-site-audit-issues-groups table.widefat {
    table-layout: auto;
}

#aysa-site-audit-issues-groups table.widefat th,
#aysa-site-audit-issues-groups table.widefat td {
    white-space: normal;
    word-break: normal;
    overflow-wrap: anywhere;
    vertical-align: top;
}

#aysa-site-audit-issues-groups table.widefat th:nth-child(1) {
    width: 28%;
}

#aysa-site-audit-issues-groups table.widefat th:nth-child(2) {
    width: 12%;
}

#aysa-site-audit-issues-groups table.widefat th:nth-child(3) {
    width: 28%;
}

#aysa-site-audit-issues-groups table.widefat th:nth-child(4) {
    width: 22%;
}

#aysa-site-audit-issues-groups table.widefat th:nth-child(5) {
    width: 10%;
}

.aysa-site-audit-issue-group-head {
    padding: 12px 14px;
    border-bottom: 1px solid #e5edf9;
    background: #f8fbff;
}

.aysa-site-audit-issue-group.is-error .aysa-site-audit-issue-group-head {
    border-top: 3px solid #ef5350;
}

.aysa-site-audit-issue-group.is-warning .aysa-site-audit-issue-group-head {
    border-top: 3px solid #f6a43c;
}

.aysa-site-audit-issue-group.is-notice .aysa-site-audit-issue-group-head {
    border-top: 3px solid #2196f3;
}

.aysa-site-audit-issue-group-head h4 {
    margin: 0;
}

.aysa-site-audit-issue-list {
    display: flex;
    flex-direction: column;
}

.aysa-site-audit-issue-item {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    padding: 14px;
    border-top: 1px solid #edf2f8;
}

.aysa-site-audit-issue-item:first-child {
    border-top: 0;
}

.aysa-site-audit-issue-main {
    min-width: 0;
    flex: 1 1 auto;
}

.aysa-site-audit-issue-side {
    display: flex;
    align-items: center;
    flex: 0 0 auto;
}

.aysa-site-audit-issue-title-row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    margin-bottom: 8px;
}

.aysa-site-audit-issue-category {
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 999px;
    background: #f2f6fc;
    color: #536b89;
    font-size: 12px;
    font-weight: 700;
}

.aysa-site-audit-issue-item h5 {
    margin: 0 0 8px;
    color: #16365b;
    font-size: 16px;
}

.aysa-site-audit-issue-impact {
    margin: 0 0 10px;
    color: #435872;
    line-height: 1.5;
}

.aysa-site-audit-issue-meta-line {
    margin: 4px 0;
    color: #314b69;
    font-size: 13px;
    line-height: 1.45;
}

.aysa-site-audit-status-pill {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 48px;
    padding: 5px 10px;
    border-radius: 999px;
    font-weight: 700;
    background: #edf2f8;
    color: #365170;
}

.aysa-site-audit-status-pill.status-200 {
    background: #dff5e6;
    color: #1d7d41;
}

.aysa-site-audit-page-issue-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 5px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    background: #edf2f8;
    color: #365170;
}

.aysa-site-audit-page-issue-badge.is-fix-now {
    background: #fff0f0;
    color: #982f2f;
}

.aysa-site-audit-page-issue-badge.is-high {
    background: #fff5e8;
    color: #8d4d00;
}

.aysa-site-audit-page-issue-badge.is-medium {
    background: #eef5ff;
    color: #29558f;
}

.aysa-site-audit-page-issue-note {
    margin-top: 5px;
    color: #556d8b;
    font-size: 12px;
    line-height: 1.35;
}

.aysa-site-audit-stats-grid {
    margin-bottom: 12px;
}

.aysa-site-audit-stat-card {
    min-height: 170px;
}

.aysa-site-audit-stat-value {
    font-size: 22px;
    font-weight: 800;
    color: #1c4f95;
    margin-bottom: 6px;
}

.aysa-site-audit-stat-subtitle {
    color: #425770;
    font-size: 13px;
    margin-bottom: 12px;
}

.aysa-site-audit-stat-list {
    margin: 0;
    padding-left: 18px;
}

.aysa-site-audit-stat-list li {
    margin: 4px 0;
    color: #49607d;
    font-size: 13px;
}

.aysa-site-audit-priority-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 72px;
    padding: 4px 9px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    border: 1px solid #d4deed;
    background: #edf2f8;
    color: #355170;
}

.aysa-site-audit-priority-badge.is-fix-now {
    background: #fff0f0;
    border-color: #f0b1b1;
    color: #982f2f;
}

.aysa-site-audit-priority-badge.is-high {
    background: #fff5e8;
    border-color: #ffd7a2;
    color: #8d4d00;
}

.aysa-site-audit-priority-badge.is-medium {
    background: #eef5ff;
    border-color: #c8dcfb;
    color: #29558f;
}

.aysa-site-audit-priority-badge.is-low {
    background: #eef7f0;
    border-color: #cfe5d4;
    color: #2f6a3c;
}

.aysa-site-audit-card ul {
    margin: 0;
    padding-left: 18px;
}

.aysa-site-audit-card li {
    margin: 2px 0;
}

.aysa-site-audit-table-wrap {
    overflow: visible;
    border: 1px solid #dbe6f8;
    border-radius: 8px;
    background: #fff;
}

.aysa-site-audit-table-wrap table {
    margin: 0;
}

.aysa-site-audit-inline-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 8px;
}

.aysa-site-audit-inline-action {
    appearance: none;
    border: 1px solid #cfdcf2;
    background: #f7faff;
    color: #294b72;
    border-radius: 999px;
    padding: 5px 10px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
}

.aysa-site-audit-inline-action:hover,
.aysa-site-audit-inline-action:focus {
    background: #edf4ff;
    border-color: #b8cbe8;
    color: #173659;
}

.aysa-site-audit-table-wrap thead th {
    position: sticky;
    top: 0;
    z-index: 15;
    background: #f2f6fc;
}

@media (max-width: 782px) {
    .aysa-site-audit-table-wrap {
        overflow-x: auto;
        overflow-y: visible;
    }

    .aysa-site-audit-table-wrap thead th {
        top: 0;
    }
}

.aysa-issue-severity-error,
.aysa-issue-severity-warning,
.aysa-issue-severity-notice {
    display: inline-block;
    border-radius: 999px;
    padding: 4px 9px;
    text-transform: uppercase;
    font-size: 11px;
    font-weight: 700;
}

.aysa-issue-severity-error {
    color: #a72a2a;
    background: #ffe7e7;
    border: 1px solid #ffc8c8;
}

.aysa-issue-severity-warning {
    color: #8d5700;
    background: #fff1dd;
    border: 1px solid #ffd8a8;
}

.aysa-issue-severity-notice {
    color: #225186;
    background: #e9f2ff;
    border: 1px solid #c5dcff;
}

.aysa-sitemap-robots-panel .aysa-site-audit-grid {
    grid-template-columns: 1fr 1fr;
}

.aysa-sitemap-robots-panel .aysa-site-audit-card {
    min-height: 320px;
}

.aysa-sitemap-robots-panel .aysa-site-audit-table-wrap {
    max-height: 320px;
    overflow: auto;
}

.aysa-sitemap-robots-panel .aysa-site-audit-table-wrap thead th {
    top: 0;
}

.aysa-sitemap-robots-panel .aysa-textarea {
    background: #fbfdff;
    border-color: #cfdcf2;
}

@media (max-width: 960px) {
    .aysa-sitemap-robots-panel .aysa-site-audit-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 960px) {
    .aysa-site-audit-kpis,
    .aysa-site-audit-grid,
    .aysa-site-audit-conclusion-grid,
    .aysa-site-audit-top-problems-list,
    .aysa-site-audit-recommended-actions-list {
        grid-template-columns: 1fr;
    }

    .aysa-site-audit-meta {
        grid-template-columns: 1fr;
    }

    .aysa-site-audit-issue-item {
        flex-direction: column;
    }

    .aysa-site-audit-issue-side {
        justify-content: flex-start;
    }
}
</style>

<script type="text/javascript">
jQuery(function($) {
    try {
        const params = new URLSearchParams(window.location.search || '');
        const requestedTab = String(params.get('aysa_tab') || '').trim();
        if (!requestedTab) {
            return;
        }
        const $tab = $('.aysa-tab-btn[data-target="' + requestedTab + '"]');
        if ($tab.length) {
            window.setTimeout(function() {
                $tab.trigger('click');
            }, 0);
        }
    } catch (e) {
    }
});
</script>

</div>
