<?php
/**
 * Bloat Reduction Module
 *
 * Provides frontend performance optimizations including WooCommerce asset management,
 * checkout optimizations, HTML minification, font preloading, DNS prefetch,
 * and Heartbeat API control.
 *
 * @package Mamba\Modules\Bloat
 * @since   1.0.0
 */

namespace Mamba\Modules\Bloat;

use Mamba\Support\SavingsTracker;

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

/**
 * Class Module
 *
 * Main module class for frontend bloat reduction and performance optimizations.
 * Handles asset dequeuing, checkout optimizations, minification, and resource hints.
 *
 * @since 1.0.0
 */
final class Module {
    public function register(): void {
        add_action('wp_enqueue_scripts', [$this, 'maybeDequeueWooAssets'], 99);
        add_action('init', [$this, 'applySimplifyPriceHtmlSetting']);
        
        // Checkout optimizations
        add_action('wp_enqueue_scripts', [$this, 'optimizeCheckoutJS'], 98);
        add_action('wp_enqueue_scripts', [$this, 'optimizeCheckoutCSS'], 99);
        add_action('wp_enqueue_scripts', [$this, 'disableCheckoutFragments'], 99);
        add_action('wp_enqueue_scripts', [$this, 'lazyLoadPaymentMethods'], 98);
        add_action('init', [$this, 'deferTransactionalEmails']);
        add_action('wp_head', [$this, 'preconnectPaymentSDKs'], 1);
        
        // User-facing overhead optimizations
        add_action('wp_enqueue_scripts', [$this, 'disableOrderAttribution'], 100);
        add_action('wp_enqueue_scripts', [$this, 'enqueueHoverPrefetch'], 101);

        // Fallback HTML/CSS/JS minification when page cache is disabled
        add_action('template_redirect', [$this, 'maybeStartMinifyBuffer'], 9999);
        
        // Font preloading
        add_action('wp_head', [$this, 'preloadFonts'], 1);
        
        // DNS prefetch for external domains
        add_action('wp_head', [$this, 'dnsPrefetch'], 1);
        
        // Preconnect to external domains (user-configurable, separate from payment SDKs)
        add_action('wp_head', [$this, 'preconnectExternalDomains'], 1);
        
        // Heartbeat API control
        add_action('init', [$this, 'controlHeartbeat']);
        add_filter('heartbeat_settings', [$this, 'modifyHeartbeatSettings']);
        
        // JavaScript Delay (Premium)
        $this->registerJsDelay();
    }

    public function maybeDequeueWooAssets(): void {
        if (!get_option('mamba_disable_wc_assets_on_non_wc', 0)) return;
        if (!function_exists('is_woocommerce')) return;
        
        // Only dequeue on non-WooCommerce pages
        if (is_woocommerce() || (function_exists('is_cart') && (is_cart() || is_checkout() || is_account_page()))) {
            return; // Don't dequeue on WooCommerce pages
        }
        
        // Dequeue all WooCommerce styles on non-WooCommerce pages
        wp_dequeue_style('woocommerce-layout');
        wp_dequeue_style('woocommerce-smallscreen');
        wp_dequeue_style('woocommerce-general');
        wp_dequeue_style('woocommerce_frontend_styles');
        wp_dequeue_style('woocommerce_fancybox_styles');
        wp_dequeue_style('woocommerce_chosen_styles');
        wp_dequeue_style('woocommerce_prettyPhoto_css');
        wp_dequeue_style('woocommerce-inline');
        wp_dequeue_style('wc-block-style');
        wp_dequeue_style('wc-block-vendors-style');
        
        // Dequeue all WooCommerce scripts on non-WooCommerce pages
        wp_dequeue_script('woocommerce');
        wp_dequeue_script('wc-add-to-cart');
        wp_dequeue_script('wc_price_slider');
        wp_dequeue_script('wc-single-product');
        wp_dequeue_script('wc-checkout');
        wp_dequeue_script('wc-add-to-cart-variation');
        wp_dequeue_script('wc-cart');
        wp_dequeue_script('wc-chosen');
        wp_dequeue_script('prettyPhoto');
        wp_dequeue_script('prettyPhoto-init');
        wp_dequeue_script('jquery-blockui');
        wp_dequeue_script('jquery-placeholder');
        wp_dequeue_script('fancybox');
        wp_dequeue_script('jqueryui');
    }

