<?php

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

<?php 
// Handle form submission
if ( isset( $_POST['mamba_media_settings'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mamba_nonce'] ?? '' ) ), 'mamba_media_settings' ) && current_user_can( 'manage_options' ) ) {
    // Premium media features - only save if user has premium
    if ( function_exists( 'mamba_fs' ) && mamba_fs()->can_use_premium_code__premium_only() ) {
        // LCP Optimization (Premium)
        update_option( 'mamba_enable_lcp_optimization', ( isset( $_POST['mamba_enable_lcp_optimization'] ) ? 1 : 0 ) );
        // Image Compression (Premium)
        update_option( 'mamba_enable_image_compression', ( isset( $_POST['mamba_enable_image_compression'] ) ? 1 : 0 ) );
        update_option( 'mamba_compression_quality', (int) wp_unslash( $_POST['mamba_compression_quality'] ?? 85 ) );
        update_option( 'mamba_compression_type', sanitize_text_field( wp_unslash( $_POST['mamba_compression_type'] ?? 'lossy' ) ) );
        update_option( 'mamba_compress_full_size', ( isset( $_POST['mamba_compress_full_size'] ) ? 1 : 0 ) );
        // Get previous values and intended new values
        $prev_webp = (bool) get_option( 'mamba_enable_webp_conversion', 0 );
        $prev_avif = (bool) get_option( 'mamba_enable_avif_conversion', 0 );
        $now_webp = isset( $_POST['mamba_enable_webp_conversion'] );
        $now_avif = isset( $_POST['mamba_enable_avif_conversion'] );
        // Enforce mutual exclusivity: Only one next-gen format can be enabled at a time
        // Priority: If user is enabling a new format, disable the other
        if ( $now_avif && !$prev_avif && $now_webp ) {
            // AVIF is being newly enabled while WebP was checked - disable WebP
            $now_webp = false;
        } elseif ( $now_webp && !$prev_webp && $now_avif ) {
            // WebP is being newly enabled while AVIF was checked - disable AVIF
            $now_avif = false;
        } elseif ( $now_webp && $now_avif ) {
            // Both checked but neither is new - keep the one that was previously enabled
            if ( $prev_avif ) {
                $now_webp = false;
            } else {
                $now_avif = false;
            }
        }
        // AVIF Conversion (Premium)
        update_option( 'mamba_enable_avif_conversion', ( $now_avif ? 1 : 0 ) );
        update_option( 'mamba_avif_quality', (int) wp_unslash( $_POST['mamba_avif_quality'] ?? 65 ) );
        update_option( 'mamba_convert_full_size_avif', ( isset( $_POST['mamba_convert_full_size_avif'] ) ? 1 : 0 ) );
        // Handle .htaccess rules based on changes
        $htaccessManager = new \Mamba\Modules\Media\Services\HtaccessManager();
        $serverInfo = $htaccessManager->getServerInfo();
        if ( $htaccessManager->isSupported() && $serverInfo['is_apache_compatible'] ) {
            $any_nextgen = $now_webp || $now_avif;
            $prev_nextgen = $prev_webp || $prev_avif;
            if ( !$prev_nextgen && $any_nextgen ) {
                $htaccessManager->addNextGenRules();
            } elseif ( $prev_nextgen && !$any_nextgen ) {
                $htaccessManager->removeNextGenRules();
            } elseif ( $any_nextgen ) {
                // Re-apply rules if settings changed
                $htaccessManager->addNextGenRules();
            }
        }
    }
    // WebP Conversion (Free feature)
    update_option( 'mamba_enable_webp_conversion', ( isset( $_POST['mamba_enable_webp_conversion'] ) ? 1 : 0 ) );
    update_option( 'mamba_webp_quality', (int) wp_unslash( $_POST['mamba_webp_quality'] ?? 85 ) );
    update_option( 'mamba_convert_full_size', ( isset( $_POST['mamba_convert_full_size'] ) ? 1 : 0 ) );
    // Add Missing Image Dimensions (Free feature)
    update_option( 'mamba_add_image_dimensions', ( isset( $_POST['mamba_add_image_dimensions'] ) ? 1 : 0 ) );
    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( __( 'Media settings saved successfully!', 'mamba-cache-for-woocommerce' ) ) . '</p></div>';
}
// Get current settings
$addImageDimensions = (bool) get_option( 'mamba_add_image_dimensions', 0 );
$enableLCPOptimization = (bool) get_option( 'mamba_enable_lcp_optimization', 0 );
$enableImageCompression = (bool) get_option( 'mamba_enable_image_compression', 0 );
$compressionQuality = (int) get_option( 'mamba_compression_quality', 85 );
$compressionType = get_option( 'mamba_compression_type', 'lossy' );
$compressFullSize = (bool) get_option( 'mamba_compress_full_size', 0 );
$enableWebPConversion = (bool) get_option( 'mamba_enable_webp_conversion', 0 );
$webpQuality = (int) get_option( 'mamba_webp_quality', 85 );
$convertFullSize = (bool) get_option( 'mamba_convert_full_size', 0 );
$enableAvifConversion = (bool) get_option( 'mamba_enable_avif_conversion', 0 );
$avifQuality = (int) get_option( 'mamba_avif_quality', 65 );
$convertFullSizeAvif = (bool) get_option( 'mamba_convert_full_size_avif', 0 );
// Get stats
$bulkOptimizer = new \Mamba\Modules\Media\Services\BulkOptimizer();
$stats = $bulkOptimizer->getTotalCounts();
$htaccessManager = new \Mamba\Modules\Media\Services\HtaccessManager();
$serverInfo = $htaccessManager->getServerInfo();
// Ensure .htaccess rules exist if Next-Gen is enabled
if ( ($enableWebPConversion || $enableAvifConversion) && $serverInfo['is_apache_compatible'] && $serverInfo['htaccess_writable'] && !$htaccessManager->hasNextGenRules() ) {
    $htaccessManager->addNextGenRules();
    $serverInfo = $htaccessManager->getServerInfo();
}
?>

<div class="mamba-admin-wrap">
    <!-- Media Optimization Overview -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-images-alt2"></span>
                <?php 
echo esc_html( __( 'Media Optimization Overview', 'mamba-cache-for-woocommerce' ) );
?>
            </h4>
        </div>
        
        <div class="mamba-media-overview">
            <div class="mamba-media-card">
                <div class="mamba-media-icon">
                    <span class="dashicons dashicons-performance"></span>
                </div>
                <div class="mamba-media-content">
                    <h3 class="mamba-media-title"><?php 
echo esc_html( __( 'Image Optimization', 'mamba-cache-for-woocommerce' ) );
?></h3>
                    <p class="mamba-media-description">
                        <?php 
echo esc_html( __( 'Optimize your images for faster loading, better Core Web Vitals scores, and improved user experience. Compress images, convert to WebP, and prioritize critical images for optimal performance.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
            </div>
        </div>
        
    </div>

    <form method="post" action="" class="mamba-media-form">
        <?php 
wp_nonce_field( 'mamba_media_settings', 'mamba_nonce' );
?>
        <input type="hidden" name="mamba_media_settings" value="1">
        
            <!-- LCP Optimization Section -->
            <div class="mamba-form-section">
                <div class="mamba-section-header">
                    <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-performance"></span>
                        <?php 
echo esc_html( __( 'LCP (Largest Contentful Paint) Optimization', 'mamba-cache-for-woocommerce' ) );
?>
                        <?php 
?>
                            <span class="mamba-premium-badge"><?php 
echo esc_html( __( 'Premium', 'mamba-cache-for-woocommerce' ) );
?></span>
                        <?php 
?>
                    </h4>
            </div>
            
            <div class="mamba-optimization-intro">
                        <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Optimize critical images for faster loading and better Core Web Vitals scores.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
            <?php 
?>
                <div class="mamba-premium-upsell">
                    <div class="mamba-upsell-content">
                        <span class="dashicons dashicons-lock"></span>
                        <h5><?php 
echo esc_html( __( 'Boost Google Vitals Score', 'mamba-cache-for-woocommerce' ) );
?></h5>
                        <p><?php 
echo esc_html( __( 'Automatically prioritize product images, shop banners, and category images with fetchpriority="high" and preload hints. Improves LCP (Largest Contentful Paint) scores.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        <a href="<?php 
echo esc_url( mamba_fs()->get_upgrade_url() );
?>" class="button button-primary mamba-upgrade-btn">
                            <?php 
echo esc_html( __( 'Upgrade to Pro', 'mamba-cache-for-woocommerce' ) );
?>
                        </a>
                    </div>
                </div>
            <?php 
?>
            </div>
            
            <!-- Image Dimensions Section (Free) -->
            <div class="mamba-form-section">
                <div class="mamba-section-header">
                    <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-image-crop"></span>
                        <?php 
echo esc_html( __( 'Image Dimensions', 'mamba-cache-for-woocommerce' ) );
?>
                    </h4>
                </div>
            
                <div class="mamba-optimization-intro">
                    <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Automatically add missing width and height attributes to images to reduce Cumulative Layout Shift (CLS).', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
                <div class="mamba-optimization-grid">
                    <div class="mamba-optimization-item">
                        <div class="mamba-optimization-header">
                            <div class="mamba-optimization-icon dashicons dashicons-image-crop"></div>
                            <div class="mamba-optimization-content">
                                <h5 class="mamba-optimization-name"><?php 
echo esc_html( __( 'Add Missing Image Dimensions', 'mamba-cache-for-woocommerce' ) );
?></h5>
                                <p class="mamba-optimization-description"><?php 
echo esc_html( __( 'Scans images in content and automatically adds width/height attributes if missing. Improves Core Web Vitals CLS score.', 'mamba-cache-for-woocommerce' ) );
?></p>
                            </div>
                        </div>
                        <div class="mamba-toggle-switch">
                            <input id="mamba_add_image_dimensions" type="checkbox" name="mamba_add_image_dimensions" <?php 
checked( $addImageDimensions );
?> />
                            <label for="mamba_add_image_dimensions"><?php 
echo esc_html( __( 'Enable', 'mamba-cache-for-woocommerce' ) );
?></label>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Image Compression Section -->
            <div class="mamba-form-section">
                <div class="mamba-section-header">
                        <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-images-alt2"></span>
                        <?php 
echo esc_html( __( 'Image Compression', 'mamba-cache-for-woocommerce' ) );
?>
                        <?php 
?>
                            <span class="mamba-premium-badge"><?php 
echo esc_html( __( 'Premium', 'mamba-cache-for-woocommerce' ) );
?></span>
                        <?php 
?>
                    </h4>
            </div>
            
            <div class="mamba-optimization-intro">
                        <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Reduce image file sizes while maintaining quality for faster page loads.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
            <?php 
?>
                <div class="mamba-premium-upsell">
                    <div class="mamba-upsell-content">
                        <span class="dashicons dashicons-lock"></span>
                        <h5><?php 
echo esc_html( __( 'Reduce Image Sizes Automatically', 'mamba-cache-for-woocommerce' ) );
?></h5>
                        <p><?php 
echo esc_html( __( 'Compress JPEG/PNG images on upload with configurable quality (1–100%). Choose lossy or lossless compression. Option to compress full-size originals in addition to thumbnails.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        <a href="<?php 
echo esc_url( mamba_fs()->get_upgrade_url() );
?>" class="button button-primary mamba-upgrade-btn">
                            <?php 
echo esc_html( __( 'Upgrade to Pro', 'mamba-cache-for-woocommerce' ) );
?>
                        </a>
                    </div>
                </div>
            <?php 
?>
            </div>
            
            <!-- WebP Conversion Section -->
            <div class="mamba-form-section">
                <div class="mamba-section-header">
                    <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-admin-appearance"></span>
                        <?php 
echo esc_html( __( 'WebP Conversion', 'mamba-cache-for-woocommerce' ) );
?>
                    </h4>
            </div>
            
            <div class="mamba-optimization-intro">
                <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Convert images to modern WebP format for smaller file sizes and faster loading.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
            <div class="mamba-optimization-grid">
                <div class="mamba-optimization-item">
                    <div class="mamba-optimization-header">
                        <div class="mamba-optimization-icon dashicons dashicons-admin-appearance"></div>
                        <div class="mamba-optimization-content">
                            <h5 class="mamba-optimization-name"><?php 
echo esc_html( __( 'Enable WebP Conversion', 'mamba-cache-for-woocommerce' ) );
?></h5>
                            <p class="mamba-optimization-description"><?php 
echo esc_html( __( 'Automatically convert JPEG and PNG images to WebP format on upload.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        </div>
                    </div>
                    <div class="mamba-toggle-switch">
                        <input id="mamba_enable_webp_conversion" type="checkbox" name="mamba_enable_webp_conversion" <?php 
checked( $enableWebPConversion );
?> />
                        <label for="mamba_enable_webp_conversion"><?php 
echo esc_html( __( 'Enable', 'mamba-cache-for-woocommerce' ) );
?></label>
                        </div>
                    </div>
                    
                <div class="mamba-optimization-item" style="<?php 
echo esc_attr( ( !$enableWebPConversion ? 'opacity: 0.5; pointer-events: none;' : '' ) );
?>">
                    <div class="mamba-optimization-header">
                        <div class="mamba-optimization-icon dashicons dashicons-admin-settings"></div>
                        <div class="mamba-optimization-content">
                            <h5 class="mamba-optimization-name"><?php 
echo esc_html( __( 'WebP Conversion Quality', 'mamba-cache-for-woocommerce' ) );
?></h5>
                            <p class="mamba-optimization-description"><?php 
echo esc_html( __( 'Quality setting for WebP conversion. Higher values = better quality but larger files.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        </div>
                    </div>
                    <div class="mamba-setting-control">
                        <div class="mamba-range-control">
                            <input type="range" name="mamba_webp_quality" min="1" max="100" value="<?php 
echo esc_attr( $webpQuality );
?>" class="mamba-range" oninput="this.nextElementSibling.value = this.value + '%'" />
                            <output class="mamba-range-output"><?php 
echo esc_html( $webpQuality );
?>%</output>
                        </div>
                    </div>
                 </div>
                    
                <div class="mamba-optimization-item" style="<?php 
echo esc_attr( ( !$enableWebPConversion ? 'opacity: 0.5; pointer-events: none;' : '' ) );
?>">
                    <div class="mamba-optimization-header">
                        <div class="mamba-optimization-icon dashicons dashicons-admin-generic"></div>
                        <div class="mamba-optimization-content">
                            <h5 class="mamba-optimization-name"><?php 
echo esc_html( __( 'Convert Full Size Images (WebP)', 'mamba-cache-for-woocommerce' ) );
?></h5>
                            <p class="mamba-optimization-description"><?php 
echo esc_html( __( 'Also convert the original full-size images to WebP format.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        </div>
                    </div>
                    <div class="mamba-toggle-switch">
                        <input id="mamba_convert_full_size" type="checkbox" name="mamba_convert_full_size" <?php 
checked( $convertFullSize );
?> />
                        <label for="mamba_convert_full_size"><?php 
echo esc_html( __( 'Enable', 'mamba-cache-for-woocommerce' ) );
?></label>
                    </div>
                </div>
            </div>
         </div>

            <!-- AVIF Conversion Section -->
            <div class="mamba-form-section">
                <div class="mamba-section-header">
                    <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-images-alt"></span>
                        <?php 
echo esc_html( __( 'AVIF Conversion', 'mamba-cache-for-woocommerce' ) );
?>
                        <?php 
?>
                            <span class="mamba-premium-badge"><?php 
echo esc_html( __( 'Premium', 'mamba-cache-for-woocommerce' ) );
?></span>
                        <?php 
?>
                    </h4>
            </div>
            
            <div class="mamba-optimization-intro">
                <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Convert images to AVIF format for superior compression and quality compared to WebP.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
            <?php 
?>
                <div class="mamba-premium-upsell">
                    <div class="mamba-upsell-content">
                        <span class="dashicons dashicons-lock"></span>
                        <h5><?php 
echo esc_html( __( 'Superior Next-Gen Compression (AVIF)', 'mamba-cache-for-woocommerce' ) );
?></h5>
                        <p><?php 
echo esc_html( __( 'Auto-convert to AVIF format (50% smaller than JPEG). Configurable quality (recommended 60–70%), optional full-size conversion, and automatic .htaccess rules for serving.', 'mamba-cache-for-woocommerce' ) );
?></p>
                        <a href="<?php 
echo esc_url( mamba_fs()->get_upgrade_url() );
?>" class="button button-primary mamba-upgrade-btn">
                            <?php 
echo esc_html( __( 'Upgrade to Pro', 'mamba-cache-for-woocommerce' ) );
?>
                        </a>
                    </div>
                </div>
            <?php 
?>
         </div>
                    
            <!-- Server Support Information -->
                    <?php 
if ( $serverInfo['is_apache_compatible'] && $serverInfo['htaccess_writable'] ) {
    ?>
            <div class="mamba-server-support">
                <div class="mamba-server-support-item">
                    <div class="mamba-server-support-icon dashicons dashicons-yes-alt"></div>
                        <div class="mamba-server-support-content">
                        <h5 class="mamba-server-support-title"><?php 
    echo esc_html( __( 'Server Support', 'mamba-cache-for-woocommerce' ) );
    ?></h5>
                        <p class="mamba-server-support-description">
                            <?php 
    $serverType = $serverInfo['server_type'] ?? 'Apache';
    // translators: %s is the server type
    printf( esc_html( __( '%s detected. .htaccess rules will be automatically added for AVIF/WebP serving.', 'mamba-cache-for-woocommerce' ) ), esc_html( $serverType ) );
    ?>
                        </p>
                        </div>
                            <span class="mamba-status-badge mamba-status-success">
                                <?php 
    echo esc_html( __( 'Automatic', 'mamba-cache-for-woocommerce' ) );
    ?>
                            </span>
                        </div>
                    </div>
                    <?php 
}
?>
                    
                    <?php 
// Check support
$webpSupported = function_exists( 'wp_image_editor_supports' ) && wp_image_editor_supports( [
    'mime_type' => 'image/webp',
] );
$avifSupported = function_exists( 'wp_image_editor_supports' ) && wp_image_editor_supports( [
    'mime_type' => 'image/avif',
] );
?>
            <div class="mamba-server-support">
                <div class="mamba-server-support-item">
                    <div class="mamba-server-support-icon dashicons <?php 
echo esc_attr( ( $avifSupported ? 'dashicons-yes-alt' : 'dashicons-warning' ) );
?>"></div>
                    <div class="mamba-server-support-content">
                        <h5 class="mamba-server-support-title"><?php 
echo esc_html( __( 'AVIF Generation Support', 'mamba-cache-for-woocommerce' ) );
?></h5>
                        <p class="mamba-server-support-description">
                            <?php 
echo ( $avifSupported ? esc_html( __( 'Server can generate AVIF via GD/Imagick.', 'mamba-cache-for-woocommerce' ) ) : esc_html( __( 'This server cannot generate AVIF (libavif missing or old PHP/ImageMagick version).', 'mamba-cache-for-woocommerce' ) ) );
?>
                        </p>
                        </div>
                            <span class="mamba-status-badge <?php 
echo esc_attr( ( $avifSupported ? 'mamba-status-success' : 'mamba-status-warning' ) );
?>">
                                <?php 
echo ( $avifSupported ? esc_html( __( 'Supported', 'mamba-cache-for-woocommerce' ) ) : esc_html( __( 'Not Supported', 'mamba-cache-for-woocommerce' ) ) );
?>
                            </span>
                        </div>
                    </div>

            <div class="mamba-server-support">
                <div class="mamba-server-support-item">
                    <div class="mamba-server-support-icon dashicons <?php 
echo esc_attr( ( $webpSupported ? 'dashicons-yes-alt' : 'dashicons-warning' ) );
?>"></div>
                    <div class="mamba-server-support-content">
                        <h5 class="mamba-server-support-title"><?php 
echo esc_html( __( 'WebP Generation Support', 'mamba-cache-for-woocommerce' ) );
?></h5>
                        <p class="mamba-server-support-description">
                            <?php 
echo ( $webpSupported ? esc_html( __( 'Server can generate WebP via GD/Imagick.', 'mamba-cache-for-woocommerce' ) ) : esc_html( __( 'This server cannot generate WebP (GD/Imagick missing WebP support).', 'mamba-cache-for-woocommerce' ) ) );
?>
                        </p>
                        </div>
                            <span class="mamba-status-badge <?php 
echo esc_attr( ( $webpSupported ? 'mamba-status-success' : 'mamba-status-warning' ) );
?>">
                                <?php 
echo ( $webpSupported ? esc_html( __( 'Supported', 'mamba-cache-for-woocommerce' ) ) : esc_html( __( 'Not Supported', 'mamba-cache-for-woocommerce' ) ) );
?>
                            </span>
                        </div>
                    </div>
                    
                    <?php 
if ( $serverInfo['is_nginx'] && ($enableWebPConversion || $enableAvifConversion) ) {
    ?>
            <div class="mamba-server-support">
                <div class="mamba-server-support-item">
                    <div class="mamba-server-support-icon dashicons dashicons-warning"></div>
                    <div class="mamba-server-support-content">
                        <h5 class="mamba-server-support-title"><?php 
    echo esc_html( __( 'Nginx Configuration Required', 'mamba-cache-for-woocommerce' ) );
    ?></h5>
                        <p class="mamba-server-support-description">
                            <?php 
    if ( $enableAvifConversion ) {
        echo esc_html( __( 'Nginx detected. Add the configuration below to serve AVIF images.', 'mamba-cache-for-woocommerce' ) );
    } else {
        echo esc_html( __( 'Nginx detected. Add the configuration below to serve WebP images.', 'mamba-cache-for-woocommerce' ) );
    }
    ?>
                        </p>
                        </div>
                            <span class="mamba-status-badge mamba-status-warning">
                                <?php 
    echo esc_html( __( 'Manual Required', 'mamba-cache-for-woocommerce' ) );
    ?>
                            </span>
                    </div>
                    
                <div class="mamba-nginx-config">
                    <h5 class="mamba-nginx-config-title">
                        <?php 
    if ( $enableAvifConversion ) {
        echo esc_html( __( 'Nginx AVIF Configuration', 'mamba-cache-for-woocommerce' ) );
    } else {
        echo esc_html( __( 'Nginx WebP Configuration', 'mamba-cache-for-woocommerce' ) );
    }
    ?>
                    </h5>
                    <p class="mamba-nginx-config-description">
                        <?php 
    if ( $enableAvifConversion ) {
        echo esc_html( __( 'Add this to your nginx.conf or site configuration to serve AVIF images:', 'mamba-cache-for-woocommerce' ) );
    } else {
        echo esc_html( __( 'Add this to your nginx.conf or site configuration to serve WebP images:', 'mamba-cache-for-woocommerce' ) );
    }
    ?>
                    </p>
                            <div class="mamba-code-snippet">
                                <pre><code><?php 
    echo esc_html( $htaccessManager->getNginxNextGenConfig() );
    ?></code></pre>
                                <button type="button" class="button button-small" onclick="copyToClipboard(this.previousElementSibling)">
                                    <span class="copy-text"><?php 
    echo esc_html( __( 'Copy', 'mamba-cache-for-woocommerce' ) );
    ?></span>
                                    <span class="copied-text" style="display: none;"><?php 
    echo esc_html( __( '✓ Copied', 'mamba-cache-for-woocommerce' ) );
    ?></span>
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php 
}
?>
            </div>
            
            <!-- Bulk Operations Section -->
  <div class="mamba-form-section">
                <div class="mamba-section-header">
                    <h4 class="mamba-section-title">
                        <span class="dashicons dashicons-admin-tools"></span>
                        <?php 
echo esc_html( __( 'Process Existing Images', 'mamba-cache-for-woocommerce' ) );
?>
                    </h4>
            </div>
            
            <div class="mamba-optimization-intro">
                <p class="mamba-optimization-description">
                        <?php 
echo esc_html( __( 'Apply optimizations to images that were uploaded before enabling these features.', 'mamba-cache-for-woocommerce' ) );
?>
                    </p>
                </div>
                
                    <div class="mamba-stats-grid" id="mamba-media-stats">
                        <div class="mamba-stat-card">
                            <div class="mamba-stat-header">
                                <span class="dashicons dashicons-images-alt"></span>
                                <h4><?php 
echo esc_html( __( 'Total Images', 'mamba-cache-for-woocommerce' ) );
?></h4>
                            </div>
                            <div class="mamba-stat-value" id="stat-total"><?php 
echo esc_html( number_format( $stats['total'] ) );
?></div>
                            <div class="mamba-stat-description"><?php 
echo esc_html( __( 'All media library images', 'mamba-cache-for-woocommerce' ) );
?></div>
                        </div>
                        
                        <div class="mamba-stat-card">
                            <div class="mamba-stat-header">
                                <span class="dashicons dashicons-admin-appearance"></span>
                                <h4><?php 
echo esc_html( __( 'Eligible for Optimization', 'mamba-cache-for-woocommerce' ) );
?></h4>
                            </div>
                            <div class="mamba-stat-value" id="stat-eligible"><?php 
echo esc_html( number_format( $stats['eligible'] ) );
?></div>
                            <div class="mamba-stat-description"><?php 
echo esc_html( __( 'JPEG/PNG images', 'mamba-cache-for-woocommerce' ) );
?></div>
                        </div>
                        
                        <div class="mamba-stat-card">
                            <div class="mamba-stat-header">
                                <span class="dashicons dashicons-yes-alt"></span>
                                <h4><?php 
echo esc_html( __( 'Compressed', 'mamba-cache-for-woocommerce' ) );
?></h4>
                            </div>
                            <div class="mamba-stat-value" id="stat-compressed"><?php 
echo esc_html( number_format( $stats['compressed'] ) );
?></div>
                            <div class="mamba-stat-description" id="stat-compressed-pct">
                                <?php 
$compressionPercent = ( $stats['eligible'] > 0 ? round( $stats['compressed'] / $stats['eligible'] * 100, 1 ) : 0 );
// translators: %s is the percentage
printf( esc_html( __( '%s%% of eligible', 'mamba-cache-for-woocommerce' ) ), esc_html( $compressionPercent ) );
?>
                            </div>
                        </div>
                        
                        <div class="mamba-stat-card">
                            <div class="mamba-stat-header">
                                <span class="dashicons dashicons-admin-appearance"></span>
                                <h4><?php 
echo esc_html( __( 'Next-Gen Converted', 'mamba-cache-for-woocommerce' ) );
?></h4>
                            </div>
                            <div class="mamba-stat-value" id="stat-nextgen">
                                <?php 
if ( $enableWebPConversion ) {
    ?>
                                    <?php 
    echo esc_html( number_format( $stats['webp'] ) );
    ?> 
                                    <span style="font-size: 14px; opacity: 0.6;">(WebP)</span>
                                <?php 
} elseif ( $enableAvifConversion ) {
    ?>
                                    <?php 
    echo esc_html( number_format( $stats['avif'] ) );
    ?>
                                    <span style="font-size: 14px; opacity: 0.6;">(AVIF)</span>
                                <?php 
} else {
    ?>
                                    <?php 
    echo esc_html( number_format( $stats['webp'] + $stats['avif'] ) );
    ?>
                                <?php 
}
?>
                            </div>
                            <div class="mamba-stat-description" id="stat-nextgen-pct">
                                <?php 
if ( $enableWebPConversion ) {
    $pct = ( $stats['eligible'] > 0 ? round( $stats['webp'] / $stats['eligible'] * 100, 1 ) : 0 );
    printf( esc_html( __( '%s%% converted to WebP', 'mamba-cache-for-woocommerce' ) ), esc_html( $pct ) );
} elseif ( $enableAvifConversion ) {
    $pct = ( $stats['eligible'] > 0 ? round( $stats['avif'] / $stats['eligible'] * 100, 1 ) : 0 );
    printf( esc_html( __( '%s%% converted to AVIF', 'mamba-cache-for-woocommerce' ) ), esc_html( $pct ) );
} else {
    echo esc_html( __( 'Enable WebP or AVIF above', 'mamba-cache-for-woocommerce' ) );
}
?>
                            </div>
                        </div>
                    </div>
                    
            <div class="mamba-hint">
                        <?php 
echo esc_html( __( 'Bulk operations process generated image sizes by default. Enable "Include original (full size)" options above to also process original files.', 'mamba-cache-for-woocommerce' ) );
?>
            </div>
                    
                    
                    <div class="mamba-bulk-actions" id="mamba-bulk-actions">
                        <button type="button" class="button button-secondary" id="btn-bulk-compress" onclick="processBulkOperation('mamba_bulk_compress', 0)" style="<?php 
echo esc_attr( ( $enableImageCompression ? '' : 'display:none;' ) );
?>">
                            <span class="dashicons dashicons-images-alt2"></span>
                            <?php 
echo esc_html( __( 'Bulk Compress', 'mamba-cache-for-woocommerce' ) );
?>
                        </button>

                        <button type="button" class="button button-primary" id="btn-bulk-webp" onclick="processBulkOperation('mamba_bulk_webp', 0)" style="<?php 
echo esc_attr( ( $enableWebPConversion ? '' : 'display:none;' ) );
?>">
                            <span class="dashicons dashicons-admin-appearance"></span>
                            <?php 
echo esc_html( __( 'Convert to WebP', 'mamba-cache-for-woocommerce' ) );
?>
                        </button>
                        
                        <button type="button" class="button button-primary" id="btn-bulk-avif" onclick="processBulkOperation('mamba_bulk_avif', 0)" style="<?php 
echo esc_attr( ( $enableAvifConversion ? '' : 'display:none;' ) );
?>">
                            <span class="dashicons dashicons-images-alt"></span>
                            <?php 
echo esc_html( __( 'Convert to AVIF', 'mamba-cache-for-woocommerce' ) );
?>
                        </button>
                        
                        <p class="mamba-hint" id="bulk-no-features-hint" style="margin: 0; <?php 
echo esc_attr( ( !$enableWebPConversion && !$enableAvifConversion && !$enableImageCompression ? '' : 'display:none;' ) );
?>">
                            <span class="dashicons dashicons-info" style="color: #f59e0b;"></span>
                            <?php 
echo esc_html( __( 'Enable Image Compression, WebP, or AVIF conversion above to process existing images.', 'mamba-cache-for-woocommerce' ) );
?>
                        </p>
                        
                        <button type="button" class="button button-secondary" id="btn-revert" onclick="showRevertDialog()">
                            <span class="dashicons dashicons-undo"></span>
                            <?php 
echo esc_html( __( 'Revert Optimizations', 'mamba-cache-for-woocommerce' ) );
?>
                        </button>
                    </div>
                    
                    <div id="mamba-bulk-progress" style="display: none;">
                        <div class="mamba-progress-container">
                            <div class="mamba-progress-bar">
                                <div class="mamba-progress-fill"></div>
                                <div class="mamba-progress-percentage">0%</div>
                            </div>
                            <div class="mamba-progress-text"><?php 
echo esc_html( __( 'Starting...', 'mamba-cache-for-woocommerce' ) );
?></div>
                    </div>
  </div>
</div>

        <!-- Form Actions -->
        <div class="mamba-form-actions">
            <button type="submit" class="mamba-save-button">
                <span class="dashicons dashicons-saved"></span>
                <?php 
echo esc_html( __( 'Save Media Settings', 'mamba-cache-for-woocommerce' ) );
?>
            </button>
        </div>
    </form>
</div>

<?php 
ob_start();
?>
/* Media Overview Section */
.mamba-media-overview {
    margin-bottom: 30px;
}

.mamba-media-card {
    display: flex;
    align-items: center;
    gap: 20px;
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    width: 100%;
    max-width: -webkit-fill-available;
}

.mamba-media-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.mamba-media-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 8px;
    background: linear-gradient(135deg, #E68057 0%, #E6704D 100%);
    box-shadow: 0 2px 8px rgba(230, 128, 87, 0.2);
}

.mamba-media-icon .dashicons {
    font-size: 20px;
    width: 20px;
    height: 20px;
    color: #ffffff;
}

.mamba-media-content {
    flex: 1;
}

.mamba-media-title {
    margin: 0 0 6px 0;
    font-size: 16px;
    font-weight: 500;
    color: var(--mamba-dark);
}

.mamba-media-description {
    margin: 0;
    color: var(--mamba-muted);
    line-height: 1.4;
    font-size: 13px;
}

/* Optimization Sections */
.mamba-optimization-intro {
    margin-bottom: 20px;
}

.mamba-optimization-description {
    margin: 0;
    color: var(--mamba-muted);
    font-size: 13px;
    line-height: 1.4;
}

/* Optimization Grid */
.mamba-optimization-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 16px;
    margin: 20px 0;
}

.mamba-optimization-item {
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.mamba-optimization-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.mamba-optimization-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
}

.mamba-optimization-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 6px;
    background: linear-gradient(135deg, #E68057 0%, #E6704D 100%);
    color: #ffffff;
    font-size: 14px;
}

.mamba-optimization-content {
    flex: 1;
}

.mamba-optimization-name {
    margin: 0 0 4px 0;
    font-size: 12px;
    font-weight: 500;
    color: var(--mamba-dark);
    letter-spacing: 0.5px;
}

.mamba-optimization-item .mamba-optimization-description {
    margin: 0;
    font-size: 11px;
    color: var(--mamba-muted);
    line-height: 1.3;
}

/* Toggle Switch Styling */
.mamba-toggle-switch {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.mamba-toggle-switch input[type="checkbox"] {
    display: none;
}

.mamba-toggle-switch label {
    position: relative;
    padding-left: 44px;
    cursor: pointer;
    font-weight: 500;
    color: var(--mamba-text);
    font-size: 12px;
    user-select: none;
    line-height: 1.4;
}

.mamba-toggle-switch label::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 16px;
    background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
    border-radius: 4px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.mamba-toggle-switch label::after {
    content: '';
    position: absolute;
    left: 2px;
    top: 50%;
    transform: translateY(-50%);
    width: 12px;
    height: 12px;
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 3px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.mamba-toggle-switch input[type="checkbox"]:checked + label::before {
    background: linear-gradient(135deg, #E68057 0%, #E6704D 100%);
    box-shadow: inset 0 2px 4px rgba(230, 128, 87, 0.2);
}

.mamba-toggle-switch input[type="checkbox"]:checked + label::after {
    transform: translate(16px, -50%);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
}

/* Form Controls */
.mamba-select {
    width: 100%;
    padding: 6px 10px;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    background: white;
    font-size: 12px;
    color: var(--mamba-text);
    transition: all 0.2s ease;
}

.mamba-select:focus {
    outline: none;
    border-color: #E68057;
    box-shadow: 0 0 0 2px rgba(230, 128, 87, 0.1);
}

.mamba-range {
    width: 100%;
    height: 4px;
    border-radius: 2px;
    background: #e5e7eb;
    outline: none;
    -webkit-appearance: none;
}

.mamba-range::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background: #E68057;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.mamba-range::-moz-range-thumb {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background: #E68057;
    cursor: pointer;
    border: none;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* Server Support */
.mamba-server-support {
    margin: 20px 0;
}

.mamba-server-support-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
     border-radius: 6px;
    margin-bottom: 8px;
}

.mamba-server-support-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 4px;
    font-size: 12px;
}

.mamba-server-support-icon.success {
    background: #68BA7F;
    color: #ffffff;
}

.mamba-server-support-icon.warning {
    background: #f59e0b;
    color: #ffffff;
}

.mamba-server-support-content {
    flex: 1;
}

.mamba-server-support-title {
    margin: 0 0 2px 0;
    font-size: 12px;
    font-weight: 500;
    color: var(--mamba-dark);
}

.mamba-server-support-description {
     margin: 0;
     font-size: 11px;
    color: var(--mamba-muted);
}

.mamba-status-badge {
    display: inline-flex;
    align-items: center;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 0.5625rem;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    flex-shrink: 0;
    white-space: nowrap;
}

.mamba-status-success {
    background: linear-gradient(135deg, #68BA7F 0%, #5aa06f 100%);
    color: #ffffff;
}

.mamba-status-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: #ffffff;
}

/* Nginx Configuration */
.mamba-nginx-config {
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    padding: 16px;
    margin: 16px 0;
}

.mamba-nginx-config-title {
    margin: 0 0 8px 0;
    font-size: 12px;
     font-weight: 500;
    color: var(--mamba-dark);
}

.mamba-nginx-config-description {
    margin: 0 0 12px 0;
    font-size: 11px;
    color: var(--mamba-muted);
}

.mamba-nginx-config pre {
    background: #1a1a1a;
    color: #ffffff;
    padding: 12px;
    border-radius: 4px;
    font-size: 11px;
    line-height: 1.4;
    overflow-x: auto;
    margin: 0;
}

/* Stats Grid */
.mamba-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin: 20px 0;
}

.mamba-stat-card {
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 16px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.mamba-stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, #E68057, #ff6b35);
}

.mamba-stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.mamba-stat-header {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    margin-bottom: 10px;
}

.mamba-stat-header .dashicons {
    color: #E68057;
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.mamba-stat-header h4 {
    margin: 0;
    font-size: 0.5625rem;
    font-weight: 500;
    color: var(--mamba-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.mamba-stat-value {
     font-size: 14px;
    font-weight: 500;
    color: var(--mamba-dark);
    margin-bottom: 3px;
    line-height: 1.2;
}

.mamba-stat-description {
    font-size: 0.625rem;
    color: var(--mamba-muted);
    font-weight: 400;
}

/* Hints and Notices */
.mamba-hint {
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 6px;
    padding: 12px;
    margin: 12px 0;
    font-size: 11px;
    color: #0369a1;
}

.mamba-notice-box {
    background: #fef3c7;
    border: 1px solid #f59e0b;
     border-radius: 6px;
    padding: 12px;
    margin: 12px 0;
    font-size: 11px;
    color: #92400e;
}

/* Bulk Actions */
.mamba-bulk-actions {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 16px;
    margin: 20px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.mamba-bulk-actions button {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    height: 36px;
    line-height: 1;
    vertical-align: middle;
}

.mamba-bulk-actions .button .dashicons {
    line-height: 1;
    vertical-align: middle;
}

.mamba-progress-bar {
    width: 100%;
    height: 6px;
    background: #e5e7eb;
    border-radius: 3px;
    overflow: hidden;
    margin: 8px 0;
}

.mamba-progress-percentage {
    height: 100%;
    background: linear-gradient(90deg, #E68057, #ff6b35);
    transition: width 0.3s ease;
}

.mamba-progress-text {
    font-size: 11px;
    color: var(--mamba-muted);
    text-align: center;
    margin-top: 4px;
}

/* Form Actions */
.mamba-form-actions {
    display: flex;
    justify-content: center;
    padding: 24px 0;
    border-top: 1px solid #f1f5f9;
    margin-top: 24px;
    gap: 10px;
}

.mamba-save-button {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 10px 20px;
    background: linear-gradient(135deg, #E68057 0%, #E6704D 100%);
    border: none;
     border-radius: 6px;
    color: #ffffff;
     font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(230, 128, 87, 0.2);
}

.mamba-save-button:hover {
    background: linear-gradient(135deg, #d45a3a 0%, #c24a2a 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(230, 128, 87, 0.3);
}

.mamba-save-button .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

/* Responsive Design */
@media (max-width: 1200px) {
    .mamba-optimization-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .mamba-stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    }
    
@media (max-width: 768px) {
    .mamba-media-card {
        flex-direction: column;
        text-align: center;
        gap: 12px;
    }
    
    .mamba-optimization-grid {
        grid-template-columns: 1fr;
    }
    
    .mamba-stats-grid {
        grid-template-columns: 1fr;
    }
    
    .mamba-optimization-header {
        flex-direction: column;
        text-align: center;
        gap: 6px;
    }
    
    .mamba-form-actions {
        flex-direction: column;
        align-items: center;
    }
}
<?php 
$__tab_css = ob_get_clean();
wp_register_style( 'mamba-tab-media-inline', false );
wp_enqueue_style( 'mamba-tab-media-inline' );
wp_add_inline_style( 'mamba-tab-media-inline', $__tab_css );
wp_print_styles( ['mamba-tab-media-inline'] );
?>

<?php 
ob_start();
?>
jQuery(document).ready(function($) {
    const BATCH_SIZE = 3; // Small batch to prevent 504 gateway timeouts
    let totalProcessed = 0;
    let totalSuccesses = 0;
    let totalFailures = 0;
    
    function showProgress() {
        $('#mamba-bulk-progress').show();
        $('.mamba-bulk-actions button').prop('disabled', true);
        totalProcessed = 0;
        totalSuccesses = 0;
        totalFailures = 0;
    }
    
    function hideProgress() {
        $('#mamba-bulk-progress').hide();
        $('.mamba-bulk-actions button').prop('disabled', false);
    }
    
    function updateProgress(percent, text, memoryInfo = null) {
        $('.mamba-progress-fill').css('width', percent + '%');
        $('.mamba-progress-percentage').text(Math.round(percent) + '%');
        let progressText = text;
        if (memoryInfo) {
            progressText += ` (Memory: ${memoryInfo.current})`;
        }
        $('.mamba-progress-text').html(progressText);
    }
    
    function processBulkOperation(action, cursor = 0, type = '') {
        // Only block *manual* starts; internal continuations keep going
        if (!window.mambaBulkRunning) {
            window.mambaBulkRunning = true;
            showProgress();
            updateProgress(0, 'Starting...');
            
            // Fallback timeout to prevent getting stuck on "Starting..."
            window.mambaFallbackTimeout = setTimeout(() => {
                if (totalProcessed === 0) {
                    console.error('Bulk operation appears stuck, checking for issues...');
                    updateProgress(0, '<span style="color: orange;">⚠️ Operation taking longer than expected. Check browser console for errors.</span>');
                }
            }, 10000); // 10 seconds fallback
        }
        
        console.log('Processing batch:', action, 'cursor:', cursor, 'type:', type);
        
        const data = {
            action: action,
            nonce: '<?php 
echo esc_js( wp_create_nonce( 'mamba_bulk_optimize' ) );
?>',
            cursor: cursor,
            batch_size: BATCH_SIZE
        };
        
        if (type) {
            data.type = type;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: data,
            timeout: 60000, // Reduced to 1 minute for faster feedback
            beforeSend: function(xhr, settings) {
                console.log('AJAX request starting:', settings.url, settings.data);
            },
            success: function(response) {
                console.log('AJAX response received:', response);
                
                // Clear fallback timeout since we got a response
                if (window.mambaFallbackTimeout) {
                    clearTimeout(window.mambaFallbackTimeout);
                    window.mambaFallbackTimeout = null;
                }
                
                if (response.success) {
                    // Reset retry count on success
                    window.mambaRetryCount = 0;
                    
                    const data = response.data;
                    const successes = data.results.filter(r => r.success === true).length;
                    const failures = data.results.filter(r => r.success === false).length;
                    const processed = data.results.length;
                    const hasMore = data.has_more;
                    
                    // Update totals
                    totalProcessed += processed;
                    totalSuccesses += successes;
                    totalFailures += failures;
                    
                    // Build progress message
                    let progressMsg = `Processed ${totalProcessed} images`;
                    if (totalSuccesses > 0) progressMsg += ` • <span style="color: green;">✓ ${totalSuccesses}</span>`;
                    if (totalFailures > 0) progressMsg += ` • <span style="color: red;">✗ ${totalFailures}</span>`;
                    
                    // Calculate more accurate progress percentage
                    const progressPercent = hasMore ? Math.min(95, (totalProcessed / (totalProcessed + 5)) * 100) : 100;
                    
                    updateProgress(progressPercent, progressMsg, data.memory_usage);
                    
                    if (hasMore) {
                        // Continue immediately without delay
                        processBulkOperation(action, data.cursor, type);
                    } else {
                        // Check if we're doing "optimize all" and need to continue
                        if (window.mambaOptimizeAll && action === 'mamba_bulk_compress') {
                            if (window.mambaAvifSupported) {
                                updateProgress(50, 'Compression complete. Starting AVIF conversion...');
                                setTimeout(() => { processBulkOperation('mamba_bulk_avif', 0); }, 500);
                                return;
                            } else if (window.mambaWebPSupported) {
                                updateProgress(50, 'Compression complete. Starting WebP conversion...');
                                setTimeout(() => { processBulkOperation('mamba_bulk_webp', 0); }, 500);
                                return;
                            }
                        } else if (window.mambaOptimizeAll && action === 'mamba_bulk_avif' && window.mambaWebPSupported) {
                            // Rare case if both are enabled (though UI prevents it, technically possible if toggled manually)
                            updateProgress(75, 'AVIF complete. Starting WebP conversion...');
                            setTimeout(() => { processBulkOperation('mamba_bulk_webp', 0); }, 500);
                            return;
                        }
                        
                        window.mambaOptimizeAll = false;
                        
                        const finalMsg = totalSuccesses > 0 
                            ? `<span style="color: green;">✅ Completed! ${totalSuccesses} images optimized</span>${totalFailures > 0 ? ` <span style="color: orange;">(${totalFailures} failed)</span>` : ''}`
                            : totalFailures > 0 ? `<span style="color: orange;">⚠️ Completed with ${totalFailures} failures</span>` : '<span style="color: green;">✅ All done!</span>';
                        updateProgress(100, finalMsg);
                        setTimeout(() => { 
                            hideProgress(); 
                            window.mambaBulkRunning = false;
                            // Show success notification and refresh stats
                            if (totalSuccesses > 0) {
                                $('<div class="notice notice-success is-dismissible"><p>Optimization completed successfully! ' + totalSuccesses + ' images processed. Refreshing stats...</p></div>').insertAfter('.mamba-admin-wrap form');
                                // Refresh the page to update stats
                                setTimeout(() => {
                                    location.reload();
                                }, 1500);
                            }
                        }, 3000);
                    }
                } else {
                    console.error('AJAX request failed:', response);
                    const reason = typeof response.data === 'string' ? response.data : (response.data?.message || 'Unknown error');
                    updateProgress(0, `<span style="color: red;">❌ Error: ${reason}</span>`);
                    setTimeout(() => { 
                        hideProgress(); 
                        window.mambaBulkRunning = false; 
                    }, 3000);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX network error:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText,
                    readyState: xhr.readyState,
                    statusText: xhr.statusText
                });
                
                // Clear fallback timeout
                if (window.mambaFallbackTimeout) {
                    clearTimeout(window.mambaFallbackTimeout);
                    window.mambaFallbackTimeout = null;
                }
                
                let errorMsg = 'Network error occurred';
                if (status === 'timeout') {
                    errorMsg = 'Request timed out - server may be overloaded';
                } else if (xhr.status === 403) {
                    errorMsg = 'Permission denied - check user capabilities';
                } else if (xhr.status === 500) {
                    errorMsg = 'Server error - check error logs';
                } else if (xhr.responseJSON?.data) {
                    errorMsg = xhr.responseJSON.data;
                } else if (error) {
                    errorMsg = error;
                }
                
                // Add retry logic for timeout/504 errors - retry up to 3 times
                window.mambaRetryCount = window.mambaRetryCount || 0;
                if ((status === 'timeout' || xhr.status === 504) && window.mambaRetryCount < 3) {
                    window.mambaRetryCount++;
                    updateProgress(totalProcessed > 0 ? 50 : 0, `<span style="color: orange;">⚠️ Server timeout - Retrying (${window.mambaRetryCount}/3)...</span>`);
                    setTimeout(() => {
                        processBulkOperation(action, cursor, type);
                    }, 3000);
                    return;
                }
                
                // Reset retry count on other errors or after max retries
                window.mambaRetryCount = 0;
                updateProgress(0, `<span style="color: red;">❌ ${errorMsg}</span>`);
                setTimeout(() => { 
                    hideProgress(); 
                    window.mambaBulkRunning = false; 
                }, 3000);
            }
        });
    }
    
    function showRevertDialog() {
        // Build options based on what has been optimized
        const compressed = <?php 
echo (int) $stats['compressed'];
?>;
        const webp = <?php 
echo (int) $stats['webp'];
?>;
        const avif = <?php 
echo (int) $stats['avif'];
?>;
        
        let options = [];
        if (compressed > 0) options.push('compression (' + compressed + ' images)');
        if (webp > 0) options.push('webp (' + webp + ' images)');
        if (avif > 0) options.push('avif (' + avif + ' images)');
        
        if (options.length === 0) {
            alert('No optimizations to revert.');
            return;
        }
        
        const type = prompt('What would you like to revert?\n\nAvailable options:\n• ' + options.join('\n• ') + '\n\nEnter: compression, webp, or avif');
        
        if (type && (type === 'compression' || type === 'webp' || type === 'avif')) {
            const count = type === 'compression' ? compressed : (type === 'webp' ? webp : avif);
            if (count === 0) {
                alert('No ' + type + ' optimizations to revert.');
                return;
            }
            if (confirm(`Are you sure you want to revert ${count} ${type} optimizations?\n\nThis will restore the original images from backups.`)) {
                processBulkOperation('mamba_bulk_revert', 0, type);
            }
        } else if (type) {
            alert('Invalid option. Please enter "compression", "webp", or "avif".');
        }
    }
    
    // Combined optimization function
    function processBulkOptimizeAll() {
        if (window.mambaBulkRunning) {
            return;
        }
        
        // Determine what to run based on support
        const webpSupported = <?php 
echo ( wp_image_editor_supports( [
    'mime_type' => 'image/webp',
] ) ? 'true' : 'false' );
?>;
        const avifSupported = <?php 
echo ( wp_image_editor_supports( [
    'mime_type' => 'image/avif',
] ) ? 'true' : 'false' );
?>;
        const compressionEnabled = $('input[name="mamba_enable_image_compression"]').is(':checked');
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        
        if (!compressionEnabled && !webpEnabled && !avifEnabled) {
            alert('Please enable at least one optimization feature above first.');
            return;
        }

        window.mambaOptimizeAll = true;
        window.mambaWebPSupported = webpSupported && webpEnabled;
        window.mambaAvifSupported = avifSupported && avifEnabled;
        
        // Start with compression if enabled
        if (compressionEnabled) {
            processBulkOperation('mamba_bulk_compress', 0);
        } else if (window.mambaAvifSupported) {
            processBulkOperation('mamba_bulk_avif', 0);
        } else if (window.mambaWebPSupported) {
            processBulkOperation('mamba_bulk_webp', 0);
        } else {
            alert('No enabled/supported features to process.');
            window.mambaOptimizeAll = false;
        }
    }
    
    // Handle conditional settings visibility and mutual exclusivity
    function updateSettingVisibility() {
        // Image Compression
        const compressionEnabled = $('input[name="mamba_enable_image_compression"]').is(':checked');
        $('.mamba-optimization-item').each(function() {
            if ($(this).find('input[name="mamba_compression_quality"], select[name="mamba_compression_type"], input[name="mamba_compress_full_size"]').length) {
                $(this).css({
                    'opacity': compressionEnabled ? '1' : '0.5',
                    'pointer-events': compressionEnabled ? 'auto' : 'none'
                });
            }
        });
        
        // WebP Conversion
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        $('.mamba-optimization-item').each(function() {
            if ($(this).find('input[name="mamba_webp_quality"], input[name="mamba_convert_full_size"]').length) {
                $(this).css({
                    'opacity': webpEnabled ? '1' : '0.5',
                    'pointer-events': webpEnabled ? 'auto' : 'none'
                });
            }
        });

        // AVIF Conversion
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        $('.mamba-optimization-item').each(function() {
            if ($(this).find('input[name="mamba_avif_quality"], input[name="mamba_convert_full_size_avif"]').length) {
                $(this).css({
                    'opacity': avifEnabled ? '1' : '0.5',
                    'pointer-events': avifEnabled ? 'auto' : 'none'
                });
            }
        });
    }
    
    // Initialize and bind events
    updateSettingVisibility();
    
    // Update bulk action buttons based on current checkbox state
    function updateBulkActionButtons() {
        const compressionEnabled = $('input[name="mamba_enable_image_compression"]').is(':checked');
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        
        // Show/hide buttons based on checkbox state
        $('#btn-bulk-compress').toggle(compressionEnabled);
        $('#btn-bulk-webp').toggle(webpEnabled);
        $('#btn-bulk-avif').toggle(avifEnabled);
        
        // Show hint if nothing is enabled
        $('#bulk-no-features-hint').toggle(!compressionEnabled && !webpEnabled && !avifEnabled);
    }
    
    // AJAX save function for live settings
    function saveMediaSetting(setting, value, callback) {
        $.post(ajaxurl, {
            action: 'mamba_save_media_setting',
            nonce: '<?php 
echo esc_js( wp_create_nonce( 'mamba_media_settings' ) );
?>',
            setting: setting,
            value: value
        }, function(response) {
            if (response.success) {
                // Update UI based on response
                if (response.data.webp_enabled !== undefined) {
                    $('input[name="mamba_enable_webp_conversion"]').prop('checked', response.data.webp_enabled);
                }
                if (response.data.avif_enabled !== undefined) {
                    $('input[name="mamba_enable_avif_conversion"]').prop('checked', response.data.avif_enabled);
                }
                // Update Nginx config snippet if provided
                if (response.data.nginx_config) {
                    updateNginxSnippet(response.data.nginx_config, response.data.avif_enabled);
                }
                // Update stats if provided
                if (response.data.stats) {
                    updateStatsDisplay(response.data.stats);
                }
                // Show success indicator
                showSettingSaved();
            }
            if (callback) callback(response);
        });
    }
    
    // Update Nginx snippet display
    function updateNginxSnippet(config, isAvif) {
        const $nginxSection = $('.mamba-nginx-config');
        if ($nginxSection.length) {
            $nginxSection.find('pre code').text(config);
            const title = isAvif ? 'Nginx AVIF Configuration' : 'Nginx WebP Configuration';
            const desc = isAvif 
                ? 'Add this to your nginx.conf or site configuration to serve AVIF images:'
                : 'Add this to your nginx.conf or site configuration to serve WebP images:';
            $nginxSection.find('.mamba-nginx-config-title').text(title);
            $nginxSection.find('.mamba-nginx-config-description').text(desc);
        }
        // Show/hide nginx section based on whether any format is enabled
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        $('.mamba-server-support').has('.mamba-nginx-config').toggle(webpEnabled || avifEnabled);
    }
    
    // Update stats display
    function updateStatsDisplay(stats) {
        $('#stat-total').text(stats.total.toLocaleString());
        $('#stat-eligible').text(stats.eligible.toLocaleString());
        $('#stat-compressed').text(stats.compressed.toLocaleString());
        
        const compressionPct = stats.eligible > 0 ? ((stats.compressed / stats.eligible) * 100).toFixed(1) : 0;
        $('#stat-compressed-pct').text(compressionPct + '% of eligible');
        
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        
        if (webpEnabled) {
            $('#stat-nextgen').html(stats.webp.toLocaleString() + ' <span style="font-size: 14px; opacity: 0.6;">(WebP)</span>');
            const pct = stats.eligible > 0 ? ((stats.webp / stats.eligible) * 100).toFixed(1) : 0;
            $('#stat-nextgen-pct').text(pct + '% converted to WebP');
        } else if (avifEnabled) {
            $('#stat-nextgen').html(stats.avif.toLocaleString() + ' <span style="font-size: 14px; opacity: 0.6;">(AVIF)</span>');
            const pct = stats.eligible > 0 ? ((stats.avif / stats.eligible) * 100).toFixed(1) : 0;
            $('#stat-nextgen-pct').text(pct + '% converted to AVIF');
        } else {
            $('#stat-nextgen').text((stats.webp + stats.avif).toLocaleString());
            $('#stat-nextgen-pct').text('Enable WebP or AVIF above');
        }
    }
    
    // Show brief "Saved" indicator
    function showSettingSaved() {
        let $indicator = $('#mamba-save-indicator');
        if (!$indicator.length) {
            $indicator = $('<div id="mamba-save-indicator" style="position: fixed; top: 50px; right: 20px; background: #10b981; color: white; padding: 10px 20px; border-radius: 6px; z-index: 99999; display: none; font-weight: 500;"><span class="dashicons dashicons-yes" style="margin-right: 5px;"></span>Saved</div>');
            $('body').append($indicator);
        }
        $indicator.fadeIn(200).delay(1000).fadeOut(200);
    }
    
    // Enforce mutual exclusivity between WebP and AVIF with live save
    $('input[name="mamba_enable_webp_conversion"]').on('change', function() {
        const isChecked = $(this).is(':checked');
        if (isChecked) {
            $('input[name="mamba_enable_avif_conversion"]').prop('checked', false);
        }
        saveMediaSetting('mamba_enable_webp_conversion', isChecked ? 1 : 0);
        updateSettingVisibility();
        updateNextGenInfo();
        updateBulkActionButtons();
    });
    
    $('input[name="mamba_enable_avif_conversion"]').on('change', function() {
        const isChecked = $(this).is(':checked');
        if (isChecked) {
            $('input[name="mamba_enable_webp_conversion"]').prop('checked', false);
        }
        saveMediaSetting('mamba_enable_avif_conversion', isChecked ? 1 : 0);
        updateSettingVisibility();
        updateNextGenInfo();
        updateBulkActionButtons();
    });
    
    $('input[name="mamba_enable_image_compression"]').on('change', function() {
        saveMediaSetting('mamba_enable_image_compression', $(this).is(':checked') ? 1 : 0);
        updateSettingVisibility();
        updateBulkActionButtons();
    });
    
    // Live save for LCP optimization
    $('input[name="mamba_enable_lcp_optimization"]').on('change', function() {
        saveMediaSetting('mamba_enable_lcp_optimization', $(this).is(':checked') ? 1 : 0);
    });
    
    // Live save for quality sliders and other inputs
    $('input[name="mamba_compression_quality"], input[name="mamba_webp_quality"], input[name="mamba_avif_quality"]').on('change', function() {
        saveMediaSetting($(this).attr('name'), $(this).val());
    });
    
    $('select[name="mamba_compression_type"]').on('change', function() {
        saveMediaSetting('mamba_compression_type', $(this).val());
    });
    
    $('input[name="mamba_compress_full_size"], input[name="mamba_convert_full_size"], input[name="mamba_convert_full_size_avif"]').on('change', function() {
        saveMediaSetting($(this).attr('name'), $(this).is(':checked') ? 1 : 0);
    });
    
    // Initialize bulk action buttons on page load
    updateBulkActionButtons();
    
    // Show info about selected next-gen format
    function updateNextGenInfo() {
        const webpEnabled = $('input[name="mamba_enable_webp_conversion"]').is(':checked');
        const avifEnabled = $('input[name="mamba_enable_avif_conversion"]').is(':checked');
        
        // Remove existing hints
        $('.mamba-nextgen-hint').remove();
        
        if (avifEnabled) {
            const hint = $('<div class="mamba-nextgen-hint mamba-hint" style="margin-top: 15px; background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%); border: 1px solid #6ee7b7; border-left: 4px solid #10b981;">' +
                '<span class="dashicons dashicons-yes-alt" style="color: #10b981; margin-right: 8px;"></span>' +
                '<strong>AVIF Selected:</strong> AVIF provides up to 50% better compression than JPEG. Supported by Chrome 85+, Firefox 93+, Safari 16+. Images will be served as AVIF to supported browsers.' +
                '</div>');
            $('.mamba-form-section').has('input[name="mamba_enable_avif_conversion"]').find('.mamba-optimization-grid').after(hint);
        } else if (webpEnabled) {
            const hint = $('<div class="mamba-nextgen-hint mamba-hint" style="margin-top: 15px; background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); border: 1px solid #93c5fd; border-left: 4px solid #3b82f6;">' +
                '<span class="dashicons dashicons-yes-alt" style="color: #3b82f6; margin-right: 8px;"></span>' +
                '<strong>WebP Selected:</strong> WebP provides ~30% better compression than JPEG with excellent browser support (95%+). A reliable choice for most stores.' +
                '</div>');
            $('.mamba-form-section').has('input[name="mamba_enable_webp_conversion"]').find('.mamba-optimization-grid').after(hint);
        }
    }
    
    // Initialize info on page load
    updateNextGenInfo();
    
    // Make functions globally available
    window.processBulkOperation = processBulkOperation;
    window.showRevertDialog = showRevertDialog;
    window.processBulkOptimizeAll = processBulkOptimizeAll;
     
     // Copy to clipboard function
     window.copyToClipboard = function(element) {
         const text = element.textContent;
         const copyBtn = element.nextElementSibling;
         const copyText = copyBtn.querySelector('.copy-text');
         const copiedText = copyBtn.querySelector('.copied-text');
         
         navigator.clipboard.writeText(text).then(function() {
             copyText.style.display = 'none';
             copiedText.style.display = 'inline';
             
             setTimeout(function() {
                 copyText.style.display = 'inline';
                 copiedText.style.display = 'none';
             }, 2000);
         }).catch(function() {
             // Fallback for older browsers
             const textArea = document.createElement('textarea');
             textArea.value = text;
             document.body.appendChild(textArea);
             textArea.select();
             document.execCommand('copy');
             document.body.removeChild(textArea);
             
             copyText.style.display = 'none';
             copiedText.style.display = 'inline';
             
             setTimeout(function() {
                 copyText.style.display = 'inline';
                 copiedText.style.display = 'none';
             }, 2000);
         });
     };
 });
<?php 
wp_add_inline_script( 'mamba-admin', ob_get_clean() );
?>

<?php 
$media_extra_css = '.mamba-section-header{margin-bottom:24px}.mamba-section-title{display:flex;align-items:center;gap:8px;margin:0 0 8px 0;font-size:12px;font-weight:500;color:var(--mamba-dark);letter-spacing:0.5px}.mamba-section-title .dashicons{color:#E68057;font-size:16px;width:16px;height:16px}.mamba-optimization-name{margin:0 0 4px 0;font-size:12px;font-weight:500;color:var(--mamba-dark);letter-spacing:0.5px}';
wp_register_style( 'mamba-tab-media-extra-inline', false );
wp_enqueue_style( 'mamba-tab-media-extra-inline' );
wp_add_inline_style( 'mamba-tab-media-extra-inline', $media_extra_css );
wp_print_styles( ['mamba-tab-media-extra-inline'] );
?>


