<?php
/**
 * Settings Page for StaticQ
 * 
 * @package suspended-cloud/cloudflare-media-offload
 * @since 2.0.0
 */

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

class SQMedia_Settings_Page {
    
    /**
     * Render the settings page
     */
    public function render(): void {
        // Handle form submission
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified on the same line via check_admin_referer().
        if (isset($_POST['sqmedia_save_settings']) && check_admin_referer('sqmedia_settings_nonce')) {
            $this->save_settings();
            echo '<div class="notice notice-success"><p>' . esc_html__('Settings saved.', 'staticq-media') . '</p></div>';
        }
        
        $settings = SQMedia_Settings::get_instance();
        $all_settings = $settings->get_all();
        ?>
        <div class="wrap sqmedia-admin-wrap">
            <h1><?php esc_html_e('StaticQ Settings', 'staticq-media'); ?></h1>
            
            <form method="post" action="">
                <?php wp_nonce_field('sqmedia_settings_nonce'); ?>
                
                <!-- =======================================================================
                     SECTION 1: Plugin Status
                     ======================================================================= -->
                <div class="sqmedia-settings-section">
                    <h2>📁 <?php esc_html_e('Plugin Status', 'staticq-media'); ?></h2>
                    
                    <?php $this->render_upload_status($all_settings); ?>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Enable Upload Interception', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_enabled" id="sqmedia_enabled" value="1" <?php checked(!empty($all_settings['enabled'])); ?>>
                                    <?php esc_html_e('Intercept WordPress uploads and apply plugin settings', 'staticq-media'); ?>
                                </label>
                                <p class="description">
                                    <strong><?php esc_html_e('What this controls:', 'staticq-media'); ?></strong><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Enabled:', 'staticq-media'); ?></strong> <?php esc_html_e("Plugin intercepts NEW WordPress uploads and applies the plugin's settings to them", 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Disabled:', 'staticq-media'); ?></strong> <?php esc_html_e('WordPress handles NEW uploads normally', 'staticq-media'); ?><br>
                                    <br>
                                    <strong><?php esc_html_e('What continues to work when disabled:', 'staticq-media'); ?></strong><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;✓ <?php esc_html_e('Background cron processing (processes pending queue items)', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;✓ <?php esc_html_e('Registration tool (can add old images to queue for processing)', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;✓ <?php esc_html_e('All scan and repair tools continue to operate', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;✓ <?php esc_html_e('Dashboard, statistics, and reports remain accessible', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Manage All Media', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_manage_all_media" id="sqmedia_manage_all_media" value="1" <?php checked(!empty($all_settings['manage_all_media'])); ?> <?php disabled(empty($all_settings['enabled'])); ?>>
                                    <?php esc_html_e('Also manage non-image files (PDFs, documents, etc.)', 'staticq-media'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('When enabled, the plugin will offload all media uploads to cloud storage, not just images. PDF preview thumbnails will also be processed.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <?php ob_start(); ?>
                    (function() {
                        var enabled = document.getElementById('sqmedia_enabled');
                        var allMedia = document.getElementById('sqmedia_manage_all_media');
                        if (!enabled || !allMedia) return;
                        function toggle() {
                            allMedia.disabled = !enabled.checked;
                            allMedia.closest('tr').style.opacity = allMedia.disabled ? '0.5' : '1';
                        }
                        toggle();
                        enabled.addEventListener('change', toggle);
                    })();
                    <?php wp_add_inline_script('sqmedia-admin', ob_get_clean()); ?>
                </div>

                <!-- =======================================================================
                     SECTION 2: Storage Configuration
                     ======================================================================= -->
                <div class="sqmedia-settings-section">
                    <h2>💾 <?php esc_html_e('Storage', 'staticq-media'); ?></h2>
                    <p class="description"><?php esc_html_e('Configure where your media files should be stored.', 'staticq-media'); ?></p>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Storage Mode', 'staticq-media'); ?></th>
                            <td>
                                <?php $storage_mode = $all_settings['storage_mode'] ?? 'cloud_only'; ?>
                                <select name="sqmedia_storage_mode" id="sqmedia_storage_mode" class="sqmedia-provider-select">
                                    <option value="local_only" <?php selected($storage_mode, 'local_only'); ?>>
                                        📐 <?php esc_html_e('Local Only — Files stay on your server', 'staticq-media'); ?>
                                    </option>
                                    <option value="cloud_and_local" <?php selected($storage_mode, 'cloud_and_local'); ?>>
                                        📐☁️ <?php esc_html_e('Local + Cloud — Files on both (redundancy)', 'staticq-media'); ?>
                                    </option>
                                    <option value="cloud_only" <?php selected($storage_mode, 'cloud_only'); ?>>
                                        ☁️ <?php esc_html_e('Cloud Only — Files in bucket, delete local after upload', 'staticq-media'); ?>
                                    </option>
                                </select>
                                <p class="description">
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Local Only:', 'staticq-media'); ?></strong> <?php esc_html_e('No cloud upload. Files remain on your WordPress server only.', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Local + Cloud:', 'staticq-media'); ?></strong> <?php esc_html_e('Upload to cloud storage while keeping local copies for backup/redundancy.', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Cloud Only:', 'staticq-media'); ?></strong> <?php esc_html_e('Upload to cloud storage and delete local files to save disk space.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    
                    <!-- Cloud Storage Provider Settings (hidden when local_only) -->
                    <div id="sqmedia-cloud-storage-settings" class="sqmedia-conditional-section">
                        <input type="hidden" name="sqmedia_storage_provider" id="sqmedia_storage_provider" value="r2">

                        <!-- === Cloudflare R2 Settings === -->
                        <div id="sqmedia-r2-settings" class="sqmedia-provider-settings" data-provider="r2">
                            <h3>🔶 <?php esc_html_e('Cloudflare R2 Configuration', 'staticq-media'); ?></h3>
                            
                            <!-- R2 Setup Instructions -->
                            <div class="sqmedia-setup-guide" style="background: #f0f6fc; border: 1px solid #c3d9ed; border-radius: 4px; padding: 15px; margin-bottom: 20px;">
                                <h4 style="margin-top: 0; color: #1d4ed8;">📉 <?php esc_html_e('How to Create R2 API Credentials', 'staticq-media'); ?></h4>
                                <ol style="margin-bottom: 10px; padding-left: 20px;">
                                    <li><?php esc_html_e('Go to the Cloudflare dashboard → R2 Object Storage', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Click "Manage R2 API Tokens" in the right sidebar (under Account details)', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Click "Create API token"', 'staticq-media'); ?></li>
                                    <li><strong><?php esc_html_e('Permissions:', 'staticq-media'); ?></strong> <?php esc_html_e('Select "Object Read & Write"', 'staticq-media'); ?></li>
                                    <li><strong><?php esc_html_e('Specify bucket(s):', 'staticq-media'); ?></strong> <?php esc_html_e('Select "Apply to specific buckets only" and choose your media bucket', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Set TTL (optional): Leave as "Forever" or set an expiration', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Click "Create API Token"', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Copy the Access Key ID and Secret Access Key shown (you won\'t see the secret again!)', 'staticq-media'); ?></li>
                                </ol>
                                <p style="margin-bottom: 0;">
                                    <a href="https://dash.cloudflare.com/?to=/:account/r2/api-tokens" target="_blank" class="button button-secondary">🔑 <?php esc_html_e('Open R2 API Tokens Page', 'staticq-media'); ?></a>
                                    <a href="https://dash.cloudflare.com/?to=/:account/r2/new" target="_blank" class="button button-secondary" style="margin-left: 10px;">➕ <?php esc_html_e('Create New R2 Bucket', 'staticq-media'); ?></a>
                                </p>
                            </div>
                            
                            <?php 
                            // Check if credentials are in wp-config.php
                            $r2_creds_in_config = SQMedia_Settings::are_r2_credentials_in_config();
                            if ($r2_creds_in_config): 
                            ?>
                            <div class="sqmedia-config-notice" style="background: #d1fae5; border: 1px solid #6ee7b7; border-radius: 4px; padding: 12px; margin-bottom: 20px;">
                                <span style="color: #065f46;">✓ <?php esc_html_e('R2 credentials are securely stored in wp-config.php', 'staticq-media'); ?></span>
                            </div>
                            <?php endif; ?>
                            
                            <table class="form-table">
                                <tr>
                                    <th scope="row"><?php esc_html_e('Account ID', 'staticq-media'); ?></th>
                                    <td>
                                        <?php 
                                        $r2_account_id = $all_settings['r2_account_id'] ?? '';
                                        $r2_account_from_config = defined('SQMEDIA_R2_ACCOUNT_ID');
                                        if ($r2_account_from_config) {
                                            $r2_account_id = SQMEDIA_R2_ACCOUNT_ID;
                                        }
                                        ?>
                                        <input type="text" name="sqmedia_r2_account_id" value="<?php echo esc_attr($r2_account_id); ?>" class="regular-text" placeholder="f01c2d59171158f26d6e62596826841f" <?php if ( $r2_account_from_config ) { echo 'readonly'; } ?>>
                                        <p class="description">
                                            <?php if ($r2_account_from_config): ?>
                                                <span style="color: #059669;">✓ <?php esc_html_e('Loaded from SQMEDIA_R2_ACCOUNT_ID in wp-config.php', 'staticq-media'); ?></span>
                                            <?php else: ?>
                                                <?php esc_html_e('Your 32-character Cloudflare Account ID. Find it in the R2 dashboard URL or in the right sidebar.', 'staticq-media'); ?>
                                            <?php endif; ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Access Key ID', 'staticq-media'); ?></th>
                                    <td>
                                        <?php $r2_access_key_in_config = defined('SQMEDIA_R2_ACCESS_KEY_ID'); ?>
                                        <?php if ($r2_access_key_in_config): ?>
                                            <input type="text" value="••••••••••••••••" class="regular-text" readonly>
                                            <p class="description" style="color: #059669;">✓ <?php esc_html_e('Loaded from SQMEDIA_R2_ACCESS_KEY_ID in wp-config.php', 'staticq-media'); ?></p>
                                        <?php else: ?>
                                            <input type="text" name="sqmedia_r2_access_key_id" value="<?php echo esc_attr($all_settings['r2_access_key_id'] ?? ''); ?>" class="regular-text" placeholder="e.g., 1a2b3c4d5e6f7g8h9i0j">
                                            <p class="description"><?php esc_html_e('The Access Key ID from your R2 API token.', 'staticq-media'); ?></p>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Secret Access Key', 'staticq-media'); ?></th>
                                    <td>
                                        <?php $r2_secret_in_config = defined('SQMEDIA_R2_SECRET_ACCESS_KEY'); ?>
                                        <?php if ($r2_secret_in_config): ?>
                                            <input type="password" value="••••••••••••••••••••••••••••••••" class="regular-text" readonly>
                                            <p class="description" style="color: #059669;">✓ <?php esc_html_e('Loaded from SQMEDIA_R2_SECRET_ACCESS_KEY in wp-config.php', 'staticq-media'); ?></p>
                                        <?php else: ?>
                                            <input type="password" name="sqmedia_r2_secret_access_key" value="<?php echo esc_attr($all_settings['r2_secret_access_key'] ?? ''); ?>" class="regular-text" placeholder="Your secret access key">
                                            <p class="description"><?php esc_html_e('The Secret Access Key from your R2 API token.', 'staticq-media'); ?></p>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                
                                <?php if (!$r2_creds_in_config): ?>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Security Recommendation', 'staticq-media'); ?></th>
                                    <td>
                                        <div style="background: #fef3c7; border: 1px solid #fcd34d; border-radius: 4px; padding: 12px;">
                                            <p style="margin: 0 0 10px 0;"><strong>🔒 <?php esc_html_e('For better security, store your R2 credentials in wp-config.php:', 'staticq-media'); ?></strong></p>
                                            <code style="display: block; background: #1f2937; color: #f3f4f6; padding: 10px; border-radius: 4px; font-size: 12px; white-space: pre-wrap;">define('SQMEDIA_R2_ACCESS_KEY_ID', 'your_access_key_here');
define('SQMEDIA_R2_SECRET_ACCESS_KEY', 'your_secret_key_here');
// Optional: define('SQMEDIA_R2_ACCOUNT_ID', 'your_account_id');</code>
                                            <p style="margin: 10px 0 0 0; font-size: 12px; color: #92400e;"><?php esc_html_e('Add these lines to wp-config.php, above the line that says "That\'s all, stop editing!"', 'staticq-media'); ?></p>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                
                                <tr>
                                    <th scope="row"><?php esc_html_e('Bucket Name', 'staticq-media'); ?></th>
                                    <td>
                                        <input type="text" name="sqmedia_r2_bucket" value="<?php echo esc_attr($all_settings['r2_bucket'] ?? ''); ?>" class="regular-text" placeholder="my-media-bucket">
                                        <p class="description"><?php esc_html_e('The name of your R2 bucket. Create it first in the Cloudflare dashboard if it doesn\'t exist.', 'staticq-media'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Bucket Path Prefix', 'staticq-media'); ?></th>
                                    <td>
                                        <input type="text" name="sqmedia_r2_prefix" value="<?php echo esc_attr($all_settings['r2_prefix'] ?? 'wp-content/uploads'); ?>" class="regular-text" placeholder="wp-content/uploads">
                                        <p class="description"><?php esc_html_e('Path prefix for files in bucket. Files will be stored as: prefix/2025/01/file.jpg', 'staticq-media'); ?></p>
                                        <p style="margin-top: 8px;">
                                            <label>
                                                <input type="checkbox" name="sqmedia_force_prefix_in_url" value="1" <?php checked(!empty($all_settings['force_prefix_in_url'])); ?>>
                                                <?php esc_html_e('Force this path on public URLs', 'staticq-media'); ?>
                                            </label>
                                        </p>
                                        <p class="description"><?php esc_html_e('Leave unchecked when using a Cloudflare Worker (or other translator) that maps WordPress URLs to the bucket. Check this only if your CDN serves R2 directly with no path translation (e.g., r2.dev or a plain CNAME-to-bucket).', 'staticq-media'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Public Access', 'staticq-media'); ?></th>
                                    <td>
                                        <?php $r2_public_access = $all_settings['r2_public_access'] ?? 'custom_domain'; ?>
                                        <select name="sqmedia_r2_public_access" id="sqmedia_r2_public_access">
                                            <option value="custom_domain" <?php selected($r2_public_access, 'custom_domain'); ?>>
                                                <?php esc_html_e('Custom Domain (recommended)', 'staticq-media'); ?>
                                            </option>
                                            <option value="r2_dev" <?php selected($r2_public_access, 'r2_dev'); ?>>
                                                <?php esc_html_e('R2.dev Public URL', 'staticq-media'); ?>
                                            </option>
                                        </select>
                                        <p class="description"><?php esc_html_e('How files will be served publicly. Custom domain requires connecting a domain to your R2 bucket.', 'staticq-media'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Public URL / Custom Domain', 'staticq-media'); ?></th>
                                    <td>
                                        <input type="text" name="sqmedia_r2_public_url" value="<?php echo esc_attr($all_settings['r2_public_url'] ?? ''); ?>" class="regular-text" placeholder="https://media.example.com" autocomplete="off">
                                        <p class="description">
                                            <?php esc_html_e('The public URL for your R2 bucket. This can be:', 'staticq-media'); ?><br>
                                            • <?php esc_html_e('A custom domain connected to R2 (e.g., https://media.example.com)', 'staticq-media'); ?><br>
                                            • <?php esc_html_e('Your R2.dev URL (e.g., https://pub-abc123.r2.dev)', 'staticq-media'); ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><?php esc_html_e('Test Connection', 'staticq-media'); ?></th>
                                    <td>
                                        <button type="button" id="sqmedia-test-r2" class="button"><?php esc_html_e('Test R2 Connection', 'staticq-media'); ?></button>
                                        <span id="sqmedia-r2-result" class="sqmedia-test-result"></span>
                                    </td>
                                </tr>
                            </table>

                            <!-- R2 Migration Tip -->
                            <?php
                            $migration_account_id = defined('SQMEDIA_R2_ACCOUNT_ID')
                                ? SQMEDIA_R2_ACCOUNT_ID
                                : ($all_settings['r2_account_id'] ?? '');
                            $slurper_url = !empty($migration_account_id)
                                ? 'https://dash.cloudflare.com/' . esc_attr($migration_account_id) . '/r2/slurper'
                                : 'https://dash.cloudflare.com/?to=/:account/r2/slurper';
                            ?>
                            <div id="sqmedia-r2-migration-tip" class="sqmedia-migration-tip" style="margin-top: 20px; padding: 15px; background: #f0f6fc; border-left: 4px solid #2271b1; border-radius: 4px;">
                                <h4 style="margin: 0 0 10px 0; color: #1d2327;">
                                    &#128161; <?php esc_html_e('Migrating from another bucket?', 'staticq-media'); ?>
                                </h4>
                                <p style="margin: 0 0 10px 0; color: #50575e;">
                                    <?php esc_html_e('If you have existing media in Google Cloud Storage or Amazon S3 and want to migrate to R2, Cloudflare offers Super Slurper — a migration tool that copies objects from your source bucket to R2.', 'staticq-media'); ?>
                                </p>
                                <p style="margin: 0 0 10px 0; color: #50575e;">
                                    <?php esc_html_e('You can migrate your entire bucket or specify a prefix to copy only certain paths (e.g., wp-content/uploads/).', 'staticq-media'); ?>
                                </p>
                                <p style="margin: 0;">
                                    <a href="https://developers.cloudflare.com/r2/data-migration/super-slurper/" target="_blank" class="button button-secondary">
                                        &#128279; <?php esc_html_e('Learn about Super Slurper', 'staticq-media'); ?>
                                    </a>
                                    <a href="<?php echo esc_url($slurper_url); ?>" target="_blank" class="button button-secondary" style="margin-left: 8px;">
                                        &#9881; <?php esc_html_e('Open Super Slurper', 'staticq-media'); ?>
                                    </a>
                                </p>
                            </div>
                        </div>

                        <!-- === Cloudflare Worker Delivery === -->
                        <?php $this->render_cloudflare_worker_section(); ?>
                        
                    </div>
                </div>
                
                <!-- =======================================================================
                     SECTION 3: Image Resizing
                     ======================================================================= -->
                <div class="sqmedia-settings-section">
                    <h2>🖼️ <?php esc_html_e('Image Resizing', 'staticq-media'); ?></h2>
                    <p class="description"><?php esc_html_e('Configure how image sizes and formats are generated.', 'staticq-media'); ?></p>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Resizing Tool', 'staticq-media'); ?></th>
                            <td>
                                <?php $resizing_tool = !empty($all_settings['cloudflare_enabled']) ? 'cloudflare' : 'wordpress'; ?>
                                <select name="sqmedia_resizing_tool" id="sqmedia_resizing_tool" class="sqmedia-provider-select">
                                    <option value="wordpress" <?php selected($resizing_tool, 'wordpress'); ?>>
                                        📷 <?php esc_html_e('WordPress — Native PHP resizing (GD/Imagick)', 'staticq-media'); ?>
                                    </option>
                                    <option value="cloudflare" <?php selected($resizing_tool, 'cloudflare'); ?>>
                                        &#127760; <?php esc_html_e('Cloudflare — Image Resizing API (Pro plan required)', 'staticq-media'); ?>
                                    </option>
                                </select>
                                <p class="description">
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('WordPress:', 'staticq-media'); ?></strong> <?php esc_html_e('Uses PHP to generate image sizes on upload. Images are processed and stored immediately.', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <strong><?php esc_html_e('Cloudflare:', 'staticq-media'); ?></strong> <?php esc_html_e('On-demand resizing via Cloudflare CDN. Only originals are stored, sizes generated when requested.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('WebP Generation', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_enable_webp" id="sqmedia_enable_webp" value="1" <?php checked(!empty($all_settings['enable_webp'])); ?>>
                                    <?php esc_html_e('Generate WebP versions of all images', 'staticq-media'); ?>
                                </label>
                                <p class="description"><?php esc_html_e('Creates WebP versions alongside JPEG/PNG files for better compression and faster loading.', 'staticq-media'); ?></p>
                                <?php if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ) && empty( $all_settings['cloudflare_enabled'] ) ) : ?>
                                    <p class="description" style="color: #d63638;">
                                        <?php esc_html_e( 'Your server does not support WebP generation. Install GD with WebP support or Imagick with WebP delegate, or select Cloudflare as your resizing tool.', 'staticq-media' ); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <!-- Cloudflare Image Resizing Settings (hidden when WordPress is selected) -->
                    <div id="sqmedia-cloudflare-resizing-settings" class="sqmedia-conditional-section">
                        <h3>&#127760; <?php esc_html_e('Cloudflare Image Resizing Configuration', 'staticq-media'); ?></h3>
                        <p class="description"><?php esc_html_e('Requires Cloudflare Pro plan or higher with Image Resizing enabled.', 'staticq-media'); ?></p>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e('Cloudflare Domain', 'staticq-media'); ?></th>
                                <td>
                                    <input type="text" name="sqmedia_cloudflare_domain" value="<?php echo esc_attr($all_settings['cloudflare_domain'] ?? ''); ?>" class="regular-text" placeholder="example.com">
                                    <p class="description">
                                        <?php esc_html_e('Your Cloudflare-proxied domain (without https://). Example: example.com', 'staticq-media'); ?><br>
                                        <strong><?php esc_html_e('Note:', 'staticq-media'); ?></strong> <?php esc_html_e('This domain is used for Cloudflare Image Resizing transformations only.', 'staticq-media'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Connection Test', 'staticq-media'); ?></th>
                                <td>
                                    <div id="sqmedia-cloudflare-proxy-status">
                                        <button type="button" class="button button-secondary" id="sqmedia-check-cf-proxy">
                                            <?php esc_html_e('Test Cloudflare Connection', 'staticq-media'); ?>
                                        </button>
                                        <span id="sqmedia-cf-proxy-result" style="margin-left: 10px;"></span>
                                    </div>
                                    <p class="description">
                                        <?php esc_html_e('Tests if the domain is proxied through Cloudflare. Image Resizing only works on proxied domains.', 'staticq-media'); ?><br>
                                        <strong><?php esc_html_e('To enable:', 'staticq-media'); ?></strong> <?php esc_html_e('Cloudflare Dashboard', 'staticq-media'); ?> &rarr; <?php esc_html_e('DNS', 'staticq-media'); ?> &rarr; <?php esc_html_e('Records', 'staticq-media'); ?> &rarr; <?php esc_html_e('Edit your A or CNAME record', 'staticq-media'); ?> &rarr; <?php esc_html_e('Set Proxy status to "Proxied" (orange cloud icon).', 'staticq-media'); ?>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Image Quality', 'staticq-media'); ?></th>
                                <td>
                                    <?php $quality = $all_settings['cloudflare_quality'] ?? 'balanced'; ?>
                                    <select name="sqmedia_cloudflare_quality">
                                        <option value="maximum" <?php selected($quality, 'maximum'); ?>><?php esc_html_e('Maximum (90) — Largest files, best quality', 'staticq-media'); ?></option>
                                        <option value="high" <?php selected($quality, 'high'); ?>><?php esc_html_e('High (85) — Recommended for photography', 'staticq-media'); ?></option>
                                        <option value="balanced" <?php selected($quality, 'balanced'); ?>><?php esc_html_e('Balanced (80) — Good quality/size ratio', 'staticq-media'); ?></option>
                                        <option value="optimized" <?php selected($quality, 'optimized'); ?>><?php esc_html_e('Optimized (75) — Smaller files, slight quality reduction', 'staticq-media'); ?></option>
                                        <option value="aggressive" <?php selected($quality, 'aggressive'); ?>><?php esc_html_e('Aggressive (65) — Smallest files, visible quality loss', 'staticq-media'); ?></option>
                                    </select>
                                    <p class="description"><?php esc_html_e('Controls the JPEG/WebP quality level for Cloudflare-generated images.', 'staticq-media'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Strip Metadata', 'staticq-media'); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="sqmedia_strip_metadata" value="1" <?php checked(!empty($all_settings['strip_metadata'])); ?>>
                                        <?php esc_html_e('Remove EXIF data from images', 'staticq-media'); ?>
                                    </label>
                                    <p class="description"><?php esc_html_e('Removes camera information, GPS coordinates, and other metadata. Reduces file size and improves privacy.', 'staticq-media'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <!-- =======================================================================
                     SECTION 4: Front-end Image Delivery
                     ======================================================================= -->
                <div class="sqmedia-settings-section">
                    <h2>&#128640; <?php esc_html_e('Front-end Image Delivery', 'staticq-media'); ?></h2>
                    <p class="description"><?php esc_html_e('Control how images are delivered to visitors. These settings only affect front-end display.', 'staticq-media'); ?></p>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Enable Picture Elements', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_enable_picture_delivery" value="1" <?php checked(!empty($all_settings['enable_picture_delivery'])); ?>>
                                    <?php esc_html_e('Wrap images in <picture> elements with WebP support', 'staticq-media'); ?>
                                </label>
                                <p class="description">
                                    <strong><?php esc_html_e('What this does:', 'staticq-media'); ?></strong><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <?php esc_html_e('Scans the rendered HTML for <img> tags and identifies WordPress attachments by their CSS class or URL', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <?php esc_html_e('Wraps recognized images in <picture> elements, with WebP <source> when available', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <?php esc_html_e('Builds a responsive srcset using all sizes registered in WordPress (thumbnail, medium, large, etc.)', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <?php esc_html_e('Rewrites image URLs to your CDN for bucket-stored files', 'staticq-media'); ?><br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;• <?php esc_html_e('Only processes images tracked by StaticQ — other images are left untouched', 'staticq-media'); ?><br>
                                    <br>
                                    <strong><?php esc_html_e('Note:', 'staticq-media'); ?></strong> <?php esc_html_e('If you\'re using another image optimization or WebP delivery plugin, you may want to disable this to avoid conflicts.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Ignored Images', 'staticq-media'); ?></th>
                            <td>
                                <input type="text" name="sqmedia_delivery_ignored_classes" value="<?php echo esc_attr($all_settings['delivery_ignored_classes'] ?? ''); ?>" class="large-text" placeholder="custom-logo, 2023/01/logo.jpg">
                                <p class="description">
                                    <?php esc_html_e('Images matching these entries are skipped entirely by the delivery engine — they will not be wrapped in <picture>, and their URLs will not be rewritten. Each entry is matched as an exact CSS class on the <img> tag, or as a partial match against the image file path.', 'staticq-media'); ?><br>
                                    <?php esc_html_e('Example: custom-logo, 2023/01/logo.jpg', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Ignored Sizes', 'staticq-media'); ?></th>
                            <td>
                                <input type="text" name="sqmedia_delivery_ignored_sizes" value="<?php echo esc_attr($all_settings['delivery_ignored_sizes'] ?? ''); ?>" class="large-text" placeholder="thumbnail, medium">
                                <p class="description">
                                    <?php esc_html_e('These WordPress size names will be left out of the srcset attribute when building the <picture> output. The image itself is still processed — only the listed size variants are excluded. Useful for removing small sizes like thumbnail that browsers should never select.', 'staticq-media'); ?><br>
                                    <?php esc_html_e('Example: thumbnail, medium, custom-size', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Lazy Loading', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_enable_lazyload" value="1" <?php checked(!empty($all_settings['enable_lazyload'])); ?>>
                                    <?php esc_html_e('Add loading="lazy" to images processed by the delivery engine', 'staticq-media'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('Defers loading of off-screen images until the visitor scrolls near them, improving initial page load speed.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Eager First Image', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_eager_first_image" value="1" <?php checked(!empty($all_settings['eager_first_image'])); ?>>
                                    <?php esc_html_e('Set the first image on each page to loading="eager" (recommended for LCP)', 'staticq-media'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('When lazy loading is enabled, the first image on the page will load eagerly instead. This improves Largest Contentful Paint (LCP) scores since the hero image loads immediately.', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>
                
                <!-- =======================================================================
                     SECTION 5: File Dimension Management
                     ======================================================================= -->
                <div class="sqmedia-settings-section">
                    <h2>📐 <?php esc_html_e('File Dimensions', 'staticq-media'); ?></h2>
                    <p class="description"><?php esc_html_e('Control how large images are handled and manage registered image sizes.', 'staticq-media'); ?></p>
                    
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Large Image Scaling', 'staticq-media'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sqmedia_enable_big_image_scaling" value="1" <?php checked(!empty($all_settings['enable_big_image_scaling'])); ?>>
                                    <?php esc_html_e('Automatically scale down very large images', 'staticq-media'); ?>
                                </label>
                                <p class="description"><?php esc_html_e('When enabled, images exceeding the maximum dimensions will be scaled down. A "-scaled" suffix is added to the filename.', 'staticq-media'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Maximum Dimensions', 'staticq-media'); ?></th>
                            <td>
                                <input type="number" name="sqmedia_big_image_size_threshold_width" value="<?php echo esc_attr($all_settings['big_image_size_threshold_width'] ?? 2560); ?>" class="small-text" min="1" max="10000"> × 
                                <input type="number" name="sqmedia_big_image_size_threshold_height" value="<?php echo esc_attr($all_settings['big_image_size_threshold_height'] ?? 2560); ?>" class="small-text" min="1" max="10000"> px
                                <p class="description"><?php esc_html_e('Width × Height. Default: 2560 × 2560', 'staticq-media'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Original File Handling', 'staticq-media'); ?></th>
                            <td>
                                <?php $original_handling = $all_settings['original_file_handling'] ?? 'preserve'; ?>
                                <select name="sqmedia_original_file_handling">
                                    <option value="preserve" <?php selected($original_handling, 'preserve'); ?>><?php esc_html_e('Keep in main directory', 'staticq-media'); ?></option>
                                    <option value="move_to_originals" <?php selected($original_handling, 'move_to_originals'); ?>><?php esc_html_e('Move to /originals/ subdirectory', 'staticq-media'); ?></option>
                                    <option value="discard" <?php selected($original_handling, 'discard'); ?>><?php esc_html_e('Discard original (not recommended)', 'staticq-media'); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e('What to do with the unscaled original when an image is scaled down.', 'staticq-media'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Registered Image Sizes', 'staticq-media'); ?></th>
                            <td>
                                <?php $this->render_registered_sizes($all_settings); ?>
                            </td>
                        </tr>
                        <?php
                        $ignored_sizes = $all_settings['ignored_sizes'] ?? '';
                        ?>
                        <tr>
                            <th scope="row"><?php esc_html_e('Scanner Ignored Sizes', 'staticq-media'); ?></th>
                            <td>
                                <input type="text" name="sqmedia_ignored_sizes" id="sqmedia_ignored_sizes" value="<?php echo esc_attr($ignored_sizes); ?>" class="regular-text" placeholder="custom-size, legacy-thumb">
                                <p class="description">
                                    <?php esc_html_e('Comma-separated list of image size names to exclude from health checks.', 'staticq-media'); ?><br>
                                    <?php esc_html_e('Some themes and plugins register their own image sizes outside of the standard WordPress sizes (thumbnail, medium, large, etc.). If you see sizes flagged as missing or deprecated that you don\'t need StaticQ to manage, add them here to silence those warnings.', 'staticq-media'); ?><br>
                                    <?php esc_html_e('Example: custom-header, portfolio-thumb', 'staticq-media'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>
                
                <!-- =======================================================================
                     SECTION 6: Processing Settings
                     ======================================================================= -->
                
                <p class="submit">
                    <input type="submit" name="sqmedia_save_settings" class="button button-primary" value="<?php esc_attr_e('Save Settings', 'staticq-media'); ?>">
                </p>
            </form>
            
            <?php // CSS extracted to admin/css/sqmedia-settings.css ?>

            <?php ob_start(); ?>
            jQuery(document).ready(function($) {
                
                // =======================================================================
                // Storage Mode Toggle
                // =======================================================================
                var $storageMode = $('#sqmedia_storage_mode');
                var $cloudStorageSettings = $('#sqmedia-cloud-storage-settings');
                var $storageProvider = $('#sqmedia_storage_provider');
                
                function updateStorageModeUI() {
                    var mode = $storageMode.val();
                    var isCloudEnabled = (mode === 'cloud_and_local' || mode === 'cloud_only');
                    
                    if (isCloudEnabled) {
                        $cloudStorageSettings.addClass('active');
                        updateStorageProviderUI(); // Show the correct provider
                    } else {
                        $cloudStorageSettings.removeClass('active');
                    }
                }
                
                function updateStorageProviderUI() {
                    var provider = $storageProvider.val();
                    
                    // Hide all provider settings
                    $('.sqmedia-provider-settings').removeClass('active');
                    
                    // Show selected provider settings
                    $('#sqmedia-' + provider + '-settings').addClass('active');
                }
                
                $storageMode.on('change', updateStorageModeUI);
                $storageProvider.on('change', updateStorageProviderUI);
                
                // Initial state
                updateStorageModeUI();
                
                // =======================================================================
                // Resizing Tool Toggle
                // =======================================================================
                var $resizingTool = $('#sqmedia_resizing_tool');
                var $cloudflareResizingSettings = $('#sqmedia-cloudflare-resizing-settings');
                
                function updateResizingToolUI() {
                    var tool = $resizingTool.val();
                    
                    if (tool === 'cloudflare') {
                        $cloudflareResizingSettings.addClass('active');
                    } else {
                        $cloudflareResizingSettings.removeClass('active');
                    }
                }
                
                $resizingTool.on('change', updateResizingToolUI);
                
                // Initial state
                updateResizingToolUI();
                
                // =======================================================================
                // Test Connection Buttons
                // =======================================================================
                
                // R2 Test Connection
                $('#sqmedia-test-r2').on('click', function() {
                    var $btn = $(this);
                    var $result = $('#sqmedia-r2-result');
                    
                    $btn.prop('disabled', true).text('<?php echo esc_js(__('Testing...', 'staticq-media')); ?>');
                    $result.removeClass('success error').text('');
                    
                    $.post(ajaxurl, {
                        action: 'sqmedia_test_r2_connection',
                        nonce: sqmediaAdmin.nonce
                    }, function(response) {
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Test R2 Connection', 'staticq-media')); ?>');
                        
                        if (response.success) {
                            $result.addClass('success').text('✓ ' + response.data.message);
                        } else {
                            $result.addClass('error').text('✗ ' + response.data);
                        }
                    }).fail(function() {
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Test R2 Connection', 'staticq-media')); ?>');
                        $result.addClass('error').text('✗ <?php echo esc_js(__('Connection error', 'staticq-media')); ?>');
                    });
                });
                

                // Cloudflare Proxy Check
                $('#sqmedia-check-cf-proxy').on('click', function() {
                    var $btn = $(this);
                    var $result = $('#sqmedia-cf-proxy-result');
                    var domain = $('input[name="sqmedia_cloudflare_domain"]').val();
                    
                    if (!domain) {
                        $result.html('<span style="color:#d63638;">&#10007; Enter a domain above first</span>');
                        return;
                    }
                    
                    $btn.prop('disabled', true).text('Checking...');
                    $result.html('');
                    
                    $.post(ajaxurl, {
                        action: 'sqmedia_check_cloudflare_proxy',
                        nonce: sqmediaAdmin.nonce,
                        domain: domain
                    }, function(response) {
                        $btn.prop('disabled', false).text('Test Cloudflare Connection');
                        
                        if (response.success && response.data) {
                            if (response.data.proxied) {
                                $result.html('<span style="color:#00a32a;">&#10003; ' + response.data.message + '</span>');
                            } else {
                                $result.html('<span style="color:#dba617;">&#9888; ' + response.data.message + '</span>');
                            }
                        } else {
                            $result.html('<span style="color:#d63638;">&#10007; ' + (response.data ? response.data.error : 'Check failed') + '</span>');
                        }
                    }).fail(function() {
                        $btn.prop('disabled', false).text('Test Cloudflare Connection');
                        $result.html('<span style="color:#d63638;">&#10007; Connection error</span>');
                    });
                });
                
                // Auto-check proxy status when Cloudflare is selected
                $resizingTool.on('change', function() {
                    if ($(this).val() === 'cloudflare') {
                        setTimeout(function() {
                            $('#sqmedia-check-cf-proxy').trigger('click');
                        }, 500);
                    }
                });
                
            });
            <?php wp_add_inline_script('sqmedia-admin', ob_get_clean()); ?>
        </div>
        <?php
    }
    
    /**
     * Render upload interception status
     */
    private function render_upload_status(array $settings): void {
        $is_enabled = !empty($settings['enabled']);
        
        if ($is_enabled) {
            echo '<div class="notice notice-success inline" style="margin: 0 0 15px; padding: 12px;"><p style="margin: 0;">';
            echo '<strong>✓ ' . esc_html__('Upload Interception:', 'staticq-media') . '</strong> <span style="color: #00a32a; font-weight: 600;">' . esc_html__('Active', 'staticq-media') . '</span> — ';
            echo esc_html__('New uploads are being processed by StaticQ.', 'staticq-media');
            echo '</p></div>';
        } else {
            echo '<div class="notice notice-warning inline" style="margin: 0 0 15px; padding: 12px;"><p style="margin: 0;">';
            echo '<strong>&#9888; ' . esc_html__('Upload Interception:', 'staticq-media') . '</strong> <span style="color: #dba617; font-weight: 600;">' . esc_html__('Disabled', 'staticq-media') . '</span> — ';
            echo esc_html__('WordPress is handling uploads normally.', 'staticq-media');
            echo '</p></div>';
        }
    }
    
    /**
     * Render Cloudflare Worker deployment section
     */
    private function render_cloudflare_worker_section(): void {
        $deployment = SQMedia_Cloudflare_Deployer::get_deployment_status();
        $is_deployed = $deployment !== null;
        // Check if site domain is proxied through Cloudflare (automatic check)
        $site_proxy_check = SQMedia_Cloudflare_Handler::check_site_cloudflare_proxy();
        $site_domain = wp_parse_url(home_url(), PHP_URL_HOST);
        $is_site_proxied = !empty($site_proxy_check['proxied']);

        // Check for storage type mismatch (deployed worker vs current settings)
        $current_storage_type = SQMedia_Settings::get_storage_provider(); // always 'r2' in free plugin
        $deployed_storage_type = $deployment['storage_provider'] ?? null;
        $storage_mismatch = $is_deployed && $deployed_storage_type && ($current_storage_type !== $deployed_storage_type);

        // Human-readable storage names
        $storage_names = [
            'r2' => __('Cloudflare R2', 'staticq-media'),
        ];
        ?>
        <div class="sqmedia-cf-worker-section">
            <h3>&#128640; <?php esc_html_e('Media Delivery via Cloudflare Worker', 'staticq-media'); ?></h3>
            <p class="description">
                <?php esc_html_e('Deploy a Cloudflare Worker to serve media files from your bucket with automatic fallback to your server.', 'staticq-media'); ?>
            </p>
            
            <?php if ($is_site_proxied): ?>
            <div class="sqmedia-cf-proxy-notice" style="background: #edfaef; border-left: 4px solid #00a32a; padding: 10px 15px; margin: 15px 0;">
                <span style="color: #00a32a;">&#10003; <strong><?php echo esc_html($site_domain); ?></strong> <?php esc_html_e('is proxied through Cloudflare', 'staticq-media'); ?></span>
            </div>
            <?php else: ?>
            <div class="sqmedia-cf-proxy-notice" style="background: #fff8e5; border-left: 4px solid #dba617; padding: 12px 15px; margin: 15px 0;">
                <strong style="color: #826200;">&#9888; <?php esc_html_e('Cloudflare Proxy Not Detected', 'staticq-media'); ?></strong>
                <p style="margin: 8px 0 0 0; color: #826200;">
                    <?php
                    printf(
                        // translators: %s: site domain
                        esc_html__('Your site (%s) does not appear to be proxied through Cloudflare. For the Worker to intercept requests, your domain must be proxied.', 'staticq-media'),
                        '<code>' . esc_html($site_domain) . '</code>'
                    ); ?>
                </p>
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #6d5a00;">
                    <strong><?php esc_html_e('To enable:', 'staticq-media'); ?></strong>
                    <?php esc_html_e('Cloudflare Dashboard', 'staticq-media'); ?> &rarr; <?php esc_html_e('DNS', 'staticq-media'); ?> &rarr; <?php esc_html_e('Records', 'staticq-media'); ?> &rarr; <?php esc_html_e('Set Proxy status to "Proxied" (orange cloud).', 'staticq-media'); ?>
                </p>
            </div>
            <?php endif; ?>
            
            <?php if ($storage_mismatch): ?>
            <div class="sqmedia-cf-storage-mismatch-notice" style="background: #fef2f2; border-left: 4px solid #d63638; padding: 12px 15px; margin: 15px 0;">
                <strong style="color: #991b1b;">&#9888; <?php esc_html_e('Storage Type Mismatch', 'staticq-media'); ?></strong>
                <p style="margin: 8px 0 0 0; color: #991b1b;">
                    <?php
                    printf(
                        // translators: %1$s: original storage type, %2$s: new storage type
                        esc_html__('The deployed Worker was configured for %1$s, but you have now selected %2$s as your storage type.', 'staticq-media'),
                        '<strong>' . esc_html($storage_names[$deployed_storage_type] ?? $deployed_storage_type) . '</strong>',
                        '<strong>' . esc_html($storage_names[$current_storage_type] ?? $current_storage_type) . '</strong>'
                    ); ?>
                </p>
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #7f1d1d;">
                    <?php esc_html_e('The Worker will not function correctly until you remove it and deploy a new one with the correct storage configuration.', 'staticq-media'); ?>
                </p>
            </div>
            <?php endif; ?>
            
            <?php if ($is_deployed): ?>
                <!-- Deployed State -->
                <div class="sqmedia-cf-status-box sqmedia-cf-status-deployed">
                    <div class="sqmedia-cf-status-header">
                        <span class="sqmedia-cf-status-indicator active"></span>
                        <strong><?php esc_html_e('Status:', 'staticq-media'); ?></strong>
                        <span class="sqmedia-cf-status-text"><?php esc_html_e('Configured', 'staticq-media'); ?></span>
                    </div>
                    <p class="sqmedia-cf-status-note">
                        <?php esc_html_e('A worker deployment is configured. Use "Test Connection" to verify it responds correctly.', 'staticq-media'); ?>
                    </p>
                    <div class="sqmedia-cf-status-details">
                        <div class="sqmedia-cf-detail-row">
                            <span class="sqmedia-cf-detail-label"><?php esc_html_e('Worker:', 'staticq-media'); ?></span>
                            <code><?php echo esc_html($deployment['worker_name']); ?></code>
                        </div>
                        <div class="sqmedia-cf-detail-row">
                            <span class="sqmedia-cf-detail-label"><?php esc_html_e('Storage:', 'staticq-media'); ?></span>
                            <span><?php echo esc_html($storage_names[$deployment['storage_provider'] ?? 'r2'] ?? $deployment['storage_provider']); ?></span>
                        </div>
                        <div class="sqmedia-cf-detail-row">
                            <span class="sqmedia-cf-detail-label"><?php esc_html_e('Bucket:', 'staticq-media'); ?></span>
                            <code><?php echo esc_html($deployment['bucket_name']); ?></code>
                        </div>
                        <div class="sqmedia-cf-detail-row">
                            <span class="sqmedia-cf-detail-label"><?php esc_html_e('Route:', 'staticq-media'); ?></span>
                            <code><?php echo esc_html($deployment['route_pattern']); ?></code>
                        </div>
                        <?php if (!empty($deployment['last_test'])): ?>
                        <div class="sqmedia-cf-detail-row">
                            <span class="sqmedia-cf-detail-label"><?php esc_html_e('Last test:', 'staticq-media'); ?></span>
                            <span><?php echo esc_html(human_time_diff(strtotime($deployment['last_test']), strtotime(current_time('mysql')))) . ' ' . esc_html__('ago', 'staticq-media'); ?></span>
                            <?php if (!empty($deployment['last_test_result']['success'])): ?>
                                <span class="sqmedia-cf-test-success">✓</span>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="sqmedia-cf-status-actions">
                        <button type="button" id="sqmedia-cf-test-btn" class="button button-primary">
                            <?php esc_html_e('Test Connection', 'staticq-media'); ?>
                        </button>
                        <button type="button" id="sqmedia-cf-delete-btn" class="button sqmedia-cf-delete-btn">
                            &#128465; <?php esc_html_e('Remove Worker', 'staticq-media'); ?>
                        </button>
                        <span id="sqmedia-cf-test-status"></span>
                    </div>
                    <div class="sqmedia-cf-secondary-actions">
                        <a href="#" id="sqmedia-cf-clear-local"><?php esc_html_e('Clear local settings only', 'staticq-media'); ?></a>
                        <span class="sqmedia-cf-help-tip" title="<?php esc_attr_e('Use this if your API token has expired or been revoked. This clears the plugin settings without contacting Cloudflare. You may need to manually delete the worker and route from your Cloudflare dashboard.', 'staticq-media'); ?>">?</span>
                    </div>
                </div>
                
                <!-- Delete Confirmation Modal -->
                <div id="sqmedia-cf-delete-modal" class="sqmedia-cf-delete-modal" style="display:none;">
                    <div class="sqmedia-cf-delete-modal-content">
                        <h3>&#9888; <?php esc_html_e('Remove Cloudflare Worker?', 'staticq-media'); ?></h3>
                        <p><?php esc_html_e('This will remove the following from your Cloudflare account:', 'staticq-media'); ?></p>
                        <ul>
                            <li><?php printf(
                                // translators: %s: worker script name
                                esc_html__('Worker script: %s', 'staticq-media'),
                                '<code>' . esc_html($deployment['worker_name']) . '</code>'
                            ); ?></li>
                            <li><?php printf(
                                // translators: %s: route pattern
                                esc_html__('Route: %s', 'staticq-media'),
                                '<code>' . esc_html($deployment['route_pattern']) . '</code>'
                            ); ?></li>
                        </ul>
                        <div class="sqmedia-cf-delete-warning">
                            <strong><?php esc_html_e('Warning:', 'staticq-media'); ?></strong>
                            <?php esc_html_e('If you have manually edited the worker code in the Cloudflare dashboard, those changes will be lost.', 'staticq-media'); ?>
                        </div>
                        <p class="sqmedia-cf-delete-bucket-note">
                            <em><?php esc_html_e('Note: The R2 bucket and its contents will NOT be deleted.', 'staticq-media'); ?></em>
                        </p>
                        <div class="sqmedia-cf-delete-modal-actions">
                            <button type="button" id="sqmedia-cf-delete-cancel" class="button"><?php esc_html_e('Cancel', 'staticq-media'); ?></button>
                            <button type="button" id="sqmedia-cf-delete-confirm" class="button button-link-delete"><?php esc_html_e('Yes, Remove Worker', 'staticq-media'); ?></button>
                        </div>
                    </div>
                </div>

                <!-- Clear Local Settings Confirmation Modal -->
                <div id="sqmedia-cf-clear-local-modal" class="sqmedia-cf-delete-modal" style="display:none;">
                    <div class="sqmedia-cf-delete-modal-content">
                        <h3>&#9888; <?php esc_html_e('Clear Local Settings?', 'staticq-media'); ?></h3>
                        <p><?php esc_html_e('This will only clear the plugin\'s local configuration. It will NOT contact Cloudflare.', 'staticq-media'); ?></p>
                        <div class="sqmedia-cf-delete-warning">
                            <strong><?php esc_html_e('Important:', 'staticq-media'); ?></strong>
                            <?php esc_html_e('The worker and route may still exist in your Cloudflare account. You should manually delete them from the Cloudflare dashboard:', 'staticq-media'); ?>
                            <ul style="margin: 10px 0 0 20px;">
                                <li><?php printf(
                                    // translators: %s: worker name
                                    esc_html__('Worker: %s', 'staticq-media'),
                                    '<code>' . esc_html($deployment['worker_name']) . '</code>'
                                ); ?></li>
                                <li><?php printf(
                                    // translators: %s: route pattern
                                    esc_html__('Route: %s', 'staticq-media'),
                                    '<code>' . esc_html($deployment['route_pattern']) . '</code>'
                                ); ?></li>
                            </ul>
                        </div>
                        <div class="sqmedia-cf-delete-modal-actions">
                            <button type="button" id="sqmedia-cf-clear-local-cancel" class="button"><?php esc_html_e('Cancel', 'staticq-media'); ?></button>
                            <button type="button" id="sqmedia-cf-clear-local-confirm" class="button button-secondary"><?php esc_html_e('Clear Local Settings', 'staticq-media'); ?></button>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <!-- Not Deployed State -->
                <div class="sqmedia-cf-status-box sqmedia-cf-status-not-deployed">
                    <div class="sqmedia-cf-status-header">
                        <span class="sqmedia-cf-status-indicator inactive"></span>
                        <strong><?php esc_html_e('Status:', 'staticq-media'); ?></strong>
                        <span class="sqmedia-cf-status-text"><?php esc_html_e('Not configured', 'staticq-media'); ?></span>
                    </div>
                    <p class="sqmedia-cf-status-description">
                        <?php esc_html_e('Set up automatic media delivery from your cloud bucket with CDN caching and fallback support.', 'staticq-media'); ?>
                    </p>
                    <button type="button" id="sqmedia-cf-launch-wizard" class="button button-primary">
                        &#128640; <?php esc_html_e('Launch Setup Wizard', 'staticq-media'); ?>
                    </button>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Cloudflare Worker Setup Modal -->
        <?php $this->render_cloudflare_wizard_modal(); ?>
        <?php
    }
    
    /**
     * Render the Cloudflare Worker setup wizard modal
     */
    private function render_cloudflare_wizard_modal(): void {
        ?>
        <div id="sqmedia-cf-modal" class="sqmedia-cf-modal-overlay">
            <div class="sqmedia-cf-modal">
                <div class="sqmedia-cf-modal-header">
                    <h2><?php esc_html_e('Cloudflare Worker Setup', 'staticq-media'); ?></h2>
                    <button type="button" class="sqmedia-cf-modal-close">&times;</button>
                </div>
                
                <!-- Progress Indicator -->
                <div class="sqmedia-cf-progress">
                    <div class="sqmedia-cf-progress-step active" data-step="1">
                        <span class="sqmedia-cf-progress-number">1</span>
                        <span class="sqmedia-cf-progress-label"><?php esc_html_e('Token', 'staticq-media'); ?></span>
                    </div>
                    <div class="sqmedia-cf-progress-step" data-step="2">
                        <span class="sqmedia-cf-progress-number">2</span>
                        <span class="sqmedia-cf-progress-label"><?php esc_html_e('Zone & Bucket', 'staticq-media'); ?></span>
                    </div>
                    <div class="sqmedia-cf-progress-step" data-step="3">
                        <span class="sqmedia-cf-progress-number">3</span>
                        <span class="sqmedia-cf-progress-label"><?php esc_html_e('Worker', 'staticq-media'); ?></span>
                    </div>
                    <div class="sqmedia-cf-progress-step" data-step="4">
                        <span class="sqmedia-cf-progress-number">4</span>
                        <span class="sqmedia-cf-progress-label"><?php esc_html_e('Deploy', 'staticq-media'); ?></span>
                    </div>
                </div>
                
                <div class="sqmedia-cf-modal-body">
                    <!-- Step 1: API Token -->
                    <div id="sqmedia-cf-step-1" class="sqmedia-cf-step active">
                        <h3>🔶 <?php esc_html_e('API Token', 'staticq-media'); ?></h3>
                        <p class="description">
                            <?php esc_html_e('Create a Custom Token in your Cloudflare dashboard.', 'staticq-media'); ?>
                        </p>
                        
                        <div class="sqmedia-cf-token-instructions">
                            <p><strong><?php esc_html_e('How to create the token:', 'staticq-media'); ?></strong></p>
                            <ol class="sqmedia-cf-numbered-list">
                                <li><?php esc_html_e('Go to Cloudflare Dashboard', 'staticq-media'); ?></li>
                                <li><?php esc_html_e('Click your profile icon (top right) to go to your profile home', 'staticq-media'); ?></li>
                                <li><?php esc_html_e('In the left menu: "Manage Account" → "Account API Tokens"', 'staticq-media'); ?></li>
                                <li><?php esc_html_e('Click "Create Token" → "Create Custom Token"', 'staticq-media'); ?></li>
                            </ol>
                            
                            <p><strong><?php esc_html_e('Required permissions:', 'staticq-media'); ?></strong></p>
                            <ul class="sqmedia-cf-permissions-list">
                                <li>Account → Workers Scripts → Edit</li>
                                <li class="sqmedia-cf-r2-only">Account → Workers R2 Storage → Edit</li>
                                <li>Zone → Workers Routes → Edit</li>
                            </ul>
                            
                            <p><strong><?php esc_html_e('Configure resources:', 'staticq-media'); ?></strong></p>
                            <ul class="sqmedia-cf-permissions-list">
                                <li><?php esc_html_e('Account Resources: Select your account', 'staticq-media'); ?></li>
                                <li><strong><?php esc_html_e('Zone Resources: Select "Specific zone" → Choose your domain', 'staticq-media'); ?></strong><br>
                                    <small style="color: #d63638;"><?php esc_html_e('&#9888; Required! "All zones" will cause an error.', 'staticq-media'); ?></small>
                                </li>
                            </ul>
                        </div>
                        
                        <p>
                            <a href="https://dash.cloudflare.com/" target="_blank" class="button button-secondary">
                                <?php esc_html_e('Open Cloudflare Dashboard', 'staticq-media'); ?> →
                            </a>
                        </p>
                        
                        <div class="sqmedia-cf-form-row sqmedia-cf-token-storage">
                            <label><?php esc_html_e('Where should the token be stored?', 'staticq-media'); ?></label>
                            <label class="sqmedia-cf-radio">
                                <input type="radio" name="sqmedia_cf_token_storage" value="database" checked>
                                <strong><?php esc_html_e('Store encrypted in database', 'staticq-media'); ?></strong>
                                <span class="sqmedia-cf-radio-description"><?php esc_html_e('Easier setup. Token is encrypted using your WordPress security keys.', 'staticq-media'); ?></span>
                            </label>
                            <label class="sqmedia-cf-radio">
                                <input type="radio" name="sqmedia_cf_token_storage" value="config">
                                <strong><?php esc_html_e('Store in wp-config.php', 'staticq-media'); ?></strong>
                                <span class="sqmedia-cf-radio-description"><?php esc_html_e('Most secure. You will need to manually edit your wp-config.php file.', 'staticq-media'); ?></span>
                            </label>
                        </div>
                        
                        <!-- Database storage: show token input -->
                        <div id="sqmedia-cf-database-token-section">
                            <div class="sqmedia-cf-form-row">
                                <label for="sqmedia-cf-token"><?php esc_html_e('API Token:', 'staticq-media'); ?></label>
                                <input type="password" id="sqmedia-cf-token" class="regular-text" placeholder="<?php esc_attr_e('Paste your token here', 'staticq-media'); ?>">
                                <button type="button" id="sqmedia-cf-verify-token" class="button"><?php esc_html_e('Verify and Save', 'staticq-media'); ?></button>
                            </div>
                            <div id="sqmedia-cf-token-status" class="sqmedia-cf-status-message"></div>
                        </div>
                        
                        <!-- wp-config.php storage: show instructions and verify button -->
                        <div id="sqmedia-cf-config-token-section" style="display:none;">
                            <div class="sqmedia-cf-config-instructions">
                                <p><strong><?php esc_html_e('Add the token to wp-config.php:', 'staticq-media'); ?></strong></p>
                                <ol class="sqmedia-cf-numbered-list">
                                    <li><?php esc_html_e('Copy your token from Cloudflare', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Open your wp-config.php file (in your WordPress root folder)', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Find the line: /* That\'s all, stop editing! */', 'staticq-media'); ?></li>
                                    <li><?php esc_html_e('Add this line ABOVE it (replace YOUR_TOKEN with your actual token):', 'staticq-media'); ?></li>
                                </ol>
                                <div class="sqmedia-cf-code-box">
                                    <code id="sqmedia-cf-config-code">define('SQMEDIA_CF_TOKEN', 'YOUR_TOKEN_HERE');</code>
                                    <button type="button" id="sqmedia-cf-copy-code" class="button button-small">&#128203; <?php esc_html_e('Copy', 'staticq-media'); ?></button>
                                </div>
                                <p class="sqmedia-cf-config-note">
                                    <?php esc_html_e('After saving wp-config.php, click the button below to verify the token is correctly set:', 'staticq-media'); ?>
                                </p>
                                <p>
                                    <button type="button" id="sqmedia-cf-verify-config-token" class="button button-primary">
                                        <?php esc_html_e('Verify Token from wp-config.php', 'staticq-media'); ?>
                                    </button>
                                </p>
                                <div id="sqmedia-cf-config-token-status" class="sqmedia-cf-status-message"></div>
                            </div>
                        </div>
                        
                        <div class="sqmedia-cf-step-error"></div>
                    </div>
                    
                    <!-- Step 2: Zone & Bucket -->
                    <div id="sqmedia-cf-step-2" class="sqmedia-cf-step">
                        <h3>&#127760; <?php esc_html_e('Zone & Storage', 'staticq-media'); ?></h3>
                        
                        <div class="sqmedia-cf-form-row">
                            <label for="sqmedia-cf-zone"><?php esc_html_e('Zone (Domain):', 'staticq-media'); ?></label>
                            <select id="sqmedia-cf-zone" class="regular-text">
                                <option value=""><?php esc_html_e('Loading...', 'staticq-media'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Select the Cloudflare zone where the worker route will be created.', 'staticq-media'); ?></p>
                        </div>
                        
                        <!-- R2 Bucket Selection (only shown for R2 provider) -->
                        <div id="sqmedia-cf-r2-bucket-section" class="sqmedia-cf-provider-section">
                            <div class="sqmedia-cf-form-row">
                                <label><?php esc_html_e('R2 Bucket:', 'staticq-media'); ?></label>
                                <label class="sqmedia-cf-radio">
                                    <input type="radio" name="sqmedia_cf_bucket_option" value="new" checked>
                                    <?php esc_html_e('Create new bucket', 'staticq-media'); ?>
                                </label>
                                <label class="sqmedia-cf-radio">
                                    <input type="radio" name="sqmedia_cf_bucket_option" value="existing">
                                    <?php esc_html_e('Use existing bucket', 'staticq-media'); ?>
                                </label>
                            </div>
                            
                            <div id="sqmedia-cf-new-bucket-row" class="sqmedia-cf-form-row">
                                <label for="sqmedia-cf-bucket-name"><?php esc_html_e('Bucket Name:', 'staticq-media'); ?></label>
                                <input type="text" id="sqmedia-cf-bucket-name" class="regular-text" placeholder="my-media-bucket">
                                <span id="sqmedia-cf-bucket-status"></span>
                            </div>
                            
                            <div id="sqmedia-cf-existing-bucket-row" class="sqmedia-cf-form-row" style="display:none;">
                                <label for="sqmedia-cf-existing-bucket"><?php esc_html_e('Select Bucket:', 'staticq-media'); ?></label>
                                <select id="sqmedia-cf-existing-bucket" class="regular-text">
                                    <option value=""><?php esc_html_e('Loading...', 'staticq-media'); ?></option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="sqmedia-cf-step-error"></div>
                    </div>
                    
                    <!-- Step 3: Worker Configuration -->
                    <div id="sqmedia-cf-step-3" class="sqmedia-cf-step">
                        <h3>&#9881; <?php esc_html_e('Worker Configuration', 'staticq-media'); ?></h3>
                        
                        <div class="sqmedia-cf-form-row">
                            <label for="sqmedia-cf-worker-name"><?php esc_html_e('Worker Name:', 'staticq-media'); ?></label>
                            <input type="text" id="sqmedia-cf-worker-name" class="regular-text" value="staticq-media-worker">
                            <span id="sqmedia-cf-worker-status"></span>
                        </div>
                        
                        <div class="sqmedia-cf-form-row">
                            <label for="sqmedia-cf-route-pattern"><?php esc_html_e('Route Pattern:', 'staticq-media'); ?></label>
                            <input type="text" id="sqmedia-cf-route-pattern" class="regular-text">
                            <p class="description"><?php esc_html_e('Auto-generated based on zone. You can edit if your uploads path differs or for testing.', 'staticq-media'); ?></p>
                        </div>
                        
                        <div class="sqmedia-cf-form-row">
                            <label class="sqmedia-cf-checkbox">
                                <input type="checkbox" id="sqmedia-cf-enable-fallback" checked>
                                <?php esc_html_e('Enable fallback to origin server (recommended)', 'staticq-media'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('If a file is missing from the bucket, the worker will try to fetch it from your WordPress server. Keep this enabled if some files may still be on your local disk. When disabled, missing files will return a 404 error.', 'staticq-media'); ?></p>
                        </div>
                        
                        <div class="sqmedia-cf-step-error"></div>
                    </div>
                    
                    <!-- Step 4: Deploy -->
                    <div id="sqmedia-cf-step-4" class="sqmedia-cf-step">
                        <h3>&#128640; <?php esc_html_e('Deploy', 'staticq-media'); ?></h3>
                        
                        <p class="sqmedia-cf-deploy-summary"><?php esc_html_e('Ready to deploy. The following will be created in your Cloudflare account:', 'staticq-media'); ?></p>
                        
                        <div id="sqmedia-cf-deploy-progress">
                            <div class="sqmedia-cf-deploy-step pending sqmedia-cf-r2-only" data-step="bucket">
                                <span class="sqmedia-cf-step-status">←</span>
                                <span class="sqmedia-cf-step-label"><?php esc_html_e('Setting up R2 bucket', 'staticq-media'); ?></span>
                                <span class="sqmedia-cf-step-message"></span>
                            </div>
                            <div class="sqmedia-cf-deploy-step pending" data-step="worker">
                                <span class="sqmedia-cf-step-status">←</span>
                                <span class="sqmedia-cf-step-label"><?php esc_html_e('Uploading worker script', 'staticq-media'); ?></span>
                                <span class="sqmedia-cf-step-message"></span>
                            </div>
                            <div class="sqmedia-cf-deploy-step pending" data-step="route">
                                <span class="sqmedia-cf-step-status">←</span>
                                <span class="sqmedia-cf-step-label"><?php esc_html_e('Creating route', 'staticq-media'); ?></span>
                                <span class="sqmedia-cf-step-message"></span>
                            </div>
                            <div class="sqmedia-cf-deploy-step pending" data-step="save">
                                <span class="sqmedia-cf-step-status">←</span>
                                <span class="sqmedia-cf-step-label"><?php esc_html_e('Saving configuration', 'staticq-media'); ?></span>
                                <span class="sqmedia-cf-step-message"></span>
                            </div>
                            <div class="sqmedia-cf-deploy-step pending" data-step="test">
                                <span class="sqmedia-cf-step-status">←</span>
                                <span class="sqmedia-cf-step-label"><?php esc_html_e('Testing deployment', 'staticq-media'); ?></span>
                                <span class="sqmedia-cf-step-message"></span>
                            </div>
                        </div>
                        
                        <div id="sqmedia-cf-deploy-success" class="sqmedia-cf-result-box success" style="display:none;">
                            <strong>✓ <?php esc_html_e('Deployment successful!', 'staticq-media'); ?></strong>
                            <p><?php esc_html_e('Your Cloudflare Worker is now configured. Use "Test Connection" on the settings page to verify it works.', 'staticq-media'); ?></p>
                        </div>
                        
                        <div id="sqmedia-cf-deploy-error" class="sqmedia-cf-result-box error" style="display:none;">
                            <strong>✗ <?php esc_html_e('Deployment failed', 'staticq-media'); ?></strong>
                            <p id="sqmedia-cf-deploy-error-message"></p>
                        </div>
                    </div>
                </div>
                
                <div class="sqmedia-cf-modal-footer">
                    <button type="button" id="sqmedia-cf-back-btn" class="button" style="display:none;">
                        ← <?php esc_html_e('Back', 'staticq-media'); ?>
                    </button>
                    <button type="button" id="sqmedia-cf-next-btn" class="button button-primary">
                        <?php esc_html_e('Next', 'staticq-media'); ?> →
                    </button>
                    <button type="button" id="sqmedia-cf-deploy-btn" class="button button-primary" style="display:none;">
                        &#128640; <?php esc_html_e('Deploy Worker', 'staticq-media'); ?>
                    </button>
                </div>
            </div>
        </div>
        
        <?php // CloudFlare wizard CSS is in admin/css/sqmedia-settings.css ?>
        <?php ob_start(); ?>
            var sqmedia_cf_nonce = '<?php echo esc_attr(wp_create_nonce('sqmedia_cf_nonce')); ?>';
            var sqmedia_cf_i18n = {
                verifying: '<?php echo esc_js(__('Verifying...', 'staticq-media')); ?>',
                verify: '<?php echo esc_js(__('Verify', 'staticq-media')); ?>',
                loading: '<?php echo esc_js(__('Loading...', 'staticq-media')); ?>',
                select_zone: '<?php echo esc_js(__('Select a zone...', 'staticq-media')); ?>',
                select_bucket: '<?php echo esc_js(__('Select a bucket...', 'staticq-media')); ?>',
                no_buckets: '<?php echo esc_js(__('No buckets found', 'staticq-media')); ?>',
                token_configured: '<?php echo esc_js(__('Token configured', 'staticq-media')); ?>',
                token_found_hint: '<?php echo esc_js(__('A saved token was found. Click Verify to check if it still works, or paste a new one.', 'staticq-media')); ?>',
                token_valid: '<?php echo esc_js(__('Token valid', 'staticq-media')); ?>',
                token_verified_saved: '<?php echo esc_js(__('Token verified and saved', 'staticq-media')); ?>',
                token_config_valid: '<?php echo esc_js(__('Token found in wp-config.php and verified', 'staticq-media')); ?>',
                token_not_in_config: '<?php echo esc_js(__('SQMEDIA_CF_TOKEN constant not found in wp-config.php. Please add it and try again.', 'staticq-media')); ?>',
                verify: '<?php echo esc_js(__('Verify', 'staticq-media')); ?>',
                verify_and_save: '<?php echo esc_js(__('Verify and Save', 'staticq-media')); ?>',
                verify_config_token: '<?php echo esc_js(__('Verify Token from wp-config.php', 'staticq-media')); ?>',
                account: '<?php echo esc_js(__('Account', 'staticq-media')); ?>',
                testing: '<?php echo esc_js(__('Testing...', 'staticq-media')); ?>',
                test_success: '<?php echo esc_js(__('Worker responding', 'staticq-media')); ?>',
                test_warning: '<?php echo esc_js(__('Test inconclusive', 'staticq-media')); ?>',
                response_time: '<?php echo esc_js(__('Response time', 'staticq-media')); ?>',
                source: '<?php echo esc_js(__('Source', 'staticq-media')); ?>',
                removing: '<?php echo esc_js(__('Removing...', 'staticq-media')); ?>',
                error_no_token: '<?php echo esc_js(__('Please verify your API token first.', 'staticq-media')); ?>',
                error_enter_token: '<?php echo esc_js(__('Please enter an API token.', 'staticq-media')); ?>',
                error_verify_token: '<?php echo esc_js(__('Please verify and save your token before continuing.', 'staticq-media')); ?>',
                error_verify_config_token: '<?php echo esc_js(__('Please verify the token from wp-config.php before continuing.', 'staticq-media')); ?>',
                error_select_zone: '<?php echo esc_js(__('Please select a zone.', 'staticq-media')); ?>',
                error_bucket_name: '<?php echo esc_js(__('Please enter or select a bucket name.', 'staticq-media')); ?>',
                error_worker_name: '<?php echo esc_js(__('Please enter a worker name.', 'staticq-media')); ?>',
                error_route_pattern: '<?php echo esc_js(__('Please enter a route pattern.', 'staticq-media')); ?>',
                error_connection: '<?php echo esc_js(__('Connection error. Please try again.', 'staticq-media')); ?>',
                error_deploy: '<?php echo esc_js(__('Deployment failed.', 'staticq-media')); ?>',
                error_undeploy: '<?php echo esc_js(__('Failed to remove worker', 'staticq-media')); ?>',
                error_loading_zones: '<?php echo esc_js(__('Error loading zones', 'staticq-media')); ?>',
                confirm_delete: '<?php echo esc_js(__('Yes, Remove Worker', 'staticq-media')); ?>',
                clearing: '<?php echo esc_js(__('Clearing...', 'staticq-media')); ?>',
                clear_local: '<?php echo esc_js(__('Clear Local Settings', 'staticq-media')); ?>',
                error_clear_local: '<?php echo esc_js(__('Failed to clear local settings', 'staticq-media')); ?>',
                copy: '<?php echo esc_js(__('Copy', 'staticq-media')); ?>',
                copied: '<?php echo esc_js(__('Copied!', 'staticq-media')); ?>'
            };
        <?php wp_add_inline_script('sqmedia-admin', ob_get_clean()); ?>
        <?php
        // Include the wizard JavaScript file
        $wizard_js_path = plugin_dir_url(dirname(__FILE__)) . 'includes/cloudflare/sqmedia-cloudflare-wizard.js';
        wp_enqueue_script('sqmedia-cloudflare-wizard', $wizard_js_path, [], SQMEDIA_VERSION, true);
    }
    
    /**
     * Render registered image sizes with checkboxes
     */
    private function render_registered_sizes(array $settings): void {
        // Get all registered WordPress image sizes
        $sizes = [];
        
        // Get intermediate sizes
        $intermediate_sizes = get_intermediate_image_sizes();
        
        foreach ($intermediate_sizes as $size_name) {
            $sizes[$size_name] = [
                'width' => get_option("{$size_name}_size_w"),
                'height' => get_option("{$size_name}_size_h"),
                'crop' => get_option("{$size_name}_crop") ? 'Yes' : 'No',
            ];
        }
        
        // Add custom sizes from theme/plugins
        global $_wp_additional_image_sizes;
        if (isset($_wp_additional_image_sizes)) {
            foreach ($_wp_additional_image_sizes as $size_name => $size_data) {
                $sizes[$size_name] = [
                    'width' => $size_data['width'],
                    'height' => $size_data['height'],
                    'crop' => !empty($size_data['crop']) ? 'Yes' : 'No',
                ];
            }
        }
        
        if (empty($sizes)) {
            echo '<p>' . esc_html__('No image sizes registered.', 'staticq-media') . '</p>';
            return;
        }
        
        // Get currently disabled sizes
        $disabled_sizes = $settings['disabled_sizes'] ?? [];
        if (!is_array($disabled_sizes)) {
            $disabled_sizes = [];
        }
        
        echo '<p class="description">' . esc_html__('Uncheck to disable generation of specific sizes.', 'staticq-media') . '</p>';
        
        echo '<table class="widefat sqmedia-sizes-table" style="max-width: 600px; margin-top: 10px;">';
        echo '<thead>';
        echo '<tr>';
        echo '<th style="width: 40px;"></th>';
        echo '<th>' . esc_html__('Size Name', 'staticq-media') . '</th>';
        echo '<th>' . esc_html__('Dimensions', 'staticq-media') . '</th>';
        echo '<th>' . esc_html__('Crop', 'staticq-media') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        foreach ($sizes as $size_name => $size_data) {
            $is_enabled = !in_array($size_name, $disabled_sizes, true);
            $row_class = $is_enabled ? '' : 'sqmedia-size-disabled';
            $width = $size_data['width'] ?: '∞';
            $height = $size_data['height'] ?: '∞';
            
            echo '<tr class="' . esc_attr($row_class) . '">';
            echo '<td style="text-align: center;">';
            echo '<input type="checkbox" name="sqmedia_enabled_sizes[]" value="' . esc_attr($size_name) . '"';
            if ($is_enabled) {
                echo ' checked';
            }
            echo '>';
            echo '</td>';
            echo '<td><code>' . esc_html($size_name) . '</code></td>';
            echo '<td>' . esc_html($width . ' × ' . $height) . '</td>';
            echo '<td>' . esc_html($size_data['crop']) . '</td>';
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';
        
        // .sqmedia-size-disabled style moved to admin/css/sqmedia-settings.css

        // Ignored sizes field is rendered separately as its own table row (see render_page)
    }
    
    /**
     * Save settings from form
     */
    private function save_settings(): void {
        // Nonce verified in render() via check_admin_referer('sqmedia_settings_nonce') before this method is called.
        $settings = [];

        // === Plugin Status ===
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['enabled'] = !empty($_POST['sqmedia_enabled']) ? 1 : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['manage_all_media'] = (!empty($_POST['sqmedia_manage_all_media']) && !empty($settings['enabled'])) ? 1 : 0;

        // === Storage Settings ===
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $storage_mode = sanitize_text_field(wp_unslash($_POST['sqmedia_storage_mode'] ?? 'cloud_only'));
        if (!in_array($storage_mode, ['local_only', 'cloud_and_local', 'cloud_only'], true)) {
            $storage_mode = 'cloud_only';
        }
        $settings['storage_mode'] = $storage_mode;

        // Storage provider is always R2 in the free plugin.
        $settings['storage_provider'] = 'r2';

        // Cloudflare R2 settings
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_account_id'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_account_id'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_access_key_id'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_access_key_id'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_secret_access_key'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_secret_access_key'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_bucket'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_bucket'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_prefix'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_prefix'] ?? 'wp-content/uploads'));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['force_prefix_in_url'] = !empty($_POST['sqmedia_force_prefix_in_url']);
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_public_access'] = sanitize_text_field(wp_unslash($_POST['sqmedia_r2_public_access'] ?? 'custom_domain'));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['r2_public_url'] = esc_url_raw(wp_unslash($_POST['sqmedia_r2_public_url'] ?? ''));

        // === Resizing Settings ===
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $resizing_tool = sanitize_text_field(wp_unslash($_POST['sqmedia_resizing_tool'] ?? 'wordpress'));
        $settings['cloudflare_enabled'] = ($resizing_tool === 'cloudflare') ? 1 : 0;

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['cloudflare_domain'] = sanitize_text_field(wp_unslash($_POST['sqmedia_cloudflare_domain'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['cloudflare_quality'] = sanitize_text_field(wp_unslash($_POST['sqmedia_cloudflare_quality'] ?? 'balanced'));

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['enable_webp'] = !empty($_POST['sqmedia_enable_webp']) ? 1 : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['strip_metadata'] = !empty($_POST['sqmedia_strip_metadata']) ? 1 : 0;

        // === Front-end Delivery ===
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['enable_picture_delivery'] = !empty($_POST['sqmedia_enable_picture_delivery']) ? 1 : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['delivery_ignored_classes'] = sanitize_text_field(wp_unslash($_POST['sqmedia_delivery_ignored_classes'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['delivery_ignored_sizes'] = sanitize_text_field(wp_unslash($_POST['sqmedia_delivery_ignored_sizes'] ?? ''));
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['enable_lazyload'] = !empty($_POST['sqmedia_enable_lazyload']) ? 1 : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['eager_first_image'] = !empty($_POST['sqmedia_eager_first_image']) ? 1 : 0;

        // === File Dimensions ===
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['enable_big_image_scaling'] = !empty($_POST['sqmedia_enable_big_image_scaling']) ? 1 : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['big_image_size_threshold_width'] = absint($_POST['sqmedia_big_image_size_threshold_width'] ?? 2560);
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['big_image_size_threshold_height'] = absint($_POST['sqmedia_big_image_size_threshold_height'] ?? 2560);
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['original_file_handling'] = sanitize_text_field(wp_unslash($_POST['sqmedia_original_file_handling'] ?? 'preserve'));

        // Handle enabled_sizes -> convert to disabled_sizes for storage
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        if (isset($_POST['sqmedia_enabled_sizes']) && is_array($_POST['sqmedia_enabled_sizes'])) {
            $all_sizes = array_keys(wp_get_registered_image_subsizes());
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
            $enabled_sizes = array_map('sanitize_text_field', wp_unslash($_POST['sqmedia_enabled_sizes']));
            $disabled_sizes = array_diff($all_sizes, $enabled_sizes);
            $settings['disabled_sizes'] = array_values($disabled_sizes);
        } else {
            $settings['disabled_sizes'] = array_keys(wp_get_registered_image_subsizes());
        }

        // Scanner ignored sizes
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in render()
        $settings['ignored_sizes'] = sanitize_text_field(wp_unslash($_POST['sqmedia_ignored_sizes'] ?? ''));

        // Save all settings
        $instance = SQMedia_Settings::get_instance();
        $instance->save_all($settings);
        $instance->clear_cache();
    }
}