<?php

/**
 * Admin Bar Menu Handler
 *
 * Adds ProRank quick access menu to WordPress admin bar
 *
 * @package ProRank\SEO\Admin
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Admin;

use ProRank\SEO\Modules\Performance\CssOptimizeModule;
use ProRank\SEO\Services\Cdn\CdnManager;
use ProRank\SEO\Core\Lifecycle;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * AdminBarMenu class
 */


class AdminBarMenu {
    private const SEO_CACHE_KEY = 'prorank_adminbar_seo_summary';
    private const SEO_CACHE_TTL = 5 * MINUTE_IN_SECONDS;
    private const POST_ROBOTS_DIRECTIVES = ['noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex'];

    /**
     * Cloud audit is not available in the free runtime.
     */
    private function can_use_cloud_audit(): bool {
        return false;
    }
    
    /**
     * Initialize admin bar menu
     *
     * @return void
     */
    public function init(): void {
        // Only show for users who can manage options
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Add admin bar menu
        add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
        
        // Handle AJAX cache clearing
        add_action('wp_ajax_prorank_clear_cache', [$this, 'ajax_clear_cache']);
        
        // Handle AJAX debug toggle
        add_action('wp_ajax_prorank_toggle_debug', [$this, 'ajax_toggle_debug']);
        add_action('admin_post_prorank_update_post_seo', [$this, 'handle_post_seo_action']);
        // Add inline styles and scripts
        add_action('admin_head', [$this, 'add_inline_assets']);
        add_action('wp_head', [$this, 'add_inline_assets']);
    }
    
