<?php
/**
 * Admin Page Settings
 *
 * Main admin interface for Mamba Cache including menu registration,
 * tab rendering, Store API caching, and settings management.
 *
 * @package Mamba\Settings
 * @since   1.0.0
 */

namespace Mamba\Settings;

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

use Mamba\Support\Paths;
use Mamba\Modules\Caching\Services\StoreApiFileCache;

/**
 * Class AdminPage
 *
 * Manages the plugin admin interface including menu registration,
 * asset enqueuing, Store API REST caching, and AJAX settings handlers.
 *
 * @since 1.0.0
 */
final class AdminPage {
    private string $slug = 'mamba';
    public function __construct(private Paths $paths) {}
    public function register(): void {
        add_action('admin_menu', [$this, 'registerMenu']);
        // Ensure dashboard is the first submenu under 'mamba' to avoid WP redirecting to another child
        add_action('admin_menu', [$this, 'ensureDashboardFirst'], 100);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
        add_action('admin_notices', [$this, 'displayCompatibilityWarnings']);
        
        // Register generic AJAX handler for live settings save
        add_action('wp_ajax_mamba_save_setting', [$this, 'handleSaveSetting']);
        // Woo Store API REST cache (early serve + store)
        add_filter('rest_pre_dispatch', [$this, 'maybeServeRestCache'], 10, 3);
        add_filter('rest_request_after_callbacks', [$this, 'maybeStoreRestCache'], 10, 3);
        // Store API preloading for zero round-trip start
        add_action('wp_enqueue_scripts', [$this, 'maybePreloadStoreApi'], 100);
        // REST endpoint: cache status
        add_action('rest_api_init', function() {
            register_rest_route('mamba-wc/v1', '/cache-status', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiCacheStatus'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            register_rest_route('mamba-wc/v1', '/warmup', [
                'methods'  => 'POST',
                'callback' => [$this, 'apiWarmup'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            register_rest_route('mamba-wc/v1', '/warmup-status', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiWarmupStatus'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            register_rest_route('mamba-wc/v1', '/warmup-cancel', [
                'methods'  => 'POST',
                'callback' => [$this, 'apiWarmupCancel'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            
            register_rest_route('mamba-wc/v1', '/warmup-resume', [
                'methods'  => 'POST',
                'callback' => [$this, 'apiWarmupResume'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            
            register_rest_route('mamba-wc/v1', '/warmup-errors', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiWarmupErrors'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            
            register_rest_route('mamba-wc/v1', '/background-warmup', [
                'methods'  => 'POST',
                'callback' => [$this, 'apiBackgroundWarmup'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            
            register_rest_route('mamba-wc/v1', '/background-jobs', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiBackgroundJobs'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);
            
            register_rest_route('mamba-wc/v1', '/stats', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiStats'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);

            // Cache counts (products/categories/etc.)
            register_rest_route('mamba-wc/v1', '/cache-counts', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiCacheCounts'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);

            // Purge endpoints
            register_rest_route('mamba-wc/v1', '/purge', [
                'methods'  => 'POST',
                'callback' => [$this, 'apiPurge'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);

            register_rest_route('mamba-wc/v1', '/purge-stats', [
                'methods'  => 'GET',
                'callback' => [$this, 'apiPurgeStats'],
                'permission_callback' => function(){ return current_user_can('manage_options') || current_user_can('manage_woocommerce'); },
            ]);

        });
    }
    /**
     * Make sure the first submenu item under 'mamba' points to the dashboard (slug 'mamba').
     * This prevents WP from redirecting the top-level menu click to another submenu (e.g., license).
     */
    public function ensureDashboardFirst(): void {
        global $submenu;
        if (!isset($submenu[$this->slug]) || !is_array($submenu[$this->slug])) return;
        $items = $submenu[$this->slug];
        $dashIndex = null;
        foreach ($items as $i => $item) {
            // $item structure: [0] => title, [1] => capability, [2] => slug, [3] => page title
            if (isset($item[2]) && $item[2] === $this->slug) { $dashIndex = $i; break; }
        }
        if ($dashIndex === null) return;
        // Move dashboard entry to the top (index 0)
        $dashboard = $items[$dashIndex];
        unset($items[$dashIndex]);
        array_unshift($items, $dashboard);
        // reindex and assign back
        $submenu[$this->slug] = array_values($items);
    }

    public function displayCompatibilityWarnings(): void {
        if (!current_user_can('manage_options')) return;
        // Check for WP Rocket
        if (defined('WP_ROCKET_VERSION') || class_exists('WP_Rocket\Plugin')) {
             ?>
             <div class="notice notice-warning is-dismissible">
                 <p>
                     <strong><?php echo esc_html( __('Mamba Conflict Detected', 'mamba-cache-for-woocommerce') ); ?></strong>: 
                     <?php echo esc_html( __('WP Rocket is active. Running two caching plugins simultaneously can cause conflicts and unexpected behavior. We recommend disabling WP Rocket\'s caching features or the plugin entirely, as Mamba handles page caching, optimization, and preloading.', 'mamba-cache-for-woocommerce') ); ?>
                 </p>
             </div>
             <?php
        }
    }

    public function registerMenu(): void {
        $cap = current_user_can('manage_options') ? 'manage_options' : 'manage_woocommerce';
        $cap = apply_filters('mamba_admin_capability', $cap);
        add_menu_page(
            __('Mamba', 'mamba-cache-for-woocommerce'),
            __('Mamba', 'mamba-cache-for-woocommerce'),
            $cap,
            $this->slug,
            [$this, 'renderPage'],
            'dashicons-performance', // Use WordPress dashicon for speed/performance
            6 // Position in the menu
        );
        // Add a submenu entry pointing to the parent page to prevent WP from redirecting to the first child submenu by default
        add_submenu_page(
            $this->slug,
            __('Dashboard', 'mamba-cache-for-woocommerce'),
            __('Dashboard', 'mamba-cache-for-woocommerce'),
            $cap,
            $this->slug,
            [$this, 'renderPage']
        );
        // Settings fields via options API (lightweight)
        add_action('admin_init', function(){
            register_setting('mamba_cache', 'mamba_preload_concurrency', ['type'=>'integer','sanitize_callback'=>'absint','default'=>5]);
            register_setting('mamba_cache', 'mamba_warmup_batch_size', ['type'=>'integer','sanitize_callback'=>'absint','default'=>25]);
            register_setting('mamba_cache', 'mamba_browser_ttl', ['type'=>'integer','sanitize_callback'=>'absint','default'=>300]);
            register_setting('mamba_cache', 'mamba_store_api_browser_ttl', ['type'=>'integer','sanitize_callback'=>'absint','default'=>300]);
            register_setting('mamba_cache', 'mamba_store_api_ttl', ['type'=>'integer','sanitize_callback'=>'absint','default'=>600]);
            register_setting('mamba_cache', 'mamba_cache_size_limit', ['type'=>'integer','sanitize_callback'=>'absint','default'=>200*1024*1024]);
            register_setting('mamba_cache', 'mamba_cdn_ttl', ['type'=>'integer','sanitize_callback'=>'absint','default'=>7200]);
            register_setting('mamba_cache', 'mamba_stale_if_error', ['type'=>'integer','sanitize_callback'=>'absint','default'=>86400]);
            register_setting('mamba_cache', 'mamba_include_accept_language_vary', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>true]);
            register_setting('mamba_cache', 'mamba_disable_wc_assets_on_non_wc', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_simplify_price_html', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_enable_hover_prefetch', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            
            // Cache size limit setting
            // Checkout optimization settings
            register_setting('mamba_cache', 'mamba_optimize_checkout_js', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_optimize_checkout_css', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_disable_checkout_fragments', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_lazy_load_payments', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_defer_transactional_emails', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_preconnect_payment_sdks', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            
            register_setting('mamba_cache', 'mamba_disable_order_attribution', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            
            // Media optimization settings
            register_setting('mamba_cache', 'mamba_enable_lcp_optimization', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
    
            register_setting('mamba_cache', 'mamba_enable_image_compression', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_compression_quality', ['type'=>'integer','sanitize_callback'=>'absint','default'=>85]);
            register_setting('mamba_cache', 'mamba_compress_full_size', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_enable_webp_conversion', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_webp_quality', ['type'=>'integer','sanitize_callback'=>'absint','default'=>85]);
            register_setting('mamba_cache', 'mamba_convert_full_size', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            
            // AVIF conversion settings
            register_setting('mamba_cache', 'mamba_enable_avif_conversion', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_avif_quality', ['type'=>'integer','sanitize_callback'=>'absint','default'=>65]);
            register_setting('mamba_cache', 'mamba_convert_full_size_avif', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            
            // HTML/CSS/JS minification settings (Performance/Bloat tab)
            register_setting('mamba_cache', 'mamba_enable_html_minify', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_html_minify_mode', ['type'=>'string','sanitize_callback'=>'sanitize_text_field','default'=>'conservative']);
            
            // Critical CSS settings
            register_setting('mamba_cache', 'mamba_enable_critical_css', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_enable_css_defer', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_css_defer_all', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_critical_css_force_include', ['type'=>'string','sanitize_callback'=>'sanitize_textarea_field','default'=>'']);
            
            // JavaScript Delay settings
            register_setting('mamba_cache', 'mamba_enable_js_delay', ['type'=>'boolean','sanitize_callback'=>'rest_sanitize_boolean','default'=>false]);
            register_setting('mamba_cache', 'mamba_js_delay_timeout', ['type'=>'integer','sanitize_callback'=>'absint','default'=>5000]);
            register_setting('mamba_cache', 'mamba_js_delay_scripts', ['type'=>'string','sanitize_callback'=>'sanitize_textarea_field','default'=>'']);
            register_setting('mamba_cache', 'mamba_js_delay_exclusions', ['type'=>'string','sanitize_callback'=>'sanitize_textarea_field','default'=>'']);
        });
    }
    public function enqueueAssets(string $hook): void {
        $onPage = (strpos($hook, $this->slug) !== false) || (isset($_GET['page']) && sanitize_key(wp_unslash($_GET['page'])) === $this->slug);
        
        // Always load minimal CSS for notices on all admin pages
        wp_enqueue_style('mamba-admin-notices', $this->paths->adminCss('mamba-admin.css'), [], '1.0.0');
        
        // Always load the JS for View Log handler on all admin pages (minimal overhead)
        wp_enqueue_script('mamba-admin', $this->paths->adminJs('mamba-admin.js'), ['jquery'], '1.0.0', true);
        wp_localize_script('mamba-admin', 'MambaAdmin', [
            'warmupEndpoint' => rest_url('mamba-wc/v1/warmup'),
            'nonce' => wp_create_nonce('wp_rest'),
            'saveNonce' => wp_create_nonce('mamba_save_setting'),
            'cacheEnabled' => (bool) get_option('mamba_enable_page_cache', 0),
            'adminUrl' => admin_url(),
            'i18n' => [
                'cachingSetupTitle' => __('Quick Start: Enable Caching', 'mamba-cache-for-woocommerce'),
                'cachingSetupMessage' => __('Great! Your license is now active. To get the most out of Mamba, enable caching for optimal WooCommerce performance.', 'mamba-cache-for-woocommerce'),
                'cachingSetupSubtitle' => __('Caching will significantly improve your store\'s loading speed and reduce server load.', 'mamba-cache-for-woocommerce'),
                'goToCaching' => __('Go to Caching Settings', 'mamba-cache-for-woocommerce'),
                'maybeLater' => __('Maybe Later', 'mamba-cache-for-woocommerce'),
            ],
        ]);
        
        // Only load full assets on Mamba plugin pages
        if (!$onPage) return;
        wp_enqueue_style('google-font-inter', 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap', [], '1.0.0');
        wp_enqueue_style('mamba-metrics',$this->paths->adminCss('mamba-metrics-dashboard.css'), [], '1.0.0');
        
        // Load WooCommerce's Select2 for enhanced multi-selects (if WooCommerce is active)
        if (function_exists('WC')) {
            wp_enqueue_style('woocommerce_admin_styles');
            wp_enqueue_script('wc-enhanced-select');
        }
        
        // Enqueue tab-specific JavaScript with localized data
        wp_enqueue_script('mamba-tabs', $this->paths->adminJs('mamba-tabs.js'), ['jquery', 'mamba-admin'], '1.0.0', true);
        
        // Localize script with tab-specific data
        $current_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'dashboard';
        $tabs_data = [
            'currentTab' => $current_tab,
            'ajaxurl' => admin_url('admin-ajax.php'),
        ];
        
        // Add tab-specific nonces and i18n
        if ($current_tab === 'logs') {
            $tabs_data['logs'] = [
                'nonce' => wp_create_nonce('mamba_logs'),
                'i18n' => [
                    'settingsSaved' => __('Settings saved successfully', 'mamba-cache-for-woocommerce'),
                    'errorSaving' => __('Error saving settings', 'mamba-cache-for-woocommerce'),
                    'exportSuccess' => __('Logs exported successfully', 'mamba-cache-for-woocommerce'),
                    'exportError' => __('Error exporting logs', 'mamba-cache-for-woocommerce'),
                    'confirmClear' => __('Are you sure you want to delete all log files? This cannot be undone.', 'mamba-cache-for-woocommerce'),
                    'clearError' => __('Error clearing logs', 'mamba-cache-for-woocommerce'),
                    'loading' => __('Loading logs...', 'mamba-cache-for-woocommerce'),
                    'errorLoading' => __('Error loading logs', 'mamba-cache-for-woocommerce'),
                    'noEntries' => __('No log entries found', 'mamba-cache-for-woocommerce'),
                ],
            ];
        }
        
        if ($current_tab === 'cdn') {
            $tabs_data['cdn'] = [
                'nonce' => wp_create_nonce('mamba_cdn_nonce'),
                'i18n' => [
                    'testing' => __('Testing...', 'mamba-cache-for-woocommerce'),
                    'testConnection' => __('Test Connection', 'mamba-cache-for-woocommerce'),
                    'testUrlPurge' => __('Test URL Purge', 'mamba-cache-for-woocommerce'),
                    'testTagPurge' => __('Test Tag Purge', 'mamba-cache-for-woocommerce'),
                    'confirmApply' => __('This will apply recommended Cloudflare settings. Continue?', 'mamba-cache-for-woocommerce'),
                    'applying' => __('Applying...', 'mamba-cache-for-woocommerce'),
                    'applySettings' => __('Apply Settings', 'mamba-cache-for-woocommerce'),
                    'requestFailed' => __('Request failed', 'mamba-cache-for-woocommerce'),
                ],
            ];
        }
        
        if ($current_tab === 'db') {
            $tabs_data['db'] = [
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('mamba_db_optimize'),
            ];
        }
        
        if ($current_tab === 'caching') {
            $tabs_data['caching'] = [
                'nonce' => wp_create_nonce('mamba_cache_settings'),
            ];
        }
        
        if ($current_tab === 'overhead') {
            $tabs_data['overhead'] = [
                'nonce' => wp_create_nonce('mamba_overhead_settings'),
            ];
        }
        
        if ($current_tab === 'media') {
            $tabs_data['media'] = [
                'nonce' => wp_create_nonce('mamba_media_nonce'),
                'i18n' => [
                    'starting' => __('Starting conversion...', 'mamba-cache-for-woocommerce'),
                    'error' => __('Error', 'mamba-cache-for-woocommerce'),
                    'networkError' => __('Network error', 'mamba-cache-for-woocommerce'),
                ],
            ];
        }
        
        wp_localize_script('mamba-tabs', 'MambaTabs', $tabs_data);
        
        // Add theme initialization inline script (must run early to prevent flash)
        wp_add_inline_script('mamba-admin', '(function(){var t=localStorage.getItem("mamba_theme")||"dark";document.body.setAttribute("data-mamba-theme",t);})();', 'before');
        
        // Add dark mode override styles
        $darkmode_css = '[data-mamba-theme="dark"] .mamba-backend-item,
            [data-mamba-theme="dark"] .mamba-flush-action,
            [data-mamba-theme="dark"] .mamba-info-card,
            [data-mamba-theme="dark"] .mamba-form-section:first-of-type,
            [data-mamba-theme="dark"] .mamba-performance-card,
            [data-mamba-theme="dark"] .mamba-server-support-item,
            [data-mamba-theme="dark"] .mamba-nginx-config,
            [data-mamba-theme="dark"] .mamba-status-card,
            [data-mamba-theme="dark"] .mamba-system-card {
                background: transparent !important;
                border-color: rgba(255,255,255,0.06) !important;
                box-shadow: none !important;
            }
            [data-mamba-theme="dark"] .mamba-backend-item,
            [data-mamba-theme="dark"] .mamba-flush-action,
            [data-mamba-theme="dark"] .mamba-info-card {
                padding: 16px;
            }
            .mamba-admin-wrap .notice {
                font-size: 14px;
                margin-top: 12px;
            }
            .mamba-admin-wrap .notice p { margin:0; padding:6px 12px; font-size:14px; }
            .mamba-admin-wrap #footer-thankyou { display: none !important; }';
        wp_add_inline_style('mamba-admin-notices', $darkmode_css);
        
        // Add Freemius notice styling script
        $freemius_fix_js = 'document.addEventListener("DOMContentLoaded",function(){try{if(!document.querySelector(".mamba-admin-wrap"))return;var notices=Array.from(document.querySelectorAll(".notice"));notices.forEach(function(n){var txt=(n.textContent||"").toLowerCase();if(txt.indexOf("yee-haw")!==-1||(txt.indexOf("license")!==-1&&txt.indexOf("activated")!==-1)){n.classList.add("mamba-freemius-notice","mamba-success-notice");n.style.cssText="background:linear-gradient(135deg,rgba(16,185,129,0.1) 0%,rgba(5,150,105,0.08) 100%);border:1px solid rgba(16,185,129,0.3);border-left:4px solid #10B981;border-radius:8px;padding:16px 20px;margin:16px 0;font-size:14px;color:#065f46;display:flex;align-items:center;gap:12px;box-shadow:0 2px 8px rgba(16,185,129,0.15);";var icon=document.createElement("span");icon.innerHTML=\'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10B981" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>\';icon.style.cssText="flex-shrink:0;display:flex;align-items:center;";n.insertBefore(icon,n.firstChild);var p=n.querySelector("p");if(p){p.style.cssText="margin:0;font-weight:500;color:#065f46;";}var header=document.querySelector(".mamba-main-content header");if(header&&header.parentNode){header.parentNode.insertBefore(n,header.nextSibling);}}});}catch(e){console&&console.error&&console.error("Mamba freemius reposition error",e);}});';
        wp_add_inline_script('mamba-admin', $freemius_fix_js);
    }
    public function renderPage(): void {
        $tabs = [
            'dashboard' => ['title'=>__('Dashboard','mamba-cache-for-woocommerce'),'icon'=>'dashicons-dashboard'],
            'caching'   => ['title'=>__('Caching','mamba-cache-for-woocommerce'),'icon'=>'dashicons-update'],
            'object-cache' => ['title'=>__('Cache Backend','mamba-cache-for-woocommerce'),'icon'=>'dashicons-performance'],
            'cdn'       => ['title'=>__('CDN','mamba-cache-for-woocommerce'),'icon'=>'dashicons-networking'],
            'overhead'  => ['title'=>__('Performance','mamba-cache-for-woocommerce'),'icon'=>'dashicons-hammer'],
            'media'     => ['title'=>__('Media','mamba-cache-for-woocommerce'),'icon'=>'dashicons-format-image'],
            'db'        => ['title'=>__('Database','mamba-cache-for-woocommerce'),'icon'=>'dashicons-database'],
            'savings'   => ['title'=>__('Savings','mamba-cache-for-woocommerce'),'icon'=>'dashicons-chart-area'],
            'logs'      => ['title'=>__('Logs','mamba-cache-for-woocommerce'),'icon'=>'dashicons-media-text'],
            'status'    => ['title'=>__('Status','mamba-cache-for-woocommerce'),'icon'=>'dashicons-chart-bar'],
        ];
        $current = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'dashboard';
        // Back-compat: map legacy 'settings' slug to new 'status'
        if ($current === 'settings') { $current = 'status'; }
        
        // Get plugin version
        $plugin_data = get_file_data($this->paths->base().'mamba-woo-cache.php', ['Version'=>'Version']);
        $version = $plugin_data['Version'] ?? '';
        
        // Cache type detection with user-friendly messaging
        $hasObjectCache = false;
        $cacheType = 'File Cache';
        $cacheStatus = 'fallback';
        $cacheIcon = 'dashicons-database';
        
        if (class_exists('\Mamba\Support\ObjectCache')) {
            try {
                $hasObjectCache = \Mamba\Support\ObjectCache::hasPersistentCache();
                $rawCacheType = \Mamba\Support\ObjectCache::getCacheType();
                
                if ($hasObjectCache) {
                    $cacheStatus = 'active';
                    $cacheIcon = 'dashicons-performance';
                    
                    // User-friendly cache type names
                    switch (strtolower($rawCacheType)) {
                        case 'redis':
                            $cacheType = 'Redis';
                            break;
                        case 'memcached':
                            $cacheType = 'Memcached';
                            break;
                        case 'object cache':
                            $cacheType = 'Object Cache';
                            break;
                        default:
                            $cacheType = $rawCacheType;
                    }
                }
            } catch (\Exception $e) {
                $hasObjectCache = false;
                $cacheType = 'File Cache';
                $cacheStatus = 'fallback';
                $cacheIcon = 'dashicons-database';
            }
        }

        echo '<div class="wrap mamba-admin mamba-cyber-theme">';
        
        // --- LEFT SIDEBAR ---
        echo '<div class="mamba-sidebar">';
            echo '<div class="mamba-brand">';
                echo '<img src="'.esc_url($this->paths->url().'admin/images/mamba-logo.svg').'" alt="Mamba" class="mamba-logo" />';
                echo '<div class="mamba-brand-text">';
                    echo '<div class="mamba-brand-title">';
                        echo '<span class="mamba-name">Mamba</span>';
                        // Only show Pro badge when premium license is active
                        if (function_exists('mamba_fs') && mamba_fs()->can_use_premium_code__premium_only()) {
                            echo '<span class="mamba-badge">Pro</span>';
                        }
                    echo '</div>';
                    if (!empty($version)) {
                        echo '<div class="mamba-version">Version '.esc_html($version).'</div>';
                    }
                echo '</div>';
            echo '</div>';

            echo '<nav class="mamba-nav">';
            foreach ($tabs as $key=>$meta) {
                $active = $key === $current ? ' active' : '';
                $url = admin_url('admin.php?page='.$this->slug.'&tab='.$key);
                printf('<a class="mamba-nav-item%s" href="%s"><span class="dashicons %s"></span><span class="nav-label">%s</span></a>',
                    esc_attr($active), esc_url($url), esc_attr($meta['icon']), esc_html($meta['title']));
            }
            echo '</nav>';
            
            // Sidebar Footer (Cache Status)
            echo '<div class="mamba-sidebar-footer">';
                 echo '<div class="mamba-theme-toggle" id="mamba-theme-toggle">';
                    echo '<span class="toggle-label">'.esc_html( __('Theme', 'mamba-cache-for-woocommerce') ).'</span>';
                    echo '<span class="dashicons dashicons-lightbulb"></span>';
                 echo '</div>';
                 
                 echo '<div class="mamba-mini-status '.esc_attr($cacheStatus).'">';
                    echo '<span class="dashicons '.esc_attr($cacheIcon).'"></span>';
                    echo '<div class="status-details">';
                        echo '<span class="label">Engine</span>';
                        echo '<span class="value">'.esc_html($cacheType).'</span>';
                    echo '</div>';
                    echo '<div class="status-led"></div>';
                 echo '</div>';
                 
                 echo '<a href="https://mambaspeed.com/documentation/" target="_blank" rel="noopener" class="mamba-mini-status mamba-docs-link">';
                    echo '<span class="dashicons dashicons-book"></span>';
                    echo '<div class="status-details">';
                        echo '<span class="label">'.esc_html( __('Help & Guides', 'mamba-cache-for-woocommerce') ).'</span>';
                        echo '<span class="value">'.esc_html( __('Documentation', 'mamba-cache-for-woocommerce') ).'</span>';
                    echo '</div>';
                    echo '<span class="dashicons dashicons-external" style="font-size: 14px; opacity: 0.6;"></span>';
                 echo '</a>';
            echo '</div>';
        echo '</div>'; // End Sidebar

        // --- MAIN CONTENT AREA ---
        echo '<div class="mamba-main-content">';
        
            // Top Bar
            echo '<header class="mamba-topbar">';
                echo '<h1 class="page-title">'.esc_html($tabs[$current]['title']).'</h1>';
                
                // Actions
                echo '<div class="mamba-header-actions">';
                    echo '  <form method="post" action="'.esc_url(admin_url('admin.php?page='.$this->slug.'&tab=caching')).'" style="display:inline;">';
                    wp_nonce_field('mamba_cache_settings', 'mamba_cache_settings_nonce');
                    echo '    <input type="hidden" name="mamba_action" value="purge" />';
                    echo '    <button class="button button-secondary mamba-purge-btn" type="submit">';
                    echo '      <span class="dashicons dashicons-trash"></span>';
                    echo '      <span class="btn-text">'.esc_html( __('Purge & Warm All', 'mamba-cache-for-woocommerce') ).'</span>';
                    echo '    </button>';
                    echo '  </form>';
                    
                    echo '  <button class="button button-primary mamba-warmup-btn" data-mamba-warmup="1" type="button">';
                    echo '    <span class="dashicons dashicons-update"></span>';
                    echo '    <span class="btn-text">'.esc_html( __('Warmup', 'mamba-cache-for-woocommerce') ).'</span>';
                    echo '  </button>';
                echo '</div>';
            echo '</header>';

            // Content Body
            echo '<div class="mamba-content-body" data-tab="'.esc_attr($current).'">';
                // Handle object-cache tab specifically
                if ($current === 'object-cache') {
                    include $this->paths->base() . 'src/Modules/Caching/views/TabObjectCache.php';
                } elseif ($current === 'cdn') {
                    include $this->paths->base() . 'src/Modules/CDN/views/TabCdn.php';
                } else {
                    do_action('mamba/admin/tab/'.$current, $this->paths);
                }
            echo '</div>';
            
        echo '</div>'; // End Main Content
        
        echo '</div>'; // End Wrapper
    }
    // REST Store API cache
    public function maybeServeRestCache($result, $server, $request) {
        // Store API Caching is a Premium feature - requires both option enabled AND premium license
        if (!get_option('mamba_enable_store_api_cache', 0)) return $result;
        if (!function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only()) return $result;
        
        if (is_user_logged_in()) return $result;
        if (method_exists($request, 'get_method') && strtoupper($request->get_method()) !== 'GET') return $result;
        $route = $request->get_route();
        // Support both Store API and Blocks API
    $isStoreApi = strpos($route, '/wc/store/') === 0;
    $isBlocksApi = strpos($route, '/wc/blocks/') === 0;
    
    if (!$isStoreApi && !$isBlocksApi) return $result;
        
        // Skip warmup requests from cache serving (let them generate fresh content)
        if ($this->isWarmupRequest()) {
            return $result;
        }
        
        // Check for cart hash for microcaching
        $cartHash = $this->getCartHash();
        
        if ($cartHash) {
            // Per-cart microcache (3 seconds) for users with cart items
            $ver = (int) get_transient('mamba_mc_ver_' . md5($cartHash));
            $key = $route . '|' . wp_json_encode($request->get_query_params()) . '|cart_' . $cartHash . '|v' . $ver;
            $microTtl = 3; // 3 seconds microcache TTL
            
            // FIX: Use unified StoreApiFileCache serving logic
            $resp = StoreApiFileCache::serveCache($key, $microTtl, $route, $request->get_query_params(), true); // true = microcache
            if ($resp !== null) {
                return $resp;
            }
        } else {
            // Existing catalog caching logic for users without cart items
            if ($this->hasCartIntent()) return $result;
            
            // Check if route is cacheable (safe allowlist approach)
            if (!$this->isStoreApiRouteCacheable($route)) return $result;
            
            // Normalize parameters to match WooCommerce Store API schema for cache key consistency
            $rawParams = $request->get_query_params();
            $normalizedParams = $this->normalizeStoreApiParams($rawParams);
            $key = $route . '|' . wp_json_encode($normalizedParams) . '|' . $this->getVarianceSignature($rawParams);
            $ttl = (int)get_option('mamba_store_api_ttl', 600);
            
            // Use unified StoreApiFileCache serving logic
            $resp = StoreApiFileCache::serveCache($key, $ttl, $route, $request->get_query_params());
            if ($resp !== null) {
                return $resp;
            }
        }
        
        return $result;
    }
    public function maybeStoreRestCache($response, $handler, $request) {
        // Store API Caching is a Premium feature - requires both option enabled AND premium license
        if (!get_option('mamba_enable_store_api_cache', 0)) return $response;
        if (!function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only()) return $response;
        
        if (is_user_logged_in() || is_wp_error($response)) return $response;
        if (method_exists($request, 'get_method') && strtoupper($request->get_method()) !== 'GET') return $response;

        $route = $request->get_route();
        if (strpos($route, '/wc/store/') !== 0) return $response;
        if (strpos($route, '/mamba-wc/') === 0) return $response;

        $isWarmup = $this->isWarmupRequest();
        $startTime = microtime(true);
        
        // Check for cart hash for microcaching
        $cartHash = $this->getCartHash();
        
        if ($cartHash) {
            // Store microcache (3 seconds) for users with cart items
            $ver = (int) get_transient('mamba_mc_ver_' . md5($cartHash));
            $key = $route . '|' . wp_json_encode($request->get_query_params()) . '|cart_' . $cartHash . '|v' . $ver;
            $microTtl = 3; // 3 seconds microcache TTL
        } else {
            // Existing catalog caching logic for users without cart items
            if ($this->hasCartIntent()) return $response;
            if (!$this->isStoreApiRouteCacheable($route)) return $response;
            
            // Normalize parameters to match WooCommerce Store API schema for cache key consistency
            $rawParams = $request->get_query_params();
            $normalizedParams = $this->normalizeStoreApiParams($rawParams);
            $key = $route . '|' . wp_json_encode($normalizedParams) . '|' . $this->getVarianceSignature($rawParams);
            $microTtl = (int)get_option('mamba_store_api_ttl', 600);
        }
        
        // Use unified StoreApiFileCache storing logic
        StoreApiFileCache::storeCache($key, $response, $microTtl, $isWarmup, ($cartHash !== null)); // accurate MICRO vs MISS labeling

        // Metrics
        $genMs = (int)round((microtime(true) - $startTime) * 1000);
        if (!$isWarmup) {
            \Mamba\Modules\Caching\Services\Stats::recordMiss('store_api', $genMs);
        }
        return $response;
    }
    
    /**
     * Check if user has cart intent (actual cart items, not just session presence)
     */
    private function hasCartIntent(): bool {
        // Skip cart detection for warmup bot requests
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
        if (strpos($userAgent, 'Mamba Cache Warmup Bot') !== false) {
            return false; // Warmup bot should never have cart items
        }
        
        // Check cart-related cookies by specific key (avoid iterating full $_COOKIE stack)
        $cartCookies = ['woocommerce_items_in_cart', 'woocommerce_cart_hash', 'store_api_cart_hash'];
        foreach ($cartCookies as $cookie) {
            if (isset($_COOKIE[$cookie]) && $_COOKIE[$cookie] !== '' && $_COOKIE[$cookie] !== 'empty') {
                return true;
            }
        }
        
        // Only check WooCommerce cart state if cookies don't indicate cart presence (fallback)
        if (function_exists('WC') && WC()->session) {
            try {
                if (WC()->cart && !WC()->cart->is_empty()) return true;
                $session_cart = WC()->session->get('cart'); 
                if (!empty($session_cart)) return true;
            } catch (\Exception $e) { 
                // Log exception for debugging but don't assume cart presence
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('Mamba: Store API cart detection exception: ' . $e->getMessage());
                }
                return false; // Don't assume cart presence on error
            }
        }
        
        return false;
    }
    
    /**
     * Check if a Store API route is safe to cache (regex-based approach)
     * Prevents accidental caching of user-scoped data
     */
    private function isStoreApiRouteCacheable(string $route): bool {
        // Normalize to relative route: strip `/wp-json` & `/wc/store|blocks/v{n}`
        $relative = preg_replace('#^(/wp-json)?/wc/(store|blocks)/v\d+#', '', $route);

        // Cache-safe catalog endpoints (regex so minor version/path changes don't break us)
        $patterns = [
            '#^/products$#',
            '#^/products/\d+$#',                      // individual product
            '#^/products/categories$#',
            '#^/products/tags$#',
            '#^/products/attributes$#',
            '#^/products/collection-data$#',
            '#^/products/reviews$#',                  // global reviews list (optional)
            '#^/products/\d+/reviews$#',              // product reviews (optional)
        ];

        // Allow themes/plugins to adjust
        $patterns = (array) apply_filters('mamba_store_api_allow_patterns', $patterns);
        $blocklist = (array) apply_filters('mamba_store_api_blocklist', [
            '/cart', '/checkout', '/addresses', '/user', '/account',
            '/orders', '/payments', '/shipping', '/billing', '/session',
        ]);

        foreach ($blocklist as $blocked) {
            if (strpos($relative, $blocked) === 0) return false;
        }

        foreach ($patterns as $re) {
            if (@preg_match($re, $relative)) {
                if (preg_match($re, $relative)) return true;
            }
        }

        return false; // default deny
    }
    
    /**
     * Normalize query parameters to match WooCommerce Store API schema
     * Ensures cache key consistency between serve and store operations
     * 
     * @param array $params Raw query parameters from request
     * @return array Normalized parameters matching WooCommerce schema
     */
    private function normalizeStoreApiParams(array $params): array {
        // Remove v parameter to prevent duplication with variance signature
        // v represents viewer context (geolocation), not functional filters

        unset($params['v']);
        
        // Allow filtering of parameters that should be treated as arrays
        $arrayParams = apply_filters('mamba_store_api_multi_params', [
            'category',    // WooCommerce normalizes category=16 to category[]=16
            'tag',         // WooCommerce normalizes tag=5 to tag[]=5
            'attributes',  // WooCommerce attributes are always arrays
            'min_price',   // WooCommerce may normalize to array
            'max_price',   // WooCommerce may normalize to array
            'rating',      // WooCommerce may normalize to array
            'stock_status' // WooCommerce may normalize to array
        ]);
        
        // Allow filtering of noise parameters that should be ignored
        $noiseParams = apply_filters('mamba_store_api_noise_params', [
            'v',           // WooCommerce geolocation hash (handled in variance signature)
            'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',
            'fbclid', 'gclid', 'msclkid', 'ref', 'ref_src', 'ref_url'
        ]);
        
        // Remove noise parameters
        foreach ($noiseParams as $param) {
            unset($params[$param]);
        }
        
        $normalized = $params;
        
        foreach ($arrayParams as $param) {
            if (isset($normalized[$param]) && !is_array($normalized[$param])) {
                // Convert scalar to array to match WooCommerce normalization
                $normalized[$param] = [$normalized[$param]];
            }
        }
        
        return $normalized;
    }

    /**
     * Generate variance signature for Store API cache keys
     * Ensures cache accuracy across different user contexts
     * 
     * @param array|null $rawParams Optional raw parameters for geo detection
     * @return string The variance signature hash
     */
    private function getVarianceSignature(?array $rawParams = null): string {
        // Device: mobile vs desktop (affects layout/performance)
        $device = 'd=' . (wp_is_mobile() ? 'm' : 'd');

        // Currency (and allow integrators to override)
        $currency = apply_filters('mamba_variant_currency', get_option('woocommerce_currency', ''));

        // Language (WPML/Polylang or custom)
        $lang = apply_filters('mamba_variant_lang', '');

        // Tax display mode (incl/excl)
        $tax = get_option('woocommerce_tax_display_shop', 'incl');

        // Country (when geolocation affects catalog pricing/tax)
        $country = '';
        if (get_option('woocommerce_default_customer_address') === 'geolocation_ajax') {
            $country = get_option('woocommerce_default_country', '');
            if (strpos($country, ':') !== false) {
                $country = explode(':', $country)[0];
            }
        }
        $country = apply_filters('mamba_variant_country', $country);

        // Optional extra buckets (zones, membership, B2B, etc.), default empty
        $extra = (array) apply_filters('mamba_store_api_extra_key_parts', []);
        
        // Add role-based pricing plugin dimensions
        $roleDimensions = \Mamba\Modules\Caching\Services\Invalidation::detectRoleBasedPricing();
        if (!empty($roleDimensions)) {
            $extra = array_merge($extra, $roleDimensions);
        }

        // Add WooCommerce geo hash if available (pass only the specific 'v' value needed)
        $vParam = is_array($rawParams) && isset($rawParams['v']) ? sanitize_text_field($rawParams['v']) : null;
        $wooGeoHash = $this->detectWooCommerceGeoHash($vParam);
        if ($wooGeoHash) {
            $extra[] = 'woo_geo=' . $wooGeoHash;
        }

        $parts = array_map('strval', array_merge([$device, $currency, $lang, $tax, $country], $extra));
        return md5(implode('|', $parts));
    }
    
    /**
     * Detect WooCommerce geolocation hash parameter
     * Validates and returns the 'v' parameter if present and valid
     * 
     * @param string|null $vParam Optional 'v' parameter value to check (for warmup compatibility)
     * @return string|null The validated geo hash or null
     */
    private function detectWooCommerceGeoHash(?string $vParam = null): ?string {
        // Only read the specific 'v' parameter needed (avoid processing full $_GET)
        $v = $vParam ?? (isset($_GET['v']) ? sanitize_text_field(wp_unslash($_GET['v'])) : null);
        
        // Check for WooCommerce's v parameter
        if (!empty($v) && is_string($v)) {
            $hash = sanitize_text_field($v);
            // Validate it looks like a WooCommerce geo hash (alphanumeric, reasonable length)
            if (preg_match('/^[a-zA-Z0-9]{8,32}$/', $hash)) {
                return $hash;
            }
        }
        
        // Check for WooCommerce geo cookie as fallback
        if (!empty($_COOKIE['woocommerce_geo_hash'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized via sanitize_text_field
            $cookieHash = sanitize_text_field(wp_unslash($_COOKIE['woocommerce_geo_hash']));
            // Validate cookie hash format
            if (preg_match('/^[a-zA-Z0-9]{8,32}$/', $cookieHash)) {
                return $cookieHash;
            }
        }
        
        return null;
    }
    
    /**
     * Get cart hash for microcaching
     * Returns the store_api_cart_hash if present and valid
     */
    private function getCartHash(): ?string {
        // Check for store_api_cart_hash cookie
        if (!empty($_COOKIE['store_api_cart_hash'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized via sanitize_text_field
            $hash = sanitize_text_field(wp_unslash($_COOKIE['store_api_cart_hash']));
            // Validate it looks like a valid cart hash (alphanumeric, reasonable length)
            if (preg_match('/^[a-zA-Z0-9]{8,32}$/', $hash)) {
                return $hash;
            }
        }
        return null;
    }
    
    /**
     * Check if the current request is a warmup request
     */
    private function isWarmupRequest(): bool {
        // FIX: Add X-Mamba-Warmup header detection for future-proofing alongside User-Agent
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
        $warmupHeader = isset($_SERVER['HTTP_X_MAMBA_WARMUP']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_MAMBA_WARMUP'])) : '';
        
        return strpos($userAgent, 'Mamba Cache Warmup Bot') !== false || $warmupHeader === '1';
    }
    

    public function apiCacheStatus($request) {
        $stats = get_option('mamba_cache_stats', ['cache_hits'=>0,'cache_misses'=>0,'cache_size'=>0,'last_cleared'=>0,'by_type'=>[],'gen'=>['total_ms'=>0,'misses'=>0]]);
        $warm = get_option('mamba_warmup_stats', ['last_run'=>0,'total_urls'=>0,'success'=>0]);
        return new \WP_REST_Response([
            'enabled' => (bool)get_option('mamba_enable_page_cache', 0),
            'ttl' => (int)get_option('mamba_cache_ttl', 7200), // 2 hours default
            'stats' => $stats,
            'warmup' => $warm,
        ], 200);
    }
    public function apiWarmup($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) {
            return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        }
        if (!get_option('mamba_enable_page_cache', 0)) {
            return new \WP_REST_Response(['error' => 'cache_disabled', 'message' => 'Enable the caching engine first in Caching → Page Cache.'], 400);
        }
        $job = \Mamba\Modules\Caching\Services\Preload\Preloader::startJob();
        
        // Check if job was successfully scheduled
        $scheduled = true;
        $statusCode = 200;
        if (is_array($job) && isset($job['status']) && $job['status'] === 'error') {
            $scheduled = false;
            $error = $job['error'] ?? 'unknown';
            
            // Return appropriate status codes based on error type
            if ($error === 'premium_feature') {
                $statusCode = 402; // Payment Required
            } elseif ($error === 'job_already_running') {
                $statusCode = 409; // Conflict
            } else {
                $statusCode = 400; // Bad Request
            }
            
            return new \WP_REST_Response([
                'scheduled' => false,
                'error' => $error,
                'message' => $job['message'] ?? 'Warmup could not be started.'
            ], $statusCode);
        }
        
        return new \WP_REST_Response(['scheduled'=>$scheduled,'job'=>$job], $statusCode);
    }
    public function apiWarmupStatus($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        $job = \Mamba\Modules\Caching\Services\Preload\Preloader::statusJob();
        return new \WP_REST_Response($job, 200);
    }
    public function apiWarmupCancel($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        $ok = \Mamba\Modules\Caching\Services\Preload\Preloader::cancelJob();
        return new \WP_REST_Response(['cancelled'=>$ok], 200);
    }
    
    public function apiWarmupResume($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        $ok = \Mamba\Modules\Caching\Services\Preload\Preloader::resumeJob();
        return new \WP_REST_Response(['resumed'=>$ok], 200);
    }
    
    public function apiWarmupErrors($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        
        $errors = \Mamba\Modules\Caching\Services\Preload\Warmup\ErrorTracker::getErrors();
        $stats = \Mamba\Modules\Caching\Services\Preload\Warmup\ErrorTracker::getErrorStats();
        $grouped = \Mamba\Modules\Caching\Services\Preload\Warmup\ErrorTracker::groupErrorsByType();
        
        return new \WP_REST_Response([
            'errors' => $errors,
            'stats' => $stats,
            'grouped' => $grouped
        ], 200);
    }
    
    public function apiBackgroundWarmup($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        
        try {
            // Check if cache is enabled
            if (!get_option('mamba_enable_page_cache', 0)) {
                return new \WP_REST_Response([
                    'success' => false,
                    'error' => 'Cache is not enabled. Please enable page cache first.'
                ], 400);
            }
            $jobId = \Mamba\Modules\Caching\Services\Preload\BackgroundWarmup::scheduleJob();
            
            if (!$jobId) {
                return new \WP_REST_Response([
                    'success' => false,
                    'error' => 'Failed to create background job'
                ], 500);
            }
            
            return new \WP_REST_Response([
                'success' => true,
                'job_id' => $jobId,
                'message' => 'Background warmup job scheduled successfully'
            ], 200);
        } catch (\Exception $e) {
            // Log the error for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba Background Warmup Error: ' . $e->getMessage());
                error_log('Mamba Background Warmup Stack Trace: ' . $e->getTraceAsString());
            }
            
            return new \WP_REST_Response([
                'success' => false,
                'error' => 'Failed to schedule background warmup: ' . $e->getMessage()
            ], 500);
        }
    }
    
    public function apiBackgroundJobs($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        
        $jobs = \Mamba\Modules\Caching\Services\Preload\BackgroundWarmup::getRecentJobs(10);
        return new \WP_REST_Response(['jobs' => $jobs], 200);
    }
    
    public function apiStats($request) {
        if (!(current_user_can('manage_options') || current_user_can('manage_woocommerce'))) {
            return new \WP_REST_Response(['error'=>'unauthorized'], 403);
        }
        
        // Force flush any pending stats
        if (class_exists('\Mamba\Modules\Caching\Services\StatsBuffer')) {
            \Mamba\Modules\Caching\Services\StatsBuffer::flushNow();
        }
        
        // Get fresh stats
        $stats = get_option('mamba_cache_stats', ['cache_hits'=>0,'cache_misses'=>0,'cache_size'=>0,'last_cleared'=>0]);
        $hits = (int)($stats['cache_hits'] ?? 0);
        $miss = (int)($stats['cache_misses'] ?? 0);
        $rate = ($hits + $miss) > 0 ? round(($hits / ($hits + $miss)) * 100) : 0;
        $byType = $stats['by_type'] ?? [];
        $gen = $stats['gen'] ?? ['total_ms'=>0,'misses'=>0];
        $avgGenMs = ($gen['misses'] ?? 0) > 0 ? round(($gen['total_ms'] ?? 0) / $gen['misses']) : 0;
        
        return new \WP_REST_Response([
            'hits' => $hits,
            'misses' => $miss,
            'rate' => $rate,
            'by_type' => $byType,
            'avg_gen_ms' => $avgGenMs,
            'timestamp' => time()
        ], 200);
    }

    /**
     * Purge endpoint with scope-based operations
     */
    public function apiPurge($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) {
            return new \WP_REST_Response(['error' => 'unauthorized'], 403);
        }

        $params = $request->get_json_params();
        if (!is_array($params)) { $params = [];
        }

        $scope = isset($params['scope']) ? sanitize_key($params['scope']) : '';
        $value = $params['value'] ?? null;
        $andWarm = !empty($params['and_warm']);

        $actions = [];
        $warmed = [];
        $errors = [];

        try {
            switch ($scope) {
                case 'all':
                    \Mamba\Modules\Caching\Services\Invalidation::clearAll();
                    $actions[] = 'cleared_all';
                    break;

                case 'store-api':
                    \Mamba\Modules\Caching\Services\Invalidation::clearStoreApi();
                    $actions[] = 'cleared_store_api';
                    break;

                case 'url':
                    if (is_string($value)) {
                        $url = esc_url_raw($value);
                        if ($url && strpos($url, home_url()) === 0) {
                            \Mamba\Modules\Caching\Services\Invalidation::clearUrl($url);
                            $actions[] = ['cleared_url' => $url];
                            if ($andWarm && get_option('mamba_enable_page_cache', 0)) {
                                \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($url);
                                $warmed[] = $url;
                            }
                        } else {
                            $errors[] = 'invalid_or_external_url';
                        }
                    } else {
                        $errors[] = 'missing_url_value';
                    }
                    break;

                case 'urls':
                    if (is_array($value)) {
                        foreach ($value as $u) {
                            $url = esc_url_raw((string)$u);
                            if ($url && strpos($url, home_url()) === 0) {
                                \Mamba\Modules\Caching\Services\Invalidation::clearUrl($url);
                                $actions[] = ['cleared_url' => $url];
                                if ($andWarm && get_option('mamba_enable_page_cache', 0)) {
                                    \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($url);
                                    $warmed[] = $url;
                                }
                            } else {
                                $errors[] = ['invalid_or_external_url' => $url];
                            }
                        }
                    } else {
                        $errors[] = 'missing_urls_array';
                    }
                    break;

                case 'tags':
                    // Purge CDN tags via action
                    $tags = [];
                    if (is_array($value)) { $tags = array_values(array_filter(array_map('sanitize_key', $value))); }
                    elseif (is_string($value)) { $tags = array_values(array_filter(array_map('sanitize_key', explode(',', $value)))); }
                    if (!empty($tags)) {
                        do_action('mamba_purge_tags', $tags);
                        $actions[] = ['purged_tags' => $tags];
                    } else {
                        $errors[] = 'missing_tags_value';
                    }
                    break;

                case 'product':
                    $pid = (int) $value;
                    if ($pid > 0) {
                        \Mamba\Modules\Caching\Services\Invalidation::clearRelatedProduct($pid);
                        $actions[] = ['cleared_product_related' => $pid];
                    } else {
                        $errors[] = 'invalid_product_id';
                    }
                    break;

                case 'category':
                    $termId = (int) $value;
                    if ($termId > 0) {
                        $term = get_term($termId, 'product_cat');
                        if ($term && !is_wp_error($term)) {
                            $url = get_term_link($term);
                            if (!is_wp_error($url)) {
                                \Mamba\Modules\Caching\Services\Invalidation::clearUrl($url);
                                $actions[] = ['cleared_category' => (int)$term->term_id];
                                if ($andWarm && get_option('mamba_enable_page_cache', 0)) {
                                    \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($url);
                                    $warmed[] = $url;
                                }
                            }
                        } else {
                            $errors[] = 'invalid_category_term';
                        }
                    } else {
                        $errors[] = 'invalid_category_id';
                    }
                    break;

                case 'shop':
                    if (function_exists('wc_get_page_permalink')) {
                        $shopUrl = wc_get_page_permalink('shop');
                        if ($shopUrl) {
                            \Mamba\Modules\Caching\Services\Invalidation::clearUrl($shopUrl);
                            $actions[] = ['cleared_shop' => $shopUrl];
                            if ($andWarm && get_option('mamba_enable_page_cache', 0)) {
                                \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($shopUrl);
                                $warmed[] = $shopUrl;
                            }
                        }
                    }
                    break;

                case 'home':
                    $homeUrl = home_url('/');
                    \Mamba\Modules\Caching\Services\Invalidation::clearUrl($homeUrl);
                    $actions[] = ['cleared_home' => $homeUrl];
                    if ($andWarm && get_option('mamba_enable_page_cache', 0)) {
                        \Mamba\Modules\Caching\Services\Preload\Preloader::warmOne($homeUrl);
                        $warmed[] = $homeUrl;
                    }
                    break;

                default:
                    return new \WP_REST_Response(['error' => 'invalid_scope'], 400);
            }
        } catch (\Throwable $e) {
            $errors[] = $e->getMessage();
        }

        // Invalidate cached cache-counts so next poll recomputes
        delete_transient('mamba_cache_counts_cache');

        return new \WP_REST_Response([
            'success' => empty($errors),
            'actions' => $actions,
            'warmed'  => $warmed,
            'errors'  => $errors,
        ], empty($errors) ? 200 : 207);
    }

    /**
     * Cache counts endpoint (lightweight, cached via transient for 60s)
     */
    public function apiCacheCounts($request) {
        if (!(current_user_can('manage_options') || current_user_can('manage_woocommerce'))) {
            return new \WP_REST_Response(['error' => 'unauthorized'], 403);
        }

        $cached = get_transient('mamba_cache_counts_cache');
        if (is_array($cached) && isset($cached['counts'])) {
            return new \WP_REST_Response($cached, 200);
        }

        $counts = ['products'=>0,'categories'=>0,'shop'=>0,'homepage'=>0,'other'=>0];
        $sizeBytes = 0;

        if ((bool) get_option('mamba_enable_page_cache', 0) && defined('WP_CONTENT_DIR')) {
            $cacheDir = WP_CONTENT_DIR . '/cache/mamba';
            if (is_dir($cacheDir)) {
                try {
                    $iterator = new \RecursiveIteratorIterator(
                        new \RecursiveDirectoryIterator($cacheDir, \RecursiveDirectoryIterator::SKIP_DOTS),
                        \RecursiveIteratorIterator::LEAVES_ONLY
                    );
                    foreach ($iterator as $file) {
                        if ($file->isFile()) {
                            $sizeBytes += (int) $file->getSize();
                        }
                        if (!$file->isFile() || $file->getExtension() !== 'html') continue;
                        $htmlPath = $file->getPathname();
                        $metaPath = preg_replace('/\.html$/', '.meta.json', $htmlPath);
                        $classified = false;
                        if ($metaPath && file_exists($metaPath)) {
                            $meta = json_decode(@file_get_contents($metaPath), true);
                            if (is_array($meta)) {
                                $tags = isset($meta['tags']) && is_array($meta['tags']) ? $meta['tags'] : [];
                                if (!empty($tags)) {
                                    $hasProduct = false; $hasCategory = false; $hasShop = false; $hasHome = false;
                                    foreach ($tags as $t) {
                                        if (!$hasProduct && strpos($t, 'product_') === 0) { $hasProduct = true; }
                                        elseif (!$hasCategory && strpos($t, 'category_') === 0) { $hasCategory = true; }
                                        elseif (!$hasShop && $t === 'shop') { $hasShop = true; }
                                        elseif (!$hasHome && $t === 'home') { $hasHome = true; }
                                    }
                                    if ($hasProduct) { $counts['products']++; $classified = true; }
                                    elseif ($hasCategory) { $counts['categories']++; $classified = true; }
                                    elseif ($hasShop) { $counts['shop']++; $classified = true; }
                                    elseif ($hasHome) { $counts['homepage']++; $classified = true; }
                                }
                            }
                        }
                        if ($classified) continue;
                        $relativePath = str_replace($cacheDir . '/', '', $htmlPath);
                        $pathParts = explode('/', $relativePath);
                        if (empty($pathParts)) { $counts['other']++; continue; }
                        if (count($pathParts) > 1) {
                            $urlPath = $pathParts[1];
                            if (strpos($urlPath, 'product') !== false && strpos($urlPath, 'product-category') === false) {
                                $counts['products']++;
                            } elseif (strpos($urlPath, 'product-category') !== false) {
                                $counts['categories']++;
                            } elseif (strpos($urlPath, 'shop') !== false) {
                                $counts['shop']++;
                            } elseif ($urlPath === '' || $urlPath === 'index') {
                                $counts['homepage']++;
                            } else {
                                $counts['other']++;
                            }
                        } else {
                            $counts['homepage']++;
                        }
                    }
                } catch (\Exception $e) {
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        error_log('Mamba: Cache counts scan failed: ' . $e->getMessage());
                    }
                }
            }
        }

        $payload = [
            'counts' => $counts,
            'size_bytes' => (int) $sizeBytes,
            'timestamp' => time(),
        ];
        // Cache for 60 seconds to prevent excessive filesystem scans
        set_transient('mamba_cache_counts_cache', $payload, 60);
        return new \WP_REST_Response($payload, 200);
    }

    /**
     * Purge stats endpoint
     */
    public function apiPurgeStats($request) {
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) {
            return new \WP_REST_Response(['error' => 'unauthorized'], 403);
        }
        $stats = get_option('mamba_cache_stats', ['cache_hits'=>0,'cache_misses'=>0,'cache_size'=>0,'last_cleared'=>0]);
        return new \WP_REST_Response($stats, 200);
    }
    
    /**
     * Preload Store API responses for zero round-trip start
     * Uses WordPress core pattern: wp.apiFetch.createPreloadingMiddleware()
     */
    public function maybePreloadStoreApi(): void {
        // Only preload if we have cached data and are on appropriate pages
        if (!$this->shouldPreloadStoreApi()) return;
        
        $preloadPaths = $this->getPreloadEndpoints();
        $preloadData = [];
        
        // Filter endpoints to only include those likely to be used by current page
        $preloadPaths = $this->filterUsedEndpoints($preloadPaths);
        
        foreach ($preloadPaths as $path) {
            $key = $this->generatePreloadCacheKey($path);
            
            // Use appropriate TTL: 3s for cart/checkout (microcache), 600s for catalog
            $isCartEndpoint = (bool) preg_match('#/wc/store/v\d+/(cart|checkout)$#', str_replace('/wp-json','',$path));
            $readTtl = $isCartEndpoint ? 3 : 600;
            
            $cached = StoreApiFileCache::get($key, $readTtl);
            
            if ($cached && isset($cached['data'])) {
                // WordPress core expects: [absoluteUrl, {body: data, headers: headers}]
                $body = $cached['data'];
                $headers = isset($cached['headers']) && is_array($cached['headers']) ? $cached['headers'] : [];
                $preloadData[] = [$this->absoluteRestUrl($path), ['body' => $body, 'headers' => $headers]];
            } elseif (!$cached && preg_match('#/cart|/checkout#', $path)) {
                // Generate on-demand for cart/checkout if not cached
                $route = str_replace('/wp-json', '', $path);
                $req = new \WP_REST_Request('GET', $route);
                $resp = rest_get_server()->dispatch($req);
                
                if (!$resp->is_error()) {
                    $status = (int) $resp->get_status();
                    $body = $resp->get_data();
                    $headers = (array) $resp->get_headers();
                    
                    // Normalize headers to lowercase and clean up
                    $normalizedHeaders = array_change_key_case($headers, CASE_LOWER);
                    unset($normalizedHeaders['etag'], $normalizedHeaders['vary']);
                    if (!isset($normalizedHeaders['content-type'])) {
                        $normalizedHeaders['content-type'] = 'application/json; charset=utf-8';
                    }
                    
                    // Store to the same key (use 3s TTL if per-cart)
                    $payload = [
                        'status' => $status, 
                        'data' => $body, 
                        'headers' => $normalizedHeaders, 
                        't' => time()
                    ];
                    $ttl = preg_match('#/cart|/checkout#', $route) ? 3 : (int) get_option('mamba_store_api_ttl', 600);
                    StoreApiFileCache::set($key, $payload, $ttl);
                    
                    // Now push { body, headers } into preload list
                    $preloadData[] = [$this->absoluteRestUrl($path), ['body' => $body, 'headers' => $normalizedHeaders]];
                }
            }
        }
        
        if (!empty($preloadData)) {
            wp_enqueue_script('wp-api-fetch');
            wp_add_inline_script(
                'wp-api-fetch',
                sprintf(
                    'try{wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );}catch(e){}',
                    wp_json_encode($preloadData)
                ),
                'after'
            );
        }
    }
    
    /**
     * Check if Store API preloading should be enabled
     */
    private function shouldPreloadStoreApi(): bool {
        // Preloading helps even if page cache is off
        // Only preload if page caching is enabled
        if (!get_option('mamba_enable_page_cache', 0)) return false;
        
        // Only on WooCommerce catalog pages or cart/checkout pages
        if (!$this->isCatalogPage() && !is_cart() && !is_checkout()) return false;
        
        // Don't preload for users with cart items on catalog pages (use microcache instead)
        // But allow cart/checkout preloading even with cart items
        if ($this->hasCartIntent() && !is_cart() && !is_checkout()) return false;
        
        // Don't preload for warmup requests
        if ($this->isWarmupRequest()) return false;
        
        // Don't preload for logged-in users (they get personalized data)
        if (is_user_logged_in()) return false;
        
        return true;
    }
    
    /**
     * Get Store API endpoints to preload based on current page context
     */
    private function getPreloadEndpoints(): array {
        $endpoints = [];
        
        // Always preload products list
        $endpoints[] = '/wp-json/wc/store/v1/products';
        
        // Preload categories if on shop/category pages
        if (function_exists('is_shop') && is_shop()) {
            $endpoints[] = '/wp-json/wc/store/v1/products/categories';
        }
        
        // Preload categories if on product category pages
        if (function_exists('is_product_category') && is_product_category()) {
            $endpoints[] = '/wp-json/wc/store/v1/products/categories';
        }
        
        // Preload current product if on product page
        if (function_exists('is_product') && is_product()) {
            global $post;
            if ($post && $post->post_type === 'product') {
                $endpoints[] = '/wp-json/wc/store/v1/products/' . $post->ID;
            }
        }
        
        // Preload cart endpoint if on cart page
        if (function_exists('is_cart') && is_cart()) {
            $endpoints[] = '/wp-json/wc/store/v1/cart';
        }
        
        // Preload cart and checkout endpoints if on checkout page
        if (function_exists('is_checkout') && is_checkout()) {
            $endpoints[] = '/wp-json/wc/store/v1/cart';
            $endpoints[] = '/wp-json/wc/store/v1/checkout';
        }
        
        // Allow filtering of preload endpoints
        return apply_filters('mamba_store_api_preload_endpoints', $endpoints);
    }
    
    /**
     * Generate cache key for preloading (uses microcache key for cart/checkout, variance for catalog)
     */
    private function generatePreloadCacheKey(string $path): string {
        // Extract route from full path
        $route = str_replace('/wp-json', '', $path);
        
        // If this is a per-cart endpoint, use the microcache key
        if (preg_match('#^/wc/store/v\d+/(cart|checkout)$#', $route)) {
            if ($cart = $this->getCartHash()) {
                $ver = (int) get_transient('mamba_mc_ver_' . md5($cart));
                return $route . '|' . wp_json_encode([]) . '|cart_' . $cart . '|v' . $ver;
            }
        }
        
        // Otherwise use the catalog key w/ variance
        return $route . '|' . wp_json_encode([]) . '|' . $this->getVarianceSignature();
    }
    
    /**
     * Check if current page is a catalog page
     */
    private function isCatalogPage(): bool {
        if (!function_exists('is_woocommerce')) return false;
        
        return (function_exists('is_front_page') && (is_front_page() || is_home())) ||
               (function_exists('is_product') && is_product()) ||
               (function_exists('is_product_category') && is_product_category()) ||
               (function_exists('is_product_tag') && is_product_tag()) ||
               (function_exists('is_shop') && is_shop()) ||
               (function_exists('is_woocommerce') && is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page());
    }
    
    /**
     * Filter endpoints to only include those likely to be used by current page
     * Reduces inline size by excluding unnecessary endpoints
     */
    private function filterUsedEndpoints(array $endpoints): array {
        $filtered = [];
        
        foreach ($endpoints as $endpoint) {
            // Always include cart/checkout endpoints on cart/checkout pages
            if ((is_cart() || is_checkout()) && 
                (strpos($endpoint, '/cart') !== false || strpos($endpoint, '/checkout') !== false)) {
                $filtered[] = $endpoint;
                continue;
            }
            
            // Always include product endpoints on product pages
            if (is_product() && strpos($endpoint, '/products/') !== false) {
                $filtered[] = $endpoint;
                continue;
            }
            
            // Always include category endpoints on category pages
            if (is_product_category() && strpos($endpoint, '/categories') !== false) {
                $filtered[] = $endpoint;
                continue;
            }
            
            // Always include general products endpoint (but not on cart/checkout)
            if ($endpoint === '/wp-json/wc/store/v1/products' && !is_cart() && !is_checkout()) {
                $filtered[] = $endpoint;
                continue;
            }
            
            // Allow filtering of other endpoints
            if (apply_filters('mamba_preload_endpoint_used', true, $endpoint)) {
                $filtered[] = $endpoint;
            }
        }
        
        return $filtered;
    }
    
    /**
     * Convert relative REST path to absolute URL
     */
    private function absoluteRestUrl(string $path): string {
        // If already absolute, return as-is
        if (strpos($path, 'http') === 0) return $path;
        
        // Convert /wp-json/wc/store/v1/... to absolute URL
        if (preg_match('#/wc/store/v\d+/(.+)$#', $path, $m)) {
            return rest_url('wc/store/v1/' . $m[1]);
        }
        
        // Fallback to home_url
        return home_url($path);
    }
    
    /**
     * Handle AJAX request to save a single setting (generic handler for all tabs)
     */
    public function handleSaveSetting(): void {
        check_ajax_referer('mamba_save_setting', 'nonce');
        
        if (!current_user_can('manage_options') && !current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $setting = sanitize_text_field(wp_unslash($_POST['setting'] ?? ''));
        $value = wp_unslash($_POST['value'] ?? '');
        
        // Whitelist of allowed settings (all Mamba settings)
        $allowed_settings = [
            // Caching settings
            'mamba_enable_page_cache',
            'mamba_enable_store_api_cache',
            'mamba_cache_ttl',
            'mamba_browser_ttl',
            'mamba_store_api_browser_ttl',
            'mamba_store_api_ttl',
            'mamba_include_accept_language_vary',
            'mamba_cdn_ttl',
            'mamba_stale_if_error',
            'mamba_enable_adaptive_ttl',
            'mamba_cache_size_limit',
            'mamba_preload_concurrency',
            'mamba_warmup_batch_size',
            // Premium warmup settings
            'mamba_warmup_priority_mode',
            'mamba_warmup_selective_mode',
            'mamba_warmup_schedule_enabled',
            'mamba_warmup_schedule_time',
            'mamba_warmup_selected_categories',
            'mamba_warmup_selected_products',
            'mamba_warmup_exclusions',
            // Performance/Overhead settings
            'mamba_enable_html_minify',
            'mamba_html_minify_mode',
            'mamba_enable_lazy_load',
            'mamba_enable_defer_js',
            'mamba_enable_preconnect',
            'mamba_preconnect_domains',
            'mamba_enable_dns_prefetch',
            'mamba_dns_prefetch_domains',
            'mamba_enable_font_preload',
            'mamba_preload_fonts',
            'mamba_enable_preload_fonts',
            'mamba_remove_query_strings',
            'mamba_disable_emojis',
            'mamba_disable_embeds',
            'mamba_disable_dashicons',
            'mamba_limit_revisions',
            'mamba_revision_limit',
            'mamba_disable_heartbeat',
            'mamba_heartbeat_frequency',
            'mamba_heartbeat_frontend',
            'mamba_heartbeat_admin',
            'mamba_heartbeat_editor',
            // Critical CSS and JS Delay settings
            'mamba_enable_critical_css',
            'mamba_enable_css_defer',
            'mamba_css_defer_all',
            'mamba_critical_css_force_include',
            'mamba_enable_js_delay',
            'mamba_js_delay_timeout',
            'mamba_js_delay_scripts',
            'mamba_js_delay_exclusions',
            // User-facing optimization settings
            'mamba_disable_wc_assets_on_non_wc',
            'mamba_simplify_price_html',
            'mamba_enable_hover_prefetch',
            'mamba_disable_order_attribution',
            // Checkout optimization settings
            'mamba_optimize_checkout_js',
            'mamba_optimize_checkout_css',
            'mamba_disable_checkout_fragments',
            'mamba_lazy_load_payments',
            'mamba_defer_transactional_emails',
            'mamba_preconnect_payment_sdks',
            // CDN settings
            'mamba_cdn_provider',
            'mamba_cloudflare_zone_id',
            'mamba_cloudflare_api_token',
            'mamba_cloudflare_detect_apo',
            'mamba_cloudflare_send_cache_tags',
            'mamba_bunny_api_key',
            'mamba_bunny_pull_zone_id',
            'mamba_bunny_send_cdn_tags',
            'mamba_bunny_use_wildcard_purges',
            'mamba_generic_webhook_url',
            'mamba_generic_webhook_secret',
            'mamba_fastly_service_id',
            'mamba_fastly_api_token',
            'mamba_fastly_send_surrogate_keys',
            'mamba_fastly_soft_purge',
            'mamba_cdn_enable_rewriting',
            'mamba_cdn_hostname',
            'mamba_cdn_dirs',
            'mamba_cdn_exclusions',
            // Object Cache settings
            'mamba_object_cache_backend',
            'mamba_redis_host',
            'mamba_redis_port',
            'mamba_redis_password',
            'mamba_redis_database',
            'mamba_memcached_host',
            'mamba_memcached_port',
            // Media settings
            'mamba_enable_lcp_optimization',
            'mamba_add_image_dimensions',
            'mamba_enable_image_compression',
            'mamba_compression_type',
            'mamba_compression_quality',
            'mamba_compress_full_size',
            'mamba_enable_webp_conversion',
            'mamba_webp_quality',
            'mamba_convert_full_size',
            'mamba_enable_avif_conversion',
            'mamba_avif_quality',
            'mamba_convert_full_size_avif',
        ];
        
        if (!in_array($setting, $allowed_settings, true)) {
            wp_send_json_error(['message' => 'Invalid setting: ' . $setting]);
        }
        
        // Sanitize value based on setting type
        if (strpos($setting, '_enable_') !== false || strpos($setting, '_disable_') !== false || strpos($setting, '_remove_') !== false || strpos($setting, '_limit_') !== false) {
            // Boolean settings
            $value = $value ? 1 : 0;
        } elseif (in_array($setting, ['mamba_cache_ttl', 'mamba_browser_ttl', 'mamba_store_api_browser_ttl', 'mamba_store_api_ttl', 'mamba_cdn_ttl', 'mamba_stale_if_error', 'mamba_preload_concurrency', 'mamba_warmup_batch_size', 'mamba_revision_limit', 'mamba_heartbeat_frequency', 'mamba_redis_port', 'mamba_redis_database', 'mamba_memcached_port'])) {
            // Integer settings
            $value = absint($value);
        } elseif ($setting === 'mamba_cache_size_limit') {
            // Size in MB, convert to bytes
            $value = max(10 * 1024 * 1024, min(absint($value) * 1024 * 1024, 2 * 1024 * 1024 * 1024));
        } else {
            // String settings
            $value = sanitize_text_field($value);
        }
        
        update_option($setting, $value);
        
        wp_send_json_success([
            'message' => 'Setting saved',
            'setting' => $setting,
            'value' => $value
        ]);
    }
}