    public function applyOrderSplitterSetting(): void {
        if (!get_option('mamba_disable_order_splitter_async', 0)) return;
        add_filter('woocommerce_order_splitter_queue_async', '__return_false');
    }

    public function applySimplifyPriceHtmlSetting(): void {
        if (!get_option('mamba_simplify_price_html', 0)) return;
        add_filter('woocommerce_get_price_html', function($price, $product){
            $currency_symbol = function_exists('get_woocommerce_currency_symbol') ? esc_html( get_woocommerce_currency_symbol() ) : '';
            // Remove <bdi> wrapper
            $price = str_replace(['<bdi>', '</bdi>'], '', (string)$price);
            // Replace currency span with escaped symbol
            $price = preg_replace('/<span class="woocommerce-Price-currencySymbol">.*?<\/span>/', $currency_symbol, (string)$price);
            // Remove screen reader text (note: may affect a11y)
            $price = preg_replace('/<span class="screen-reader-text">.*?<\/span>/', '', (string)$price);
            return $price;
        }, 10, 2);
    }

    /**
     * Optimize checkout JavaScript loading
     */
    public function optimizeCheckoutJS(): void {
        if (!get_option('mamba_optimize_checkout_js', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Defer non-critical scripts
        add_filter('script_loader_tag', function($tag, $handle) {
            $defer_scripts = [
                'wc-country-select',
                'wc-address-i18n',
                'wc-payment-methods'
            ];
            
            if (in_array($handle, $defer_scripts)) {
                return str_replace('<script ', '<script defer ', $tag);
            }
            
            return $tag;
        }, 10, 2);
    }

    /**
     * Optimize checkout CSS loading
     */
    public function optimizeCheckoutCSS(): void {
        if (!get_option('mamba_optimize_checkout_css', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Remove non-critical CSS on checkout
        add_action('wp_enqueue_scripts', function() {
            wp_dequeue_style('woocommerce-layout');
            wp_dequeue_style('woocommerce-smallscreen');
        }, 99);
    }

    /**
     * Intelligently disable cart fragments on checkout (reduces AJAX calls)
     * Follows WooCommerce 7.8+ best practices using woocommerce_get_script_data filter
     */
    public function disableCheckoutFragments(): void {
        if (!get_option('mamba_disable_checkout_fragments', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Check if cart widget is present (WooCommerce's logic)
        if ($this->hasCartWidgetOnCheckout()) {
            return; // Don't disable if cart widget is present
        }
        
        // Use WooCommerce's recommended approach: woocommerce_get_script_data filter
        add_filter('woocommerce_get_script_data', function($script_data, $handle) {
            if ('wc-cart-fragments' === $handle) {
                // Return null to prevent script execution (WooCommerce's recommended method)
                return null;
            }
            return $script_data;
        }, 10, 2);
    }

    /**
     * Check if cart widget is present on checkout page
     * Follows WooCommerce's logic for when cart fragments are needed
     */
    private function hasCartWidgetOnCheckout(): bool {
        // Check if cart widget is active in any widget area
        if (is_active_widget(false, false, 'woocommerce_widget_cart')) {
            return true;
        }
        
        // Check if cart widget is hardcoded in theme templates
        if (function_exists('has_block') && has_block('woocommerce/cart')) {
            return true;
        }
        
        // Check if cart widget is present in current page content
        global $post;
        if ($post && function_exists('parse_blocks')) {
            $blocks = parse_blocks($post->post_content);
            foreach ($blocks as $block) {
                if (isset($block['blockName']) && $block['blockName'] === 'woocommerce/cart') {
                    return true;
                }
            }
        }
        
        return false;
    }

    /**
     * Lazy load payment gateway scripts
     */
    public function lazyLoadPaymentMethods(): void {
        if (!get_option('mamba_lazy_load_payments', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Defer payment gateway scripts
        add_filter('script_loader_tag', function($tag, $handle) {
            $payment_scripts = [
                'stripe',
                'paypal',
                'square',
                'klarna',
                'woocommerce_payments'
            ];
            
            foreach ($payment_scripts as $gateway) {
                if (strpos($handle, $gateway) !== false) {
                    return str_replace('<script ', '<script defer ', $tag);
                }
            }
            
            return $tag;
        }, 10, 2);
    }

    /**
     * Defer transactional emails for faster checkout
     */
    public function deferTransactionalEmails(): void {
        if (!get_option('mamba_defer_transactional_emails', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Defer WooCommerce transactional emails during checkout
        add_filter('woocommerce_defer_transactional_emails', '__return_true');
    }

    /**
     * Preconnect payment SDKs for faster checkout
     */
    public function preconnectPaymentSDKs(): void {
        if (!get_option('mamba_preconnect_payment_sdks', 0) || !mamba_fs()->can_use_premium_code__premium_only()) return;
        if (!function_exists('is_checkout') || !is_checkout()) return;
        
        // Major payment gateway domains for preconnect
        $payment_domains = [
            'https://js.stripe.com',           // Stripe
            'https://www.paypal.com',          // PayPal
            'https://www.gstatic.com',         // Google Pay
            'https://js.squareup.com',         // Square
            'https://x.klarnacdn.net',         // Klarna
            'https://apple-pay-gateway.apple.com', // Apple Pay
            'https://secure.merchantonegateway.com', // Merchant One
            'https://api.affirm.com',          // Affirm
            'https://cdn.afterpay.com',        // Afterpay
            'https://static.klarna.com',       // Klarna (alternative)
            'https://www.2checkout.com',       // 2Checkout
            'https://secure.authorize.net',    // Authorize.net
            'https://api.braintreegateway.com', // Braintree
            'https://js.chargebee.com',        // Chargebee
            'https://cdn.adyen.com',           // Adyen
        ];
        
        // Output preconnect links
        foreach ($payment_domains as $domain) {
            echo '<link rel="preconnect" href="' . esc_url($domain) . '" crossorigin>' . "\n";
        }
    }

    /**
     * Disable WooCommerce marketplace suggestions
     */
    public function disableWooMarketplaceSuggestions(): void {
        if (!get_option('mamba_disable_woo_marketplace_suggestions', 0)) return;
        
        // Remove marketplace suggestions
        add_filter('woocommerce_allow_marketplace_suggestions', '__return_false');
    }

    /**
     * Suppress WooCommerce helper notices
     */
    public function suppressWooHelperNotices(): void {
        if (!get_option('mamba_suppress_woo_helper_notices', 0)) return;
        
        // Suppress helper notices
        add_filter('woocommerce_helper_suppress_admin_notices', '__return_true');
    }

    /**
     * Disable WooCommerce payment gateway suggestions
     */
    public function disablePaymentGatewaySuggestions(): void {
        if (!get_option('mamba_disable_woo_payment_gateway_suggestions', 0)) return;
        
        // Remove payment gateway suggestions
        add_filter('woocommerce_admin_payment_gateway_suggestion_specs', '__return_empty_array');
    }

    /**
     * Remove WooCommerce submenus (Marketplace & My Subscriptions)
     */
    public function removeWooSubmenus(): void {
        if (!get_option('mamba_remove_woo_submenus', 0)) return;
        
        // Remove Marketplace and My Subscriptions submenus
        remove_submenu_page('woocommerce', 'wc-addons');
        remove_submenu_page('woocommerce', 'wc-addons&section=helper');
    }

    /**
     * Disable order attribution script on non-checkout pages
     */
    public function disableOrderAttribution(): void {
        if (!get_option('mamba_disable_order_attribution', 0)) return;
        if (!function_exists('is_checkout') || is_checkout()) return;
        
        // Remove order attribution script on non-checkout pages
        wp_dequeue_script('wc-order-attribution');
    }

    /**
     * Enqueue hover prefetch JavaScript
     */
    public function enqueueHoverPrefetch(): void {
        if (!get_option('mamba_enable_hover_prefetch', 0)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba Hover Prefetch: Setting is disabled');
            }
            return;
        }
        
        // Don't load on checkout pages (not needed)
        if (function_exists('is_checkout') && is_checkout()) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba Hover Prefetch: Skipping checkout page');
            }
            return;
        }
        
        $scriptUrl = plugin_dir_url(MAMBA_FILE) . 'admin/js/mamba-hover-prefetch.js';
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba Hover Prefetch: Enqueuing script from: ' . $scriptUrl);
        }
        
        // Enqueue hover prefetch script
        wp_enqueue_script(
            'mamba-hover-prefetch',
            $scriptUrl,
            [],
            '2.1.0',
            true
        );
        
        // Enable debug mode if WP_DEBUG is on or filter is used
        $debugMode = (defined('WP_DEBUG') && WP_DEBUG) || apply_filters('mamba_hover_prefetch_debug', false);
        if ($debugMode) {
            wp_add_inline_script('mamba-hover-prefetch', 'window.MambaHoverPrefetch = { debug: true };', 'before');
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba Hover Prefetch: Script enqueued successfully');
        }
    }

    /**
     * Start output buffering to minify HTML when page cache won't handle it.
     * This runs when:
     * - Page cache is OFF, OR
     * - Page cache is ON but user has cart items (PageCache skips these users)
     * Runs only on frontend, non-REST, non-admin, HTML responses.
     */
    public function maybeStartMinifyBuffer(): void {
        // Only run if minification is enabled
        if (!get_option('mamba_enable_html_minify', 0)) return;
        
        // Frontend only
        if (is_admin()) return;
        if (defined('REST_REQUEST') && REST_REQUEST) return;
        
        // Determine if PageCache will handle minification
        $pageCacheEnabled = (bool) get_option('mamba_enable_page_cache', 0);
        $userHasCart = $this->userHasCartItems();
        $isLoggedIn = is_user_logged_in();
        $isExcludedPage = function_exists('is_cart') && (is_cart() || is_checkout() || is_account_page());
        
        // If page cache is ON and will handle this request, skip (PageCache does minification)
        // PageCache skips: logged-in users, cart users, cart/checkout/account pages
        if ($pageCacheEnabled && !$isLoggedIn && !$userHasCart && !$isExcludedPage) {
            return; // PageCache will handle minification
        }
        
        // For logged-in users, cart users, or excluded pages - we handle minification here
        // Start late buffer with callback for minification
        // The callback processes the buffer content when it's flushed
        ob_start(function ($buffer) {
            // Minimal guard: skip tiny or non-HTML buffers
            if (strlen($buffer) < 255 || stripos($buffer, '<html') === false) {
                return $buffer;
            }
            $mode = get_option('mamba_html_minify_mode', 'conservative');
            // Aggressive mode is Premium only - fallback to conservative for free users
            if ($mode === 'aggressive' && (!function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only())) {
                $mode = 'conservative';
            }
            if (class_exists('Mamba\Modules\Bloat\Services\HtmlMinifier')) {
                $originalSize = strlen($buffer);
                $minified = \Mamba\Modules\Bloat\Services\HtmlMinifier::minify($buffer, is_string($mode) ? $mode : 'conservative');
                $minifiedSize = strlen($minified);
                
                // Track savings if minification actually reduced size
                if ($minifiedSize < $originalSize) {
                    SavingsTracker::trackMinifySavings($originalSize, $minifiedSize);
                }
                
                return $minified;
            }
            return $buffer;
        });
        
        // Register shutdown handler to ensure buffer is explicitly flushed
        // This guarantees the buffer is closed even if WordPress exits unexpectedly
        register_shutdown_function(function () {
            if (ob_get_level() > 0) {
                ob_end_flush();
            }
        });
    }
    
    /**
     * Check if current user has items in cart (for minification bypass logic)
     */
    private function userHasCartItems(): bool {
        // 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;
            }
        }
        return false;
    }
    
    /**
     * Preload critical fonts for faster LCP
     * Supports WOFF2 format for best compression and browser support
     */
    public function preloadFonts(): void {
        // Feature Gating: Font Preloading is a Premium feature
        if (!get_option('mamba_enable_font_preload', 0) || !function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only()) return;
        
        $fonts = get_option('mamba_preload_fonts', '');
        if (empty($fonts)) return;
        
        // Parse font URLs (one per line)
        $fontUrls = array_filter(array_map('trim', explode("\n", $fonts)));
        
        foreach ($fontUrls as $fontUrl) {
            $fontUrl = esc_url(trim($fontUrl));
            if (empty($fontUrl)) continue;
            
            // Determine font type from extension
            $type = 'font/woff2'; // Default to woff2
            if (preg_match('/\.(woff2|woff|ttf|otf|eot)(\?|$)/i', $fontUrl, $matches)) {
                $ext = strtolower($matches[1]);
                $typeMap = [
                    'woff2' => 'font/woff2',
                    'woff' => 'font/woff',
                    'ttf' => 'font/ttf',
                    'otf' => 'font/otf',
                    'eot' => 'application/vnd.ms-fontobject',
                ];
                $type = $typeMap[$ext] ?? 'font/woff2';
            }
            
            echo '<link rel="preload" href="' . esc_url($fontUrl) . '" as="font" type="' . esc_attr($type) . '" crossorigin>' . "\n";
        }
    }
    
    /**
     * DNS prefetch for external domains
     * Reduces DNS lookup time for third-party resources
     */
    public function dnsPrefetch(): void {
        if (!get_option('mamba_enable_dns_prefetch', 0)) return;
        
        $domains = get_option('mamba_dns_prefetch_domains', '');
        
        // Auto-detect common WooCommerce external domains if enabled
        $autoDetect = get_option('mamba_dns_prefetch_auto_detect', 1);
        $autoDomains = [];
        
        if ($autoDetect) {
            // Common WooCommerce/WordPress external domains
            $autoDomains = [
                '//fonts.googleapis.com',      // Google Fonts
                '//fonts.gstatic.com',         // Google Fonts assets
                '//www.google-analytics.com',  // Google Analytics
                '//www.googletagmanager.com',  // Google Tag Manager
                '//connect.facebook.net',      // Facebook Pixel
                '//www.facebook.com',          // Facebook
                '//cdn.shopify.com',           // Shopify CDN (for some integrations)
                '//cdnjs.cloudflare.com',      // Cloudflare CDN
                '//unpkg.com',                 // unpkg CDN
                '//cdn.jsdelivr.net',          // jsDelivr CDN
            ];
            
            // Add payment gateway domains if WooCommerce is active
            if (function_exists('WC')) {
                $autoDomains = array_merge($autoDomains, [
                    '//js.stripe.com',
                    '//www.paypal.com',
                    '//www.paypalobjects.com',
                ]);
            }
            
            // Filter to allow customization
            $autoDomains = apply_filters('mamba_dns_prefetch_auto_domains', $autoDomains);
        }
        
        // Parse user-defined domains (one per line)
        $userDomains = array_filter(array_map('trim', explode("\n", $domains)));
        
        // Merge and dedupe
        $allDomains = array_unique(array_merge($autoDomains, $userDomains));
        
        foreach ($allDomains as $domain) {
            $domain = trim($domain);
            if (empty($domain)) continue;
            
            // Ensure domain starts with //
            if (strpos($domain, '//') !== 0 && strpos($domain, 'http') !== 0) {
                $domain = '//' . ltrim($domain, '/');
            }
            
            echo '<link rel="dns-prefetch" href="' . esc_url($domain) . '">' . "\n";
        }
    }
    
    /**
     * Preconnect to external domains (user-configurable)
     * Establishes early connections for faster resource loading
     * Note: This is SEPARATE from preconnectPaymentSDKs() which handles checkout-only payment domains
     */
    public function preconnectExternalDomains(): void {
        // Feature Gating: Preconnect External Domains is a Premium feature
        if (!get_option('mamba_enable_preconnect', 0) || !function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only()) return;
        
        $domains = get_option('mamba_preconnect_domains', '');
        if (empty($domains)) return;
        
        // Parse domains (one per line)
        $domainList = array_filter(array_map('trim', explode("\n", $domains)));
        
        foreach ($domainList as $domain) {
            $domain = trim($domain);
            if (empty($domain)) continue;
            
            // Ensure proper URL format
            if (strpos($domain, 'http') !== 0) {
                $domain = 'https://' . ltrim($domain, '/');
            }
            
            // Determine if crossorigin is needed (for fonts, scripts from CDNs)
            $needsCrossorigin = $this->domainNeedsCrossorigin($domain);
            
            if ($needsCrossorigin) {
                echo '<link rel="preconnect" href="' . esc_url($domain) . '" crossorigin>' . "\n";
            } else {
                echo '<link rel="preconnect" href="' . esc_url($domain) . '">' . "\n";
            }
        }
    }
    
    /**
     * Determine if a domain needs crossorigin attribute
     */
    private function domainNeedsCrossorigin(string $domain): bool {
        $crossoriginDomains = [
            'fonts.googleapis.com',
            'fonts.gstatic.com',
            'use.typekit.net',
            'use.fontawesome.com',
            'cdnjs.cloudflare.com',
            'cdn.jsdelivr.net',
            'unpkg.com',
        ];
        
        foreach ($crossoriginDomains as $cod) {
            if (strpos($domain, $cod) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Control WordPress Heartbeat API
     * Can disable on frontend, reduce frequency in admin, or disable entirely
     */
    public function controlHeartbeat(): void {
        $frontendSetting = get_option('mamba_heartbeat_frontend', 'default');
        $adminSetting = get_option('mamba_heartbeat_admin', 'default');
        $editorSetting = get_option('mamba_heartbeat_editor', 'default');
        
        // Disable heartbeat on frontend
        if ($frontendSetting === 'disable' && !is_admin()) {
            wp_deregister_script('heartbeat');
            return;
        }
        
        // Disable heartbeat in admin (except post editor)
        if ($adminSetting === 'disable' && is_admin()) {
            global $pagenow;
            $isEditor = in_array($pagenow, ['post.php', 'post-new.php'], true);
            
            if (!$isEditor) {
                wp_deregister_script('heartbeat');
                return;
            }
        }
        
        // Disable heartbeat in post editor
        if ($editorSetting === 'disable' && is_admin()) {
            global $pagenow;
            if (in_array($pagenow, ['post.php', 'post-new.php'], true)) {
                wp_deregister_script('heartbeat');
                return;
            }
        }
    }
    
    /**
     * Modify heartbeat interval settings
     */
    public function modifyHeartbeatSettings(array $settings): array {
        $frontendSetting = get_option('mamba_heartbeat_frontend', 'default');
        $adminSetting = get_option('mamba_heartbeat_admin', 'default');
        $editorSetting = get_option('mamba_heartbeat_editor', 'default');
        
        // Get current context
        $isAdmin = is_admin();
        $isEditor = false;
        if ($isAdmin) {
            global $pagenow;
            $isEditor = in_array($pagenow, ['post.php', 'post-new.php'], true);
        }
        
        // Determine which setting to apply
        $setting = 'default';
        if (!$isAdmin) {
            $setting = $frontendSetting;
        } elseif ($isEditor) {
            $setting = $editorSetting;
        } else {
            $setting = $adminSetting;
        }
        
        // Apply interval based on setting
        switch ($setting) {
            case 'slow': // 60 seconds
                $settings['interval'] = 60;
                break;
            case 'very_slow': // 120 seconds
                $settings['interval'] = 120;
                break;
            case 'disable':
                // Handled in controlHeartbeat()
                break;
            case 'default':
            default:
                // Keep WordPress default (15-60 seconds depending on context)
                break;
        }
        
        return $settings;
    }
    
    /**
     * Register JavaScript Delay functionality (Premium)
     * Delays non-critical scripts until user interaction
     */
    private function registerJsDelay(): void {
        // Only for premium users
        if (!function_exists('mamba_fs') || !mamba_fs()->can_use_premium_code__premium_only()) {
            return;
        }
        
        // Check if enabled
        if (!get_option('mamba_enable_js_delay', 0)) {
            return;
        }
        
        // Don't run on admin
        if (is_admin()) {
            return;
        }
        
        // Initialize the JsDelayer service
        $delayer = new Services\JsDelayer();
        
        // Filter script tags
        add_filter('script_loader_tag', [$delayer, 'maybeDelayScript'], 10, 3);
        
        // Output the loader script in footer
        add_action('wp_footer', [$delayer, 'outputLoaderScript'], 999);
    }
}
