<?php
if (!defined('ABSPATH')) exit;

class AIIO_Admin {

    public static function init() {
        add_action('in_admin_header', [__CLASS__, 'suppress_foreign_notices'], 1000);
        add_action('admin_menu', [__CLASS__, 'menu']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'assets']);
        add_filter('plugin_action_links_' . plugin_basename(AIIO_FILE), [__CLASS__, 'links']);

        add_action('wp_ajax_aiio_save_settings', [__CLASS__, 'ajax_save_settings']);
        add_action('wp_ajax_aiio_scan', [__CLASS__, 'ajax_scan']);
        add_action('wp_ajax_aiio_preview_optimize', [__CLASS__, 'ajax_preview_optimize']);
        add_action('wp_ajax_aiio_apply_optimize', [__CLASS__, 'ajax_apply_optimize']);
        add_action('wp_ajax_aiio_rollback', [__CLASS__, 'ajax_rollback']);
        add_action('wp_ajax_aiio_start_job', [__CLASS__, 'ajax_start_job']);
        add_action('wp_ajax_aiio_job_status', [__CLASS__, 'ajax_job_status']);
        add_action('wp_ajax_aiio_cancel_job', [__CLASS__, 'ajax_cancel_job']);
        add_action('wp_ajax_aiio_complete_onboarding', [__CLASS__, 'ajax_complete_onboarding']);
        add_action('wp_ajax_aiio_lcp_scan', [__CLASS__, 'ajax_lcp_scan']);
        add_action('wp_ajax_aiio_lcp_optimize', [__CLASS__, 'ajax_lcp_optimize']);
    }

    public static function ajax_lcp_scan() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $budget = max(50, absint(wp_unslash($_POST['budget_kb'] ?? aiio_get_settings()['lcp_budget_kb'] ?? 200)));
        wp_send_json_success(AIIO_LCP_Scanner::scan(['budget_kb' => $budget]));
    }

    public static function ajax_lcp_optimize() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $existing = AIIO_Queue::get_job();
        if ($existing && in_array($existing['status'] ?? '', ['running', 'paused'], true)) {
            wp_send_json_error(['message' => __('A job is already running.', 'pewit-ai-image-optimizer')]);
        }
        $ids = AIIO_LCP_Scanner::over_budget_attachment_ids();
        if (empty($ids)) {
            wp_send_json_error(['message' => __('No optimizable LCP images over budget. Run a scan first.', 'pewit-ai-image-optimizer')]);
        }
        $job = AIIO_Queue::create_job($ids, [
            'webp' => !empty(aiio_get_settings()['webp_enabled']),
            'avif' => !empty(aiio_get_settings()['avif_enabled']),
        ]);
        if (is_wp_error($job)) {
            wp_send_json_error(['message' => $job->get_error_message()]);
        }
        wp_send_json_success(['job' => $job, 'count' => count($ids)]);
    }

    public static function ajax_complete_onboarding() {
        AIIO_Onboarding::ajax_complete();
    }

    public static function links($links) {
        array_unshift($links, '<a href="' . esc_url(aiio_admin_page_url()) . '">' . esc_html__('Dashboard', 'pewit-ai-image-optimizer') . '</a>');
        return $links;
    }

    public static function menu() {
        $brand = aiio_brand_name();
        add_menu_page(
            $brand,
            $brand,
            'manage_options',
            'pewit-ai-image-optimizer',
            [__CLASS__, 'page'],
            'dashicons-performance',
            62
        );

        $items = [
            ['pewit-ai-image-optimizer', __('Dashboard', 'pewit-ai-image-optimizer')],
            ['pewit-ai-image-optimizer-images', __('Images', 'pewit-ai-image-optimizer')],
            ['pewit-ai-image-optimizer-jobs', __('Jobs', 'pewit-ai-image-optimizer')],
            ['pewit-ai-image-optimizer-settings', __('Settings', 'pewit-ai-image-optimizer')],
        ];

        foreach ($items as $item) {
            add_submenu_page(
                'pewit-ai-image-optimizer',
                $item[1],
                $item[1],
                'manage_options',
                $item[0],
                [__CLASS__, 'page']
            );
        }
    }

    public static function assets($hook) {
        if (strpos($hook, 'pewit-ai-image-optimizer') === false) {
            return;
        }

        wp_enqueue_style('pewit-shell', AIIO_URL . 'assets/css/pewit-admin-shell.css', [], AIIO_VERSION);
        wp_enqueue_style('aiio-admin', AIIO_URL . 'assets/css/admin.css', ['pewit-shell'], AIIO_VERSION);
        wp_enqueue_script('aiio-admin', AIIO_URL . 'assets/js/admin.js', ['jquery'], AIIO_VERSION, true);

        $scan = AIIO_Scanner::get_last_scan();
        $job = AIIO_Queue::get_job();

        wp_localize_script('aiio-admin', 'AIIO', [
            'ajax'          => admin_url('admin-ajax.php'),
            'nonce'         => wp_create_nonce('aiio_nonce'),
            'version'       => AIIO_VERSION,
            'plan'          => aiio_plan(),
            'canAutomate'   => aiio_can_automate() ? 1 : 0,
            'supportsWebp'  => AIIO_Optimizer::supports_webp() ? 1 : 0,
            'supportsAvif'  => AIIO_Optimizer::supports_avif() ? 1 : 0,
            'supportsFfmpeg'=> AIIO_Video_Optimizer::find_ffmpeg() ? 1 : 0,
            'upgrade_url'   => aiio_upgrade_url(),
            'docs_url'      => aiio_docs_url(),
            'page'          => aiio_current_page_slug(),
            'jobs_url'      => aiio_admin_page_url('pewit-ai-image-optimizer-jobs'),
            'images_url'    => aiio_admin_page_url('pewit-ai-image-optimizer-images'),
            'scan'          => $scan,
            'job'           => $job,
            'settings'      => aiio_get_settings(),
            'onboarding_done' => AIIO_Onboarding::is_done() ? 1 : 0,
            'i18n'          => AIIO_I18n::js_strings(),
        ]);
    }

    public static function page() {
        $slug = aiio_current_page_slug();
        $s = aiio_get_settings();
        $can_auto = true;
        $scan = AIIO_Scanner::get_last_scan();
        $job = AIIO_Queue::get_job();
        ?>
        <div class="wrap pewit-wrap pewit-ai-image-optimizer">
            <div class="pewit-app-body">
                <?php self::render_toolbar(); ?>
                <?php self::render_nav($slug); ?>
                <div id="aiio-notice" class="aiio-notice" aria-live="polite"></div>

                <?php
                switch ($slug) {
                    case 'pewit-ai-image-optimizer-images':
                        self::render_images($scan, $can_auto);
                        break;
                    case 'pewit-ai-image-optimizer-jobs':
                        self::render_jobs($job, $can_auto);
                        break;
                    case 'pewit-ai-image-optimizer-settings':
                        self::render_settings($s, $can_auto);
                        break;
                    default:
                        self::render_dashboard($scan, $job, $can_auto);
                        break;
                }
                ?>
            </div>
        </div>
        <?php
        if ($slug === 'pewit-ai-image-optimizer') {
            AIIO_Onboarding::render_modal();
        }
    }

    private static function render_toolbar() {
        $plan = aiio_plan();
        $can_auto = true;
        ?>
        <div class="pewit-app-toolbar">
            <div class="pewit-app-brand">
                <div class="pewit-app-icon" aria-hidden="true">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M8 11l3 3 5-6"/></svg>
                </div>
                <div>
                    <div class="pewit-app-title-row">
                        <span class="pewit-app-title"><?php echo esc_html(aiio_brand_name()); ?></span>
                        <span class="pewit-badge pewit-badge-plan pewit-plan-<?php echo esc_attr($plan); ?>">
                            <?php echo esc_html(sprintf(/* translators: %s are replaced with dynamic values */ __('Plan · %s', 'pewit-ai-image-optimizer'), aiio_plan_label())); ?>
                        </span>
                        <span class="pewit-version"><?php echo esc_html(AIIO_VERSION); ?></span>
                    </div>
                    <div class="pewit-app-subtitle">pewit-labs · pewit-ai-image-optimizer</div>
                </div>
            </div>
            <?php if (!$can_auto): ?>
            <a class="pewit-btn pewit-btn-primary" href="<?php echo esc_url(aiio_upgrade_url()); ?>">
                <?php esc_html_e('Upgrade for automation', 'pewit-ai-image-optimizer'); ?>
            </a>
            <?php endif; ?>
        </div>
        <?php
    }

    private static function render_nav($slug) {
        $items = [
            'pewit-ai-image-optimizer' => __('Dashboard', 'pewit-ai-image-optimizer'),
            'pewit-ai-image-optimizer-images' => __('Images', 'pewit-ai-image-optimizer'),
            'pewit-ai-image-optimizer-jobs' => __('Jobs', 'pewit-ai-image-optimizer'),
            'pewit-ai-image-optimizer-settings' => __('Settings', 'pewit-ai-image-optimizer'),
        ];
        ?>
        <nav class="pewit-tabs" aria-label="<?php esc_attr_e('Pewit AI Image Optimizer sections', 'pewit-ai-image-optimizer'); ?>">
            <?php foreach ($items as $key => $label): ?>
                <a class="pewit-tab <?php echo $slug === $key ? 'is-active' : ''; ?>" href="<?php echo esc_url(aiio_admin_page_url($key)); ?>">
                    <?php echo esc_html($label); ?>
                </a>
            <?php endforeach; ?>
        </nav>
        <?php
    }

    private static function render_dashboard($scan, $job, $can_auto) {
        $stats = $scan['stats'] ?? [];
        $over = intval($stats['over_threshold'] ?? 0);
        $job_status = $job['status'] ?? '';
        ?>
        <div class="pewit-hero-card">
            <h1><?php esc_html_e('Compress images safely', 'pewit-ai-image-optimizer'); ?></h1>
            <p class="pewit-lead"><?php esc_html_e('Scan your library, preview savings per image, and apply when you are ready. WebP & AVIF sidecars, AV1 video sidecars (ffmpeg), backups, and bulk background jobs are all included for free.', 'pewit-ai-image-optimizer'); ?></p>
            <div class="pewit-actions">
                <button type="button" class="pewit-btn pewit-btn-primary" id="aiio-scan-library">
                    <?php esc_html_e('Scan media library', 'pewit-ai-image-optimizer'); ?>
                </button>
                <a class="pewit-btn pewit-btn-secondary" href="<?php echo esc_url(aiio_admin_page_url('pewit-ai-image-optimizer-images')); ?>">
                    <?php esc_html_e('Open image list', 'pewit-ai-image-optimizer'); ?>
                </a>
            </div>
        </div>

        <?php if (class_exists('AIIO_Etch') && AIIO_Etch::is_active()): ?>
        <div class="pewit-callout pewit-callout-etch">
            <strong><?php esc_html_e('EtchWP', 'pewit-ai-image-optimizer'); ?></strong>
            <?php echo esc_html(AIIO_Etch::status_line()); ?>
        </div>
        <?php endif; ?>

        <?php $lcp = AIIO_LCP_Scanner::get_last_scan(); ?>
        <div class="pewit-card pewit-killer-card">
            <h2><?php esc_html_e('PageSpeed Budget', 'pewit-ai-image-optimizer'); ?></h2>
            <p class="description"><?php esc_html_e('Find LCP-critical images (featured + first in content) over your size budget.', 'pewit-ai-image-optimizer'); ?></p>
            <div class="pewit-actions">
                <button type="button" class="pewit-btn pewit-btn-secondary" id="aiio-lcp-scan"><?php esc_html_e('Scan LCP-critical images', 'pewit-ai-image-optimizer'); ?></button>
                <button type="button" class="pewit-btn pewit-btn-primary" id="aiio-lcp-optimize"><?php esc_html_e('Optimize LCP over budget', 'pewit-ai-image-optimizer'); ?></button>
            </div>
            <p class="description" id="aiio-lcp-summary">
                <?php
                if (!empty($lcp['time'])) {
                    printf(
                        /* translators: %1$d, %2$d are replaced with dynamic values */ esc_html__('Budget %1$d KB — %2$d over budget (last scan).', 'pewit-ai-image-optimizer'),
                        (int) ($lcp['budget_kb'] ?? 200),
                        (int) ($lcp['over_budget'] ?? 0)
                    );
                } else {
                    esc_html_e('No LCP scan yet.', 'pewit-ai-image-optimizer');
                }
                ?>
            </p>
        </div>

        <div class="pewit-grid pewit-grid-stats">
            <div class="pewit-card pewit-stat-card">
                <div class="pewit-stat-label"><?php esc_html_e('JPEG/PNG in library', 'pewit-ai-image-optimizer'); ?></div>
                <div class="pewit-stat-value" id="aiio-stat-total"><?php echo esc_html(intval($stats['total_images'] ?? 0)); ?></div>
            </div>
            <div class="pewit-card pewit-stat-card">
                <div class="pewit-stat-label"><?php esc_html_e('Over size threshold', 'pewit-ai-image-optimizer'); ?></div>
                <div class="pewit-stat-value" id="aiio-stat-over"><?php echo esc_html($over); ?></div>
            </div>
            <div class="pewit-card pewit-stat-card">
                <div class="pewit-stat-label"><?php esc_html_e('Optimizable', 'pewit-ai-image-optimizer'); ?></div>
                <div class="pewit-stat-value" id="aiio-stat-optimizable"><?php echo esc_html(intval($stats['optimizable'] ?? 0)); ?></div>
            </div>
            <div class="pewit-card pewit-stat-card">
                <div class="pewit-stat-label"><?php esc_html_e('Background job', 'pewit-ai-image-optimizer'); ?></div>
                <div class="pewit-stat-value pewit-stat-sm" id="aiio-stat-job">
                    <?php echo esc_html($job_status ? ucfirst($job_status) : __('None', 'pewit-ai-image-optimizer')); ?>
                </div>
            </div>
        </div>

        <?php if (!$can_auto): ?>
        <div class="pewit-callout pewit-callout-free">
            <strong><?php esc_html_e('Manual = Free forever', 'pewit-ai-image-optimizer'); ?></strong>
            <?php esc_html_e('Preview and apply compression one image at a time on any plan. Bulk jobs, WebP/AVIF sidecars, AV1 video sidecars, and rollback backups unlock with Pro.', 'pewit-ai-image-optimizer'); ?>
        </div>
        <?php endif; ?>

        <div class="pewit-card">
            <h3><?php esc_html_e('Quick start', 'pewit-ai-image-optimizer'); ?></h3>
            <ol class="aiio-steps">
                <li><?php esc_html_e('Set JPEG quality and PNG compression in Settings.', 'pewit-ai-image-optimizer'); ?></li>
                <li><?php esc_html_e('Run a library scan to find heavy images.', 'pewit-ai-image-optimizer'); ?></li>
                <li><?php esc_html_e('Preview savings on the Images tab, then Apply when satisfied.', 'pewit-ai-image-optimizer'); ?></li>
                <?php if ($can_auto): ?>
                <li><?php esc_html_e('Queue bulk optimization from Jobs — originals are backed up first.', 'pewit-ai-image-optimizer'); ?></li>
                <?php endif; ?>
            </ol>
        </div>
        <?php
    }

    private static function render_images($scan, $can_auto) {
        $items = $scan['items'] ?? [];
        $threshold = absint(aiio_get_settings()['size_threshold_kb'] ?? 200);
        ?>
        <div class="pewit-card">
            <div class="aiio-toolbar-row">
                <div>
                    <h2><?php esc_html_e('Heavy images', 'pewit-ai-image-optimizer'); ?></h2>
                    <p class="pewit-muted"><?php printf(/* translators: %d are replaced with dynamic values */ esc_html__('Showing JPEG/PNG files over %d KB from the last scan.', 'pewit-ai-image-optimizer'), absint($threshold)); ?></p>
                </div>
                <div class="pewit-actions">
                    <button type="button" class="pewit-btn pewit-btn-secondary" id="aiio-scan-library"><?php esc_html_e('Rescan', 'pewit-ai-image-optimizer'); ?></button>
                    <?php if ($can_auto && !empty($items)): ?>
                    <button type="button" class="pewit-btn pewit-btn-primary" id="aiio-bulk-start"><?php esc_html_e('Bulk optimize', 'pewit-ai-image-optimizer'); ?></button>
                    <?php endif; ?>
                </div>
            </div>

            <div id="aiio-image-list" class="aiio-image-list">
                <?php if (empty($items)): ?>
                    <p class="pewit-muted"><?php esc_html_e('No scan results yet. Run a scan from the Dashboard.', 'pewit-ai-image-optimizer'); ?></p>
                <?php else: ?>
                    <?php foreach ($items as $item): ?>
                        <?php self::render_image_row($item, $can_auto); ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div id="aiio-preview-panel" class="pewit-card aiio-preview-panel" hidden>
            <h3><?php esc_html_e('Optimization preview', 'pewit-ai-image-optimizer'); ?></h3>
            <div id="aiio-preview-body"></div>
            <div class="pewit-actions">
                <button type="button" class="pewit-btn pewit-btn-primary" id="aiio-apply-preview" disabled><?php esc_html_e('Apply optimization', 'pewit-ai-image-optimizer'); ?></button>
                <button type="button" class="pewit-btn pewit-btn-secondary" id="aiio-dismiss-preview"><?php esc_html_e('Dismiss', 'pewit-ai-image-optimizer'); ?></button>
            </div>
        </div>
        <?php
    }

    private static function render_image_row($item, $can_auto) {
        $id = intval($item['id'] ?? 0);
        if (!$id) {
            return;
        }
        ?>
        <div class="aiio-image-row" data-id="<?php echo esc_attr($id); ?>">
            <div class="aiio-image-thumb">
                <?php if (!empty($item['thumb'])): ?>
                    <img src="<?php echo esc_url($item['thumb']); ?>" alt="" width="48" height="48" loading="lazy" />
                <?php endif; ?>
            </div>
            <div class="aiio-image-meta">
                <strong><?php echo esc_html($item['filename'] ?? ('#' . $id)); ?></strong>
                <span class="pewit-muted">#<?php echo esc_html($id); ?> · <?php echo esc_html($item['size_label'] ?? ''); ?></span>
                <?php if (!empty($item['last_optimized'])): ?>
                    <span class="pewit-badge pewit-badge-ok"><?php esc_html_e('Optimized', 'pewit-ai-image-optimizer'); ?></span>
                <?php endif; ?>
                <?php if (empty($item['optimizable']) && !empty($item['skip_reason'])): ?>
                    <span class="pewit-muted"><?php echo esc_html($item['skip_reason']); ?></span>
                <?php endif; ?>
            </div>
            <div class="aiio-image-actions">
                <?php if (!empty($item['optimizable'])): ?>
                <button type="button" class="pewit-btn pewit-btn-secondary aiio-preview-btn" data-id="<?php echo esc_attr($id); ?>">
                    <?php esc_html_e('Preview', 'pewit-ai-image-optimizer'); ?>
                </button>
                <?php endif; ?>
                <?php if ($can_auto && !empty($item['has_backup'])): ?>
                <button type="button" class="pewit-btn pewit-btn-secondary aiio-rollback-btn" data-id="<?php echo esc_attr($id); ?>">
                    <?php esc_html_e('Rollback', 'pewit-ai-image-optimizer'); ?>
                </button>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private static function render_jobs($job, $can_auto) {
        if (!$can_auto) {
            ?>
            <div class="pewit-card pewit-card-pro">
                <h2><?php esc_html_e('Background jobs (Pro)', 'pewit-ai-image-optimizer'); ?></h2>
                <p><?php echo esc_html(aiio_automation_upgrade_message()); ?></p>
                <a class="pewit-btn pewit-btn-primary" href="<?php echo esc_url(aiio_upgrade_url()); ?>"><?php esc_html_e('Upgrade to Pro', 'pewit-ai-image-optimizer'); ?></a>
            </div>
            <?php
            return;
        }

        $status = $job['status'] ?? '';
        $total = intval($job['total'] ?? 0);
        $done = count($job['processed'] ?? []) + count($job['failed'] ?? []) + count($job['skipped'] ?? []);
        $pct = $total > 0 ? min(100, round(($done / $total) * 100)) : 0;
        ?>
        <div class="pewit-card">
            <div class="aiio-toolbar-row">
                <div>
                    <h2><?php esc_html_e('Background jobs', 'pewit-ai-image-optimizer'); ?></h2>
                    <p class="pewit-muted"><?php esc_html_e('Bulk optimization runs via WP-Cron, one image at a time with automatic backups.', 'pewit-ai-image-optimizer'); ?></p>
                </div>
                <div class="pewit-actions">
                    <?php if ($status === 'running'): ?>
                    <button type="button" class="pewit-btn pewit-btn-secondary" id="aiio-cancel-job"><?php esc_html_e('Cancel job', 'pewit-ai-image-optimizer'); ?></button>
                    <?php endif; ?>
                </div>
            </div>

            <div id="aiio-job-panel">
                <?php if (empty($job)): ?>
                    <p class="pewit-muted"><?php esc_html_e('No jobs yet. Start one from the Images tab.', 'pewit-ai-image-optimizer'); ?></p>
                <?php else: ?>
                    <div class="aiio-job-summary">
                        <div><strong><?php esc_html_e('Status', 'pewit-ai-image-optimizer'); ?>:</strong> <span id="aiio-job-status"><?php echo esc_html(ucfirst($status)); ?></span></div>
                        <div><strong><?php esc_html_e('Progress', 'pewit-ai-image-optimizer'); ?>:</strong> <span id="aiio-job-progress"><?php echo esc_html($done . ' / ' . $total); ?></span></div>
                        <div class="aiio-progress"><span id="aiio-job-bar" style="width:<?php echo esc_attr($pct); ?>%"></span></div>
                    </div>
                    <div class="aiio-job-log" id="aiio-job-log">
                        <?php foreach (array_reverse($job['log'] ?? []) as $entry): ?>
                            <div class="aiio-log-line aiio-log-<?php echo esc_attr($entry['level'] ?? 'info'); ?>">
                                <span class="aiio-log-time"><?php echo esc_html($entry['time'] ?? ''); ?></span>
                                <?php echo esc_html($entry['message'] ?? ''); ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private static function render_settings($s, $can_auto) {
        $webp_supported = AIIO_Optimizer::supports_webp();
        $avif_supported = AIIO_Optimizer::supports_avif();
        $ffmpeg = AIIO_Video_Optimizer::find_ffmpeg();
        ?>
        <div class="pewit-card aiio-settings">
            <h2><?php esc_html_e('Compression settings', 'pewit-ai-image-optimizer'); ?></h2>
            <p class="pewit-muted"><?php esc_html_e('Uses WordPress wp_get_image_editor() — no external binaries required.', 'pewit-ai-image-optimizer'); ?></p>

            <div class="aiio-field">
                <label for="aiio_jpeg_quality"><?php esc_html_e('JPEG quality', 'pewit-ai-image-optimizer'); ?></label>
                <input type="number" id="aiio_jpeg_quality" min="1" max="100" value="<?php echo esc_attr(intval($s['jpeg_quality'] ?? 82)); ?>" />
                <p class="description"><?php esc_html_e('1–100. Default 82 is a good balance of size and quality.', 'pewit-ai-image-optimizer'); ?></p>
            </div>

            <div class="aiio-field">
                <label for="aiio_png_compression"><?php esc_html_e('PNG compression level', 'pewit-ai-image-optimizer'); ?></label>
                <input type="number" id="aiio_png_compression" min="0" max="9" value="<?php echo esc_attr(intval($s['png_compression'] ?? 6)); ?>" />
                <p class="description"><?php esc_html_e('0 = none, 9 = maximum compression.', 'pewit-ai-image-optimizer'); ?></p>
            </div>

            <div class="aiio-field">
                <label for="aiio_size_threshold_kb"><?php esc_html_e('Scan size threshold (KB)', 'pewit-ai-image-optimizer'); ?></label>
                <input type="number" id="aiio_size_threshold_kb" min="1" max="10240" value="<?php echo esc_attr(intval($s['size_threshold_kb'] ?? 200)); ?>" />

                <label for="aiio_lcp_budget_kb"><?php esc_html_e('PageSpeed Budget — LCP image max (KB)', 'pewit-ai-image-optimizer'); ?></label>
                <input type="number" id="aiio_lcp_budget_kb" min="50" max="1024" value="<?php echo esc_attr(intval($s['lcp_budget_kb'] ?? 200)); ?>" />
                <p class="description"><?php esc_html_e('Featured and first content images over this size appear in LCP scan.', 'pewit-ai-image-optimizer'); ?></p>
                <p class="description"><?php esc_html_e('Library scan lists images larger than this size.', 'pewit-ai-image-optimizer'); ?></p>
            </div>

            <div class="aiio-field aiio-field-pro">
                <label>
                    <input type="checkbox" id="aiio_webp_enabled" value="1" <?php checked(!empty($s['webp_enabled'])); ?> <?php disabled(!$can_auto); ?> />
                    <?php esc_html_e('Create WebP sidecar alongside original', 'pewit-ai-image-optimizer'); ?>
                </label>
                <?php if (!$can_auto): ?>
                    <p class="description"><?php echo esc_html(aiio_automation_upgrade_message()); ?></p>
                <?php elseif (!$webp_supported): ?>
                    <p class="description aiio-warn"><?php esc_html_e('WebP is not supported on this server (imagewebp / Imagick required).', 'pewit-ai-image-optimizer'); ?></p>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('Keeps the original JPEG/PNG and writes a .webp copy in the same folder.', 'pewit-ai-image-optimizer'); ?></p>
                    <label for="aiio_webp_priority"><?php esc_html_e('WebP compression priority', 'pewit-ai-image-optimizer'); ?></label>
                    <select id="aiio_webp_priority" <?php disabled(!$can_auto); ?>>
                        <?php
                        $webp_priority = AIIO_Optimizer::webp_priority();
                        foreach (AIIO_Optimizer::webp_priority_labels() as $key => $label) :
                            ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($webp_priority, $key); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">
                        <?php
                        printf(
                            /* translators: %d are replaced with dynamic values */ esc_html__('Encodes at quality %d. Balanced is the recommended default for photos on the web.', 'pewit-ai-image-optimizer'),
                            absint(AIIO_Optimizer::webp_quality())
                        );
                        ?>
                    </p>
                <?php endif; ?>
            </div>

            <div class="aiio-field aiio-field-pro">
                <label>
                    <input type="checkbox" id="aiio_avif_enabled" value="1" <?php checked(!empty($s['avif_enabled'])); ?> <?php disabled(!$can_auto); ?> />
                    <?php esc_html_e('Create AVIF sidecar alongside original', 'pewit-ai-image-optimizer'); ?>
                </label>
                <?php if (!$can_auto): ?>
                    <p class="description"><?php echo esc_html(aiio_automation_upgrade_message()); ?></p>
                <?php elseif (!$avif_supported): ?>
                    <p class="description aiio-warn"><?php esc_html_e('AVIF is not supported on this server (imageavif / Imagick with libavif required).', 'pewit-ai-image-optimizer'); ?></p>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('Keeps the original JPEG/PNG and writes a .avif copy in the same folder.', 'pewit-ai-image-optimizer'); ?></p>
                    <label for="aiio_avif_quality"><?php esc_html_e('AVIF quality', 'pewit-ai-image-optimizer'); ?></label>
                    <input type="number" id="aiio_avif_quality" min="1" max="100" value="<?php echo esc_attr(intval($s['avif_quality'] ?? 50)); ?>" />
                <?php endif; ?>
            </div>

            <div class="aiio-field aiio-field-pro">
                <label>
                    <input type="checkbox" id="aiio_video_av1_enabled" value="1" <?php checked(!empty($s['video_av1_enabled'])); ?> <?php disabled(!$can_auto); ?> />
                    <?php esc_html_e('Create AV1 WebM sidecar for videos (ffmpeg)', 'pewit-ai-image-optimizer'); ?>
                </label>
                <?php if (!$can_auto): ?>
                    <p class="description"><?php echo esc_html(aiio_automation_upgrade_message()); ?></p>
                <?php elseif (!$ffmpeg): ?>
                    <p class="description aiio-warn"><?php esc_html_e('ffmpeg not found — install ffmpeg with libsvtav1 or libaom-av1 for video sidecars.', 'pewit-ai-image-optimizer'); ?></p>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('Keeps the original MP4/MOV and writes a .av1.webm copy. Included in library scan and bulk jobs.', 'pewit-ai-image-optimizer'); ?></p>
                    <label for="aiio_video_av1_crf"><?php esc_html_e('AV1 CRF (lower = better quality)', 'pewit-ai-image-optimizer'); ?></label>
                    <input type="number" id="aiio_video_av1_crf" min="20" max="50" value="<?php echo esc_attr(intval($s['video_av1_crf'] ?? 32)); ?>" />
                <?php endif; ?>
            </div>

            <?php if ($can_auto): ?>
            <div class="aiio-field">
                <h3><?php esc_html_e('Automation', 'pewit-ai-image-optimizer'); ?></h3>
                <label>
                    <input type="checkbox" id="aiio_auto_optimize_upload" value="1" <?php checked(!empty($s['auto_optimize_upload'])); ?> />
                    <?php esc_html_e('Auto-optimize JPEG/PNG and videos on upload', 'pewit-ai-image-optimizer'); ?>
                </label>
            </div>
            <?php endif; ?>

            <div class="aiio-field">
                <h3><?php esc_html_e('Scan scope', 'pewit-ai-image-optimizer'); ?></h3>
                <label>
                    <input type="checkbox" id="aiio_only_used_images" value="1" <?php checked(!empty($s['only_used_images'])); ?> />
                    <?php esc_html_e('Only images used in published content (featured + in-content)', 'pewit-ai-image-optimizer'); ?>
                </label>
                <label for="aiio_exclude_filename_patterns"><?php esc_html_e('Exclude filename patterns (one per line, fnmatch)', 'pewit-ai-image-optimizer'); ?></label>
                <textarea id="aiio_exclude_filename_patterns" rows="3" class="large-text"><?php echo esc_textarea($s['exclude_filename_patterns'] ?? ''); ?></textarea>
                <p class="description"><?php esc_html_e('Example: *-logo* · *favicon* · skip icons and brand assets from bulk jobs.', 'pewit-ai-image-optimizer'); ?></p>
            </div>

            <div class="aiio-field">
                <label>
                    <input type="checkbox" id="aiio_notify_email_enabled" value="1" <?php checked(!empty($s['notify_email_enabled'])); ?> />
                    <?php esc_html_e('Email when bulk job completes', 'pewit-ai-image-optimizer'); ?>
                </label>
                <label for="aiio_notify_email_to"><?php esc_html_e('Recipient', 'pewit-ai-image-optimizer'); ?></label>
                <input type="email" id="aiio_notify_email_to" class="regular-text" value="<?php echo esc_attr($s['notify_email_to']); ?>" />
                <label>
                    <input type="checkbox" id="aiio_notify_include_csv" value="1" <?php checked(!empty($s['notify_include_csv'])); ?> />
                    <?php esc_html_e('Attach CSV summary to job completion email', 'pewit-ai-image-optimizer'); ?>
                </label>
            </div>

            <div class="pewit-actions">
                <button type="button" class="pewit-btn pewit-btn-primary" id="aiio-save-settings"><?php esc_html_e('Save settings', 'pewit-ai-image-optimizer'); ?></button>
            </div>

            <?php if (class_exists('AIIO_Etch') && AIIO_Etch::is_active()): ?>
            <div class="aiio-field">
                <h3><?php esc_html_e('EtchWP integration', 'pewit-ai-image-optimizer'); ?></h3>
                <p class="description"><?php echo esc_html(AIIO_Etch::status_line()); ?></p>
                <label>
                    <input type="checkbox" id="aiio_only_etch_images" value="1" <?php checked(!empty($s['only_etch_images'])); ?> />
                    <?php esc_html_e('Scan only images used in Etch (Media props / blocks)', 'pewit-ai-image-optimizer'); ?>
                </label>
                <label>
                    <input type="checkbox" id="aiio_etch_native_ui" value="1" <?php checked(AIIO_Etch::use_native_admin_ui()); ?> />
                    <?php esc_html_e('Use Etch-native dark admin styling', 'pewit-ai-image-optimizer'); ?>
                </label>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function ajax_save_settings() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $current = aiio_get_settings();
        $settings = [
            'jpeg_quality' => max(1, min(100, absint(wp_unslash($_POST['jpeg_quality'] ?? $current['jpeg_quality'])))),
            'png_compression' => max(0, min(9, absint(wp_unslash($_POST['png_compression'] ?? $current['png_compression'])))),
            'size_threshold_kb' => max(1, min(10240, absint(wp_unslash($_POST['size_threshold_kb'] ?? $current['size_threshold_kb'])))),
            'webp_enabled' => 0,
            'webp_priority' => AIIO_Optimizer::webp_priority(),
            'avif_enabled' => 0,
            'avif_quality' => max(1, min(100, absint(wp_unslash($_POST['avif_quality'] ?? $current['avif_quality'] ?? 50)))),
            'video_av1_enabled' => 0,
            'video_av1_crf' => max(20, min(50, absint(wp_unslash($_POST['video_av1_crf'] ?? $current['video_av1_crf'] ?? 32)))),
            'only_etch_images' => !empty($_POST['only_etch_images']) ? 1 : 0,
            'etch_native_ui' => !empty($_POST['etch_native_ui']) ? 1 : 0,
            'notify_email_enabled' => !empty($_POST['notify_email_enabled']) ? 1 : 0,
            'notify_email_to' => sanitize_email(wp_unslash($_POST['notify_email_to'] ?? $current['notify_email_to'])),
            'notify_include_csv' => !empty($_POST['notify_include_csv']) ? 1 : 0,
            'only_used_images' => !empty($_POST['only_used_images']) ? 1 : 0,
            'exclude_filename_patterns' => sanitize_textarea_field(wp_unslash($_POST['exclude_filename_patterns'] ?? $current['exclude_filename_patterns'] ?? '')),
            'lcp_budget_kb' => max(50, min(1024, absint(wp_unslash($_POST['lcp_budget_kb'] ?? $current['lcp_budget_kb'] ?? 200)))),
        ];
            $settings['webp_enabled'] = !empty($_POST['webp_enabled']) ? 1 : 0;
            $allowed_webp = array_keys(AIIO_Optimizer::webp_quality_map());
            $webp_priority = sanitize_key(wp_unslash($_POST['webp_priority'] ?? $current['webp_priority'] ?? 'balanced'));
            $settings['webp_priority'] = in_array($webp_priority, $allowed_webp, true) ? $webp_priority : 'balanced';
            $settings['avif_enabled'] = !empty($_POST['avif_enabled']) ? 1 : 0;
            $settings['video_av1_enabled'] = !empty($_POST['video_av1_enabled']) ? 1 : 0;
            $settings['auto_optimize_upload'] = !empty($_POST['auto_optimize_upload']) ? 1 : 0;
        aiio_update_settings(array_merge($current, $settings));
        wp_send_json_success(['message' => __('Settings saved.', 'pewit-ai-image-optimizer'), 'settings' => aiio_get_settings()]);
    }

    public static function ajax_scan() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $scan = AIIO_Scanner::scan();
        wp_send_json_success($scan);
    }

    public static function ajax_preview_optimize() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $id = absint(wp_unslash($_POST['attachment_id'] ?? 0));
        $result = AIIO_Media_Apply::preview($id);
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }
        wp_send_json_success($result);
    }

    public static function ajax_apply_optimize() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $id = absint(wp_unslash($_POST['attachment_id'] ?? 0));
        $webp = !empty($_POST['webp']);
        $avif = !empty($_POST['avif']);
        $result = AIIO_Media_Apply::apply($id, ['webp' => $webp, 'avif' => $avif]);
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }
        wp_send_json_success($result);
    }

    public static function ajax_rollback() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $id = absint(wp_unslash($_POST['attachment_id'] ?? 0));
        $result = AIIO_Backup::rollback($id);
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }
        wp_send_json_success($result);
    }

    public static function ajax_start_job() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        $raw_ids = isset($_POST['attachment_ids']) ? (array) wp_unslash($_POST['attachment_ids']) : [];
        $ids = array_values(array_filter(array_map('absint', $raw_ids)));
        $webp = !empty($_POST['webp']);
        $avif = !empty($_POST['avif']);
        $job = AIIO_Queue::create_job($ids, ['webp' => $webp, 'avif' => $avif]);
        if (is_wp_error($job)) {
            wp_send_json_error(['message' => $job->get_error_message()]);
        }
        wp_send_json_success(['job' => $job]);
    }

    public static function ajax_job_status() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        wp_send_json_success(['job' => AIIO_Queue::get_job()]);
    }

    public static function ajax_cancel_job() {
        check_ajax_referer('aiio_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-image-optimizer')], 403);
        }
        AIIO_Queue::cancel_job();
        wp_send_json_success(['job' => AIIO_Queue::get_job()]);
    }

    /**
     * Other plugins often print license nags on every admin screen.
     * Clear them on our UI so the PEWIT shell stays clean.
     */
    public static function suppress_foreign_notices() {
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        if ($page === '' || strpos($page, 'pewit-ai-image-optimizer') !== 0) {
            return;
        }
        remove_all_actions('admin_notices');
        remove_all_actions('all_admin_notices');
        remove_all_actions('user_admin_notices');
        remove_all_actions('network_admin_notices');
    }
}