    /**
     * Add admin bar menu items
     *
     * @param \WP_Admin_Bar $wp_admin_bar Admin bar instance
     * @return void
     */
    public function add_admin_bar_menu(\WP_Admin_Bar $wp_admin_bar): void {
        // Get SEO data
        $seo_data = $this->get_seo_dashboard_data();
        $score = $seo_data['seo_score'] ?? null;
        $issues = $seo_data['issues_count'] ?? 0;
        $current_post_id = $this->get_current_post_context_id();

        // Build main menu title with score badge
        $main_title = '<span class="ab-icon"></span><span class="ab-label">ProRank SEO</span>';
        if ($score !== null) {
            $score_class = $this->get_score_class($score);
            $main_title .= sprintf(' <span class="prorank-score-badge %s">%d</span>', $score_class, $score);
        }

        // ═══════════════════════════════════════════════════════════════
        // MAIN MENU
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_menu([
            'id' => 'prorank-seo',
            'title' => $main_title,
            'href' => admin_url('admin.php?page=prorank-seo'),
            'meta' => [
                'title' => __('ProRank SEO Dashboard', 'prorank-seo'),
                'class' => 'prorank-admin-bar-menu',
            ],
        ]);

        // ═══════════════════════════════════════════════════════════════
        // SEO OVERVIEW GROUP
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_group([
            'parent' => 'prorank-seo',
            'id' => 'prorank-seo-overview',
        ]);

        // SEO Score Display
        if ($score !== null) {
            $score_label = $this->get_score_label($score);
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-seo-overview',
                'id' => 'prorank-score-display',
                'title' => sprintf(
                    '<span class="prorank-menu-icon">📊</span> SEO Score: <strong>%d/100</strong> <span class="prorank-score-label %s">%s</span>',
                    $score,
                    $this->get_score_class($score),
                    $score_label
                ),
                'href' => admin_url('admin.php?page=prorank-seo'),
            ]);
        }

        // Issues Alert
        if ($issues > 0) {
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-seo-overview',
                'id' => 'prorank-issues-alert',
                'title' => sprintf(
                    '<span class="prorank-menu-icon">⚠️</span> <span class="prorank-issues-text">%d %s</span>',
                    $issues,
                    _n('Issue Found', 'Issues Found', $issues, 'prorank-seo')
                ),
                'href' => admin_url('admin.php?page=prorank-site-audit'),
            ]);
        }

        // ═══════════════════════════════════════════════════════════════
        // QUICK ACTIONS GROUP
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_group([
            'parent' => 'prorank-seo',
            'id' => 'prorank-quick-actions',
            'meta' => ['class' => 'ab-sub-secondary'],
        ]);

        // Dashboard
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-quick-actions',
            'id' => 'prorank-dashboard',
            'title' => '<span class="prorank-menu-icon">🏠</span> ' . __('Dashboard', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-seo'),
        ]);

        // Site Audit
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-quick-actions',
            'id' => 'prorank-site-audit',
            'title' => '<span class="prorank-menu-icon">🔍</span> ' . __('Site Audit', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-site-audit'),
        ]);

        // On-Page SEO
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-quick-actions',
            'id' => 'prorank-on-page',
            'title' => '<span class="prorank-menu-icon">📝</span> ' . __('On-Page SEO', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-on-page-seo'),
        ]);

        $il_detector = new \ProRank\SEO\Core\Compatibility\CompetitorDetector();
        if (!$il_detector->should_enable_internal_linking_safe_mode()) {
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-quick-actions',
                'id' => 'prorank-internal-linking',
                'title' => '<span class="prorank-menu-icon">🔗</span> ' . __('Internal Linking', 'prorank-seo'),
                'href' => admin_url('admin.php?page=prorank-internal-linking'),
            ]);
        }

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-quick-actions',
            'id' => 'prorank-technical',
            'title' => '<span class="prorank-menu-icon">⚙️</span> ' . __('Technical SEO', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-technical-seo'),
        ]);

        if ($current_post_id > 0) {
            $this->add_current_post_controls($wp_admin_bar, $current_post_id);
        }

        // ═══════════════════════════════════════════════════════════════
        // CACHE MANAGEMENT SUBMENU
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-seo',
            'id' => 'prorank-cache',
            'title' => '<span class="prorank-menu-icon">🗑️</span> ' . __('Cache Management', 'prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-cache',
            'id' => 'prorank-clear-all',
            'title' => __('Clear All Cache', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankClearCache("all"); return false;'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-cache',
            'id' => 'prorank-clear-css',
            'title' => __('Clear CSS Cache', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankClearCache("css"); return false;'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-cache',
            'id' => 'prorank-clear-html',
            'title' => __('Clear HTML Cache', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankClearCache("html"); return false;'],
        ]);

        // CDN Cache (if configured)
        $cdn_provider = get_option('prorank_cdn_provider', 'none');
        if ($cdn_provider !== 'none') {
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-cache',
                'id' => 'prorank-clear-cdn',
/* translators: %1$: value */
                'title' => sprintf(__('Clear %1$s Cache', 'prorank-seo'), ucfirst($cdn_provider)),
                'href' => '#',
                'meta' => ['onclick' => 'prorankClearCache("cdn"); return false;'],
            ]);
        }

        // Cache Stats
        $cache_stats = $this->get_cache_statistics();
        if ($cache_stats && !empty($cache_stats['total_size']) && $cache_stats['total_size'] > 0) {
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-cache',
                'id' => 'prorank-cache-stats',
                'title' => sprintf(
                    '<small style="color:#999">%s: %s | %s: %d</small>',
                    __('Size', 'prorank-seo'),
                    size_format($cache_stats['total_size']),
                    __('Files', 'prorank-seo'),
                    $cache_stats['total_files']
                ),
            ]);
        }

        // ═══════════════════════════════════════════════════════════════
        // PERFORMANCE TOOLS SUBMENU
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-seo',
            'id' => 'prorank-tools',
            'title' => '<span class="prorank-menu-icon">🛠️</span> ' . __('Performance Tools', 'prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-tools',
            'id' => 'prorank-pagespeed',
            'title' => __('PageSpeed Insights', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankTestPageSpeed(); return false;'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-tools',
            'id' => 'prorank-gtmetrix',
            'title' => __('GTmetrix Test', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankTestGTmetrix(); return false;'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-tools',
            'id' => 'prorank-mobile-test',
            'title' => __('Mobile-Friendly Test', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankMobileTest(); return false;'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-tools',
            'id' => 'prorank-schema-test',
            'title' => __('Schema Markup Test', 'prorank-seo'),
            'href' => '#',
            'meta' => ['onclick' => 'prorankSchemaTest(); return false;'],
        ]);

        // ═══════════════════════════════════════════════════════════════
        // SETTINGS SUBMENU
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-seo',
            'id' => 'prorank-settings',
            'title' => '<span class="prorank-menu-icon">⚙️</span> ' . __('Settings', 'prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-settings',
            'id' => 'prorank-settings-general',
            'title' => __('Dashboard Overview', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-settings',
            'id' => 'prorank-settings-technical',
            'title' => __('Technical SEO', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-technical-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-settings',
            'id' => 'prorank-settings-performance',
            'title' => __('Performance', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-performance'),
        ]);

        // Debug Mode Toggle (if WP_DEBUG)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $debug_mode = get_option('prorank_debug_mode', false);
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-settings',
                'id' => 'prorank-debug-toggle',
                'title' => __('Debug Mode', 'prorank-seo') . ($debug_mode ? ' ✓' : ' ✗'),
                'href' => '#',
                'meta' => ['onclick' => 'prorankToggleDebug(); return false;'],
            ]);
        }

        // ═══════════════════════════════════════════════════════════════
        // HELP & SUPPORT
        // ═══════════════════════════════════════════════════════════════
        $wp_admin_bar->add_menu([
            'parent' => 'prorank-seo',
            'id' => 'prorank-help',
            'title' => '<span class="prorank-menu-icon">❓</span> ' . __('Help & Support', 'prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-help',
            'id' => 'prorank-documentation',
            'title' => __('Documentation', 'prorank-seo'),
            'href' => 'https://prorank.io/docs',
            'meta' => ['target' => '_blank'],
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-help',
            'id' => 'prorank-support-ticket',
            'title' => __('Submit Support Ticket', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-support'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-help',
            'id' => 'prorank-changelog',
            'title' => __('Changelog', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-support&tab=changelog'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-help',
            'id' => 'prorank-license',
            'title' => __('License & Account', 'prorank-seo'),
            'href' => admin_url('admin.php?page=prorank-support'),
        ]);
    }
    
    /**
     * Add inline assets for admin bar functionality
     *
     * @return void
     */
    public function add_inline_assets(): void {
        $icon_data = '';
        $icon_paths = [];
        if (defined('PRORANK_PLUGIN_DIR')) {
            $icon_paths[] = PRORANK_PLUGIN_DIR . 'assets/prorank.svg';
            $icon_paths[] = PRORANK_PLUGIN_DIR . 'prorank.svg';
        }

        foreach ($icon_paths as $icon_path) {
            if (!file_exists($icon_path)) {
                continue;
            }

            $svg = file_get_contents($icon_path);
            if ($svg !== false) {
                // Force monochrome white for admin bar icon consistency.
                $svg = preg_replace('/fill="[^"]*"/i', 'fill="#ffffff"', $svg);
                $svg = preg_replace("/fill='[^']*'/i", "fill='#ffffff'", $svg);
                $icon_data = 'data:image/svg+xml;base64,' . base64_encode($svg);
                break;
            }
        }

        if ($icon_data === '') {
            $fallback_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><circle cx="10" cy="10" r="9" fill="#3b82f6"/><circle cx="10" cy="10" r="4" fill="#ff6b35"/></svg>';
            $icon_data = 'data:image/svg+xml;base64,' . base64_encode($fallback_svg);
        }
        ?>
        <style>
            /* ═══════════════════════════════════════════════════════════════ */
            /* ProRank SEO Premium Admin Bar Styles                            */
            /* ═══════════════════════════════════════════════════════════════ */

            /* Main Menu Icon - ProRank Logo */
            #wpadminbar #wp-admin-bar-prorank-seo > .ab-item .ab-icon {
                width: 20px !important;
                height: 20px !important;
                margin-right: 6px !important;
            }
            #wpadminbar #wp-admin-bar-prorank-seo > .ab-item .ab-icon::before {
                content: '' !important;
                display: block !important;
                width: 20px !important;
                height: 20px !important;
                background-image: url('<?php echo esc_attr($icon_data); ?>') !important;
                background-size: contain !important;
                background-repeat: no-repeat !important;
                background-position: center !important;
                font-family: inherit !important;
            }

            /* Score Badge in Top Bar */
            #wpadminbar .prorank-score-badge {
                display: inline;
                padding: 2px 7px;
                border-radius: 9px;
                font-size: 13px !important;
                font-weight: 700;
                margin-left: 6px;
            }
            #wpadminbar .prorank-score-badge.good {
                background: #0cce6b;
                color: #fff;
            }
            #wpadminbar .prorank-score-badge.ok {
                background: #ffa400;
                color: #fff;
            }
            #wpadminbar .prorank-score-badge.poor {
                background: #ff4e42;
                color: #fff;
            }

            /* Score Label in Dropdown */
            .prorank-score-label {
                padding: 2px 8px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: 600;
                margin-left: 8px;
            }
            .prorank-score-label.good { background: rgba(40, 167, 69, 0.2); color: #28a745; }
            .prorank-score-label.ok { background: rgba(249, 115, 22, 0.2); color: #f97316; }
            .prorank-score-label.poor { background: rgba(220, 53, 69, 0.2); color: #dc3545; }

            /* Issues Alert Text */
            .prorank-issues-text {
                color: #f97316 !important;
                font-weight: 600;
            }

            /* Menu Icons */
            .prorank-menu-icon {
                margin-right: 6px;
                font-size: 14px;
            }

            /* Dropdown Groups Styling */
            #wpadminbar .ab-sub-secondary {
                border-top: 1px solid rgba(255,255,255,0.1);
                padding-top: 6px;
                margin-top: 6px;
            }

            /* Hover Effects */
            #wpadminbar #wp-admin-bar-prorank-seo .ab-submenu a:hover {
                background: rgba(0, 212, 255, 0.1) !important;
                color: #00d4ff !important;
            }

            /* Submenu Headers */
            #wpadminbar #wp-admin-bar-prorank-cache > .ab-item,
            #wpadminbar #wp-admin-bar-prorank-tools > .ab-item,
            #wpadminbar #wp-admin-bar-prorank-settings > .ab-item,
            #wpadminbar #wp-admin-bar-prorank-help > .ab-item {
                font-weight: 600 !important;
                border-bottom: 1px solid rgba(255,255,255,0.05);
            }

            /* Cache Stats */
            #wpadminbar #wp-admin-bar-prorank-cache-stats .ab-item {
                font-size: 11px !important;
                color: #888 !important;
                cursor: default;
            }

            /* Cache clearing states */
            .prorank-clearing-cache { opacity: 0.6; pointer-events: none; }
            .prorank-cache-cleared .ab-item { color: #28a745 !important; }
            .prorank-cache-error .ab-item { color: #dc3545 !important; }

            /* External link indicator */
            #wpadminbar #wp-admin-bar-prorank-documentation .ab-item:after {
                content: " ↗";
                font-size: 10px;
                opacity: 0.6;
            }
        </style>
        <script>
            function prorankClearCache(type) {
                if (confirm('Are you sure you want to clear the ' + type + ' cache?')) {
                    const menuItem = event.target.closest('li');
                    menuItem.classList.add('prorank-clearing-cache');
                    
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'action=prorank_clear_cache&type=' + type + '&_ajax_nonce=' + <?php echo json_encode(wp_create_nonce('prorank_clear_cache')); ?>
                    })
                    .then(response => response.json())
                    .then(data => {
                        menuItem.classList.remove('prorank-clearing-cache');
                        if (data.success) {
                            menuItem.classList.add('prorank-cache-cleared');
                            alert(data.data.message || 'Cache cleared successfully!');
                            
                            // Refresh cache stats if visible
                            const statsElement = document.getElementById('wp-admin-bar-prorank-cache-stats');
                            if (statsElement && data.data.stats) {
                                statsElement.querySelector('.ab-item').innerHTML = 
                                    '<small>Size: ' + data.data.stats.size_formatted + ' | Files: ' + data.data.stats.files_formatted + '</small>';
                            }
                        } else {
                            menuItem.classList.add('prorank-cache-error');
                            alert('Error: ' + (data.data || 'Failed to clear cache'));
                        }
                        
                        // Remove status classes after 3 seconds
                        setTimeout(() => {
                            menuItem.classList.remove('prorank-cache-cleared', 'prorank-cache-error');
                        }, 3000);
                    })
                    .catch(error => {
                        menuItem.classList.remove('prorank-clearing-cache');
                        menuItem.classList.add('prorank-cache-error');
                        alert('Error clearing cache: ' + error.message);
                    });
                }
            }
            
            function prorankTestPageSpeed() {
                const url = window.location.href;
                window.open('https://pagespeed.web.dev/report?url=' + encodeURIComponent(url), '_blank');
            }

            function prorankTestGTmetrix() {
                const url = window.location.href;
                window.open('https://gtmetrix.com/?url=' + encodeURIComponent(url), '_blank');
            }

            function prorankMobileTest() {
                const url = window.location.href;
                window.open('https://search.google.com/test/mobile-friendly?url=' + encodeURIComponent(url), '_blank');
            }

            function prorankSchemaTest() {
                const url = window.location.href;
                window.open('https://validator.schema.org/#url=' + encodeURIComponent(url), '_blank');
            }

            function prorankToggleDebug() {
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=prorank_toggle_debug&_ajax_nonce=' + <?php echo json_encode(wp_create_nonce('prorank_toggle_debug')); ?>
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    }
                });
            }

            function prorankSetCanonical(actionUrl, currentValue) {
                const nextValue = window.prompt('Enter a custom canonical URL. Leave blank to clear it.', currentValue || '');
                if (nextValue === null) {
                    return false;
                }

                const separator = actionUrl.indexOf('?') === -1 ? '?' : '&';
                window.location.href = actionUrl + separator + 'canonical=' + encodeURIComponent(nextValue.trim());
                return false;
            }
        </script>
        <?php
    }
    
    /**
     * Handle AJAX cache clearing
     *
     * @return void
     */
    public function ajax_clear_cache(): void {
        // Verify nonce
        if (!check_ajax_referer('prorank_clear_cache', '_ajax_nonce', false)) {
            wp_send_json_error('Invalid security token');
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $type = $_POST['type'] ?? 'all';
        
        try {
            switch ($type) {
                case 'css':
                    $this->clear_css_cache();
                    $message = __('CSS cache cleared successfully', 'prorank-seo');
                    break;
                    
                case 'html':
                    $this->clear_html_cache();
                    $message = __('HTML cache cleared successfully', 'prorank-seo');
                    break;
                    
                case 'cdn':
                    $this->clear_cdn_cache();
                    $message = __('CDN cache cleared successfully', 'prorank-seo');
                    break;
                    
                case 'all':
                default:
                    $this->clear_all_cache();
                    $message = __('All caches cleared successfully', 'prorank-seo');
                    break;
            }
            
            // Get updated cache stats
            $stats = $this->get_cache_statistics();
            
            wp_send_json_success([
                'message' => $message,
                'stats' => [
                    'size_formatted' => size_format($stats['total_size']),
                    'files_formatted' => number_format($stats['total_files']),
                ],
            ]);
            
        } catch (\Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }
    
    /**
     * Clear CSS cache
     *
     * @return void
     */
    private function clear_css_cache(): void {
        try {
            $plugin = \ProRank\SEO\Plugin::get_instance();
            $module_manager = $plugin->modules();
            
            if ($module_manager) {
                $css_module = $module_manager->get_module('css_opt');
                if ($css_module instanceof CssOptimizeModule) {
                    $css_module->clear_css_cache();
                }
            }
        } catch (\Exception $e) {
            prorank_log('ProRank AdminBar: Failed to clear CSS cache - ' . $e->getMessage());
        }
        
        // Trigger cache cleared action
        do_action('prorank_css_cache_cleared');
    }
    
    /**
     * Clear HTML cache
     *
     * @return void
     */
    private function clear_html_cache(): void {
        delete_transient('prorank_html_cache_files');

        try {
            $plugin = \ProRank\SEO\Plugin::get_instance();
            $module_manager = $plugin->modules();

            if ($module_manager) {
                foreach (['modern_cache', 'cache'] as $slug) {
                    $cache_module = $module_manager->get_module($slug);
                    if (is_object($cache_module) && method_exists($cache_module, 'clear_all_cache')) {
                        $cache_module->clear_all_cache();
                    }
                }
            }
        } catch (\Exception $e) {
            prorank_log('ProRank AdminBar: Failed to clear HTML cache - ' . $e->getMessage());
        }

        if (function_exists('wp_cache_clear_cache')) {
            wp_cache_clear_cache();
        }

        do_action('prorank_html_cache_cleared');
    }
    
    /**
     * Clear CDN cache
     *
     * @return void
     */
    private function clear_cdn_cache(): void {
        $cdn = new CdnManager();
        $result = $cdn->purge_all();
        if (is_wp_error($result)) {
            $message = sanitize_text_field( wp_strip_all_tags( $result->get_error_message() ) );
            throw new \Exception( esc_html( $message ) );
        }
        do_action('prorank_cdn_cache_cleared', get_option('prorank_cdn_provider', 'none'));
    }
    
    /**
     * Clear all caches
     *
     * @return void
     */
    private function clear_all_cache(): void {
        // Clear CSS cache
        $this->clear_css_cache();
        
        // Clear HTML cache
        $this->clear_html_cache();
        
        // Clear CDN cache if configured
        $cdn_provider = get_option('prorank_cdn_provider', 'none');
        if ($cdn_provider !== 'none') {
            try {
                $this->clear_cdn_cache();
            } catch (\Exception $e) {
                // Log but don't fail the entire operation
                prorank_log('ProRank: Failed to clear CDN cache - ' . $e->getMessage());
            }
        }
        
        // Clear object cache
        wp_cache_flush();
        
        // Clear transients
        delete_transient('prorank_cache_stats');
        
        // Trigger action
        do_action('prorank_all_cache_cleared');
    }
    
    /**
     * Get cache statistics
     *
     * @return array|null
     */
    private function get_cache_statistics(): ?array {
        // Try to get from transient first
        $stats = get_transient('prorank_cache_stats');
        
        if ($stats === false) {
            $stats = [
                'total_size' => 0,
                'total_files' => 0,
            ];
            
            // Get CSS cache stats
            try {
                $plugin = \ProRank\SEO\Plugin::get_instance();
                $module_manager = $plugin->modules();
                
                if ($module_manager) {
                    $css_module = $module_manager->get_module('css_opt');
                    if ($css_module instanceof CssOptimizeModule) {
                        $css_stats = $css_module->get_cache_stats();
                        $stats['total_size'] += $css_stats['total_size'] ?? 0;
                        $stats['total_files'] += $css_stats['total_files'] ?? 0;
                    }
                }
            } catch (\Exception $e) {
                // Log error but don't break the admin bar
                prorank_log('ProRank AdminBar: Failed to get cache stats - ' . $e->getMessage());
            }
            
            // Cache for 5 minutes
            set_transient('prorank_cache_stats', $stats, 300);
        }
        
        return $stats;
    }
    
    /**
     * Handle AJAX debug toggle
     *
     * @return void
     */
    public function ajax_toggle_debug(): void {
        // Verify nonce
        if (!check_ajax_referer('prorank_toggle_debug', '_ajax_nonce', false)) {
            wp_send_json_error('Invalid security token');
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        // Toggle debug mode
        $current_debug = get_option('prorank_debug_mode', false);
        update_option('prorank_debug_mode', !$current_debug);
        
        wp_send_json_success([
            'debug_mode' => !$current_debug,
            'message' => !$current_debug ? __('Debug mode enabled', 'prorank-seo') : __('Debug mode disabled', 'prorank-seo'),
        ]);
    }

    /**
     * Handle post-level SEO changes triggered from the admin bar.
     */
    public function handle_post_seo_action(): void {
        $post_id = absint($_GET['post_id'] ?? 0);
        $operation = sanitize_key((string) ($_GET['operation'] ?? ''));
        $directive = sanitize_key((string) ($_GET['directive'] ?? ''));
        $return_url = $this->sanitize_return_url((string) ($_GET['return_url'] ?? ''));

        if ($post_id <= 0 || $operation === '') {
            wp_safe_redirect($return_url ?: admin_url());
            exit;
        }

        if (!current_user_can('edit_post', $post_id)) {
            wp_die(esc_html__('You are not allowed to update this content.', 'prorank-seo'));
        }

        $nonce = (string) ($_GET['_wpnonce'] ?? '');
        if ($nonce === '' || !wp_verify_nonce($nonce, $this->get_post_seo_nonce_action($post_id, $operation, $directive))) {
            wp_die(esc_html__('Invalid security token.', 'prorank-seo'));
        }

        switch ($operation) {
            case 'toggle_robot':
                if (in_array($directive, self::POST_ROBOTS_DIRECTIVES, true)) {
                    $robots = $this->normalize_meta_robots(get_post_meta($post_id, '_prorank_meta_robots', true));
                    if (in_array($directive, $robots, true)) {
                        $robots = array_values(array_diff($robots, [$directive]));
                    } else {
                        $robots[] = $directive;
                    }
                    update_post_meta($post_id, '_prorank_meta_robots', $this->normalize_meta_robots($robots));
                }
                break;

            case 'set_canonical':
                $canonical = esc_url_raw(trim(wp_unslash((string) ($_GET['canonical'] ?? ''))));
                if ($canonical === '') {
                    delete_post_meta($post_id, '_prorank_seo_canonical_url');
                } else {
                    update_post_meta($post_id, '_prorank_seo_canonical_url', $canonical);
                }
                break;
        }

        $redirect = $return_url ?: (get_edit_post_link($post_id, 'url') ?: admin_url());
        wp_safe_redirect($redirect);
        exit;
    }

    /**
     * Get SEO dashboard data from cache
     *
     * @return array
     */
    private function get_seo_dashboard_data(): array {
        // Check the cache first. The admin bar renders on every wp-admin and
        // every front-end request for logged-in users; calling out to the
        // cloud audit API on each request can block page load by tens of
        // seconds (it paginates and each page has a 30s timeout).
        $cached = get_transient(self::SEO_CACHE_KEY);
        if ($cached !== false && is_array($cached)) {
            return $cached;
        }

        $summary = $this->get_latest_completed_audit_summary();
        if ($summary === null) {
            $data = [
                'seo_score' => null,
                'issues_count' => 0,
            ];
        } else {
            $data = [
                'audit_id' => $summary['id'],
                'audit_source' => $summary['source'],
                'seo_score' => $summary['score'],
                'issues_count' => $summary['issues_total'],
            ];
        }

        set_transient(self::SEO_CACHE_KEY, $data, self::SEO_CACHE_TTL);

        return $data;
    }

    /**
     * Get latest completed audit summary (score + total issues).
     *
     * @return array{id: string, score: int, issues_total: int, source: string}|null
     */
    private function get_latest_completed_audit_summary(): ?array {
        $local = $this->get_latest_local_audit_summary();
        $cloud = $this->can_use_cloud_audit() ? $this->get_latest_cloud_audit_summary() : null;

        if ($local === null && $cloud === null) {
            return null;
        }

        if ($local === null) {
            return $cloud;
        }

        if ($cloud === null) {
            return $local;
        }

        return ($cloud['completed_at_ts'] ?? 0) > ($local['completed_at_ts'] ?? 0) ? $cloud : $local;
    }

    /**
     * Add contextual post/page SEO controls to the admin bar.
     */
    private function add_current_post_controls(\WP_Admin_Bar $wp_admin_bar, int $post_id): void {
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        $post = get_post($post_id);
        if (!$post instanceof \WP_Post) {
            return;
        }

        $meta_robots = $this->normalize_meta_robots(get_post_meta($post_id, '_prorank_meta_robots', true));
        $canonical_url = trim((string) get_post_meta($post_id, '_prorank_seo_canonical_url', true));
        $edit_url = get_edit_post_link($post_id, 'url') ?: admin_url('post.php?post=' . $post_id . '&action=edit');

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-seo',
            'id' => 'prorank-current-post-seo',
            'title' => '<span class="prorank-menu-icon">📝</span> ' . __('Current Post SEO', 'prorank-seo'),
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-current-post-seo',
            'id' => 'prorank-current-post-edit',
            'title' => __('Open Post Editor', 'prorank-seo'),
            'href' => $edit_url,
        ]);

        $wp_admin_bar->add_menu([
            'parent' => 'prorank-current-post-seo',
            'id' => 'prorank-current-post-canonical',
            'title' => sprintf(
                /* translators: %s: canonical state */
                __('Canonical: %s', 'prorank-seo'),
                $canonical_url !== '' ? __('Custom', 'prorank-seo') : __('Default', 'prorank-seo')
            ),
            'href' => '#',
            'meta' => [
                'onclick' => 'return prorankSetCanonical('
                    . wp_json_encode($this->get_post_seo_action_url($post_id, 'set_canonical'))
                    . ', ' . wp_json_encode($canonical_url) . ');',
            ],
        ]);

        foreach (['noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex'] as $directive) {
            $enabled = in_array($directive, $meta_robots, true);
            $wp_admin_bar->add_menu([
                'parent' => 'prorank-current-post-seo',
                'id' => 'prorank-current-post-' . $directive,
                'title' => sprintf(
                    /* translators: 1: robots directive label, 2: toggle state */
                    __('%1$s: %2$s', 'prorank-seo'),
                    $this->get_meta_robots_labels()[$directive] ?? $directive,
                    $enabled ? __('On', 'prorank-seo') : __('Off', 'prorank-seo')
                ),
                'href' => $this->get_post_seo_action_url($post_id, 'toggle_robot', ['directive' => $directive]),
            ]);
        }
    }

    /**
     * Resolve current post/page context for admin-bar SEO actions.
     */
    private function get_current_post_context_id(): int {
        if (is_admin()) {
            return absint($_GET['post'] ?? $_POST['post_ID'] ?? 0);
        }

        return is_singular() ? (int) get_queried_object_id() : 0;
    }

    /**
     * Build signed admin-post URL for post-level SEO actions.
     *
     * @param array<string,string> $args
     */
    private function get_post_seo_action_url(int $post_id, string $operation, array $args = []): string {
        $url = add_query_arg(
            array_merge(
                [
                    'action' => 'prorank_update_post_seo',
                    'post_id' => $post_id,
                    'operation' => $operation,
                    'return_url' => rawurlencode($this->get_current_request_url()),
                ],
                $args
            ),
            admin_url('admin-post.php')
        );

        return wp_nonce_url($url, $this->get_post_seo_nonce_action($post_id, $operation, $args['directive'] ?? ''));
    }

    /**
     * Current request URL for redirecting back after a post-level action.
     */
    private function get_current_request_url(): string {
        return home_url(wp_unslash((string) ($_SERVER['REQUEST_URI'] ?? '/')));
    }

    /**
     * Sanitize return URL to same-site targets only.
     */
    private function sanitize_return_url(string $return_url): string {
        return wp_validate_redirect(esc_url_raw(rawurldecode(wp_unslash($return_url))), '');
    }

    /**
     * Nonce action name for post-level SEO actions.
     */
    private function get_post_seo_nonce_action(int $post_id, string $operation, string $directive = ''): string {
        $action = 'prorank_post_seo_' . $post_id . '_' . $operation;
        if ($directive !== '') {
            $action .= '_' . $directive;
        }

        return $action;
    }

    /**
     * Normalize robots directives to the supported set.
     *
     * @param mixed $meta_robots
     * @return array<int,string>
     */
    private function normalize_meta_robots($meta_robots): array {
        if (!is_array($meta_robots)) {
            $meta_robots = empty($meta_robots) ? [] : (array) $meta_robots;
        }

        $normalized = array_map('sanitize_key', array_filter(array_map('strval', $meta_robots)));
        return array_values(array_intersect(self::POST_ROBOTS_DIRECTIVES, array_unique($normalized)));
    }

    /**
     * Labels for post-level robots directives.
     *
     * @return array<string,string>
     */
    private function get_meta_robots_labels(): array {
        return [
            'noindex' => __('No Index', 'prorank-seo'),
            'nofollow' => __('No Follow', 'prorank-seo'),
            'noarchive' => __('No Archive', 'prorank-seo'),
            'nosnippet' => __('No Snippet', 'prorank-seo'),
            'noimageindex' => __('No Image Index', 'prorank-seo'),
        ];
    }


    /**
     * Get the newest completed local audit summary.
     *
     * @return array{id: string, score: int, issues_total: int, source: string, completed_at_ts: int}|null
     */
    private function get_latest_local_audit_summary(): ?array {
        global $wpdb;
        $table_audits = $wpdb->prefix . 'prorank_audits';
        $table_issues = $wpdb->prefix . 'prorank_audit_issues';

        if (!$this->table_exists($table_audits)) {
            return null;
        }

        $audit_columns = $this->get_table_columns($table_audits);
        $order_by = $this->get_audit_order_by_clause($audit_columns);

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT *
                 FROM %i
                 WHERE status = %s
                 ORDER BY {$order_by}
                 LIMIT 1",
                $table_audits,
                'completed'
            )
        );

        if (!$row) {
            return null;
        }

        $audit_id = (string) ($row->audit_id ?? $row->id ?? '');
        if ($audit_id === '') {
            return null;
        }

        $score = is_numeric($row->score) ? (int) $row->score : null;
        if ($score === null) {
            return null;
        }

        $issues_total = 0;
        $decoded = [];
        if (!empty($row->stats)) {
            $raw = json_decode((string) $row->stats, true);
            if (is_array($raw)) {
                $decoded = $raw;
            }
        }

        if (isset($decoded['total_issues']) && is_numeric($decoded['total_issues'])) {
            $issues_total = (int) $decoded['total_issues'];
        }
        if ($issues_total <= 0) {
            if (isset($decoded['unique_issues']['total']) && is_numeric($decoded['unique_issues']['total'])) {
                $issues_total = (int) $decoded['unique_issues']['total'];
            } elseif (isset($decoded['unique_issues']) && is_numeric($decoded['unique_issues'])) {
                $issues_total = (int) $decoded['unique_issues'];
            }
        }

        if (
            $issues_total <= 0
            && $audit_id !== ''
            && $this->table_exists($table_issues)
        ) {
            $issues_total = (int) $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*)
                     FROM %i
                     WHERE audit_id = %s
                     AND severity IN ('critical','high','medium','low')",
                    $table_issues,
                    $audit_id
                )
            );
        }

        $completed_at = $row->completed_at ?? $row->end_time ?? $row->started_at ?? $row->start_time ?? null;

        return [
            'id' => $audit_id,
            'score' => $score,
            'issues_total' => $issues_total,
            'source' => 'local',
            'completed_at_ts' => $this->get_audit_timestamp($completed_at),
        ];
    }

    /**
     * Get the newest completed cloud audit summary.
     *
     * @return array{id: string, score: int, issues_total: int, source: string, completed_at_ts: int}|null
     */
    private function get_latest_cloud_audit_summary(): ?array {
        return null;
    }

    /**
     * Check whether a table exists.
     *
     * @param string $table_name Database table name.
     * @return bool
     */
    private function table_exists(string $table_name): bool {
        global $wpdb;

        return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name)) === $table_name;
    }

    /**
     * Get column names for a table.
     *
     * @param string $table_name Database table name.
     * @return array<int,string>
     */
    private function get_table_columns(string $table_name): array {
        global $wpdb;

        $columns = $wpdb->get_col("SHOW COLUMNS FROM `{$table_name}`", 0);
        if (!is_array($columns)) {
            return [];
        }

        return array_map('strval', $columns);
    }

    /**
     * Build an ORDER BY clause that matches the available local audit columns.
     *
     * @param array<int,string> $columns Table column names.
     * @return string
     */
    private function get_audit_order_by_clause(array $columns): string {
        $completed_candidates = [];
        $started_candidates = [];

        if (in_array('completed_at', $columns, true)) {
            $completed_candidates[] = 'completed_at';
        }
        if (in_array('end_time', $columns, true)) {
            $completed_candidates[] = 'end_time';
        }
        if (in_array('started_at', $columns, true)) {
            $completed_candidates[] = 'started_at';
            $started_candidates[] = 'started_at';
        }
        if (in_array('start_time', $columns, true)) {
            $completed_candidates[] = 'start_time';
            $started_candidates[] = 'start_time';
        }

        $parts = [];
        if ($completed_candidates !== []) {
            $parts[] = 'COALESCE(' . implode(', ', $completed_candidates) . ') DESC';
        }
        if ($started_candidates !== []) {
            $parts[] = 'COALESCE(' . implode(', ', $started_candidates) . ') DESC';
        }
        if (in_array('id', $columns, true)) {
            $parts[] = 'id DESC';
        } elseif (in_array('audit_id', $columns, true)) {
            $parts[] = 'audit_id DESC';
        }

        return $parts === [] ? '1 DESC' : implode(', ', $parts);
    }

    /**
     * Normalize a date/time value to a Unix timestamp.
     *
     * @param mixed $value Date/time value.
     * @return int
     */
    private function get_audit_timestamp($value): int {
        if ($value instanceof \DateTimeInterface) {
            return $value->getTimestamp();
        }

        if (!is_scalar($value) || $value === '') {
            return 0;
        }

        $timestamp = strtotime((string) $value);

        return $timestamp !== false ? (int) $timestamp : 0;
    }

    /**
     * Get score class for styling
     *
     * @param int $score SEO score
     * @return string CSS class name
     */
    private function get_score_class(int $score): string {
        if ($score >= 80) return 'good';
        if ($score >= 50) return 'ok';
        return 'poor';
    }

    /**
     * Get score label text
     *
     * @param int $score SEO score
     * @return string Human-readable label
     */
    private function get_score_label(int $score): string {
        if ($score >= 90) return __('Excellent', 'prorank-seo');
        if ($score >= 80) return __('Good', 'prorank-seo');
        if ($score >= 60) return __('Fair', 'prorank-seo');
        if ($score >= 40) return __('Needs Work', 'prorank-seo');
        return __('Poor', 'prorank-seo');
    }
}
