<?php

/**
 * Media Library Optimization Integration
 *
 * Adds image optimization features to the WordPress Media Library:
 * - Bulk actions in Media Library (list and grid views)
 * - Optimization status column in list view
 * - Detailed metabox on attachment edit page
 * - Optimization field in media modal
 *
 * @package ProRank\SEO\Admin
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Admin;

use ProRank\SEO\Plugin;
use WP_Post;

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


/**
 * MediaLibraryOptimization class
 */


class MediaLibraryOptimization {
	/**
	 * Valid optimization filter values.
	 *
	 * @var string[]
	 */
	private const VALID_OPT_FILTERS = [
		'optimized',
		'not_optimized',
		'webp',
		'avif',
		'backup',
	];

	/**
	 * Plugin instance
	 *
	 * @var Plugin
	 */
	private Plugin $plugin;

	/**
	 * Constructor
	 *
	 * @param Plugin $plugin Plugin instance.
	 */
	public function __construct( Plugin $plugin ) {
		$this->plugin = $plugin;
		$this->init();
	}

	/**
	 * Initialize media library optimization features
	 */
	private function init(): void {
		// Only load in admin
		if ( ! is_admin() ) {
			return;
		}

		// Check if image optimization module is enabled
		if ( ! $this->is_image_optimization_enabled() ) {
			return;
		}

		// Bulk actions
		add_filter( 'bulk_actions-upload', [ $this, 'add_bulk_actions' ] );
		add_filter( 'handle_bulk_actions-upload', [ $this, 'handle_bulk_actions' ], 10, 3 );
		add_action( 'admin_notices', [ $this, 'show_bulk_action_notice' ] );

		// Media Library column
		add_filter( 'manage_upload_columns', [ $this, 'add_optimization_column' ] );
		add_action( 'manage_media_custom_column', [ $this, 'display_optimization_column' ], 10, 2 );
		add_filter( 'manage_upload_sortable_columns', [ $this, 'make_column_sortable' ] );
		add_action( 'restrict_manage_posts', [ $this, 'add_optimization_filter' ] );
		add_action( 'pre_get_posts', [ $this, 'filter_media_by_optimization_status' ], 9 );
		add_action( 'pre_get_posts', [ $this, 'sort_by_optimization_status' ] );

		// Attachment edit page metabox
		add_action( 'add_meta_boxes_attachment', [ $this, 'add_optimization_metabox' ] );

		// Media modal optimization field
		add_filter( 'attachment_fields_to_edit', [ $this, 'add_optimization_fields' ], 10, 2 );

		// Enqueue scripts
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );

		// AJAX handler for single image optimization
		add_action( 'wp_ajax_prorank_optimize_single_image', [ $this, 'ajax_optimize_single_image' ] );
		add_action( 'wp_ajax_prorank_restore_single_image', [ $this, 'ajax_restore_single_image' ] );
		add_action( 'wp_ajax_prorank_get_image_optimization_status', [ $this, 'ajax_get_optimization_status' ] );
	}

	/**
	 * Check if image optimization module is enabled
	 *
	 * @return bool
	 */
    private function is_image_optimization_enabled(): bool {
        $modules = $this->plugin->modules();

        // Check if module is enabled
        return $modules->is_module_enabled( 'image_optimization' )
			|| $modules->is_module_enabled( 'image-optimization' )
			|| $modules->is_module_enabled( 'performance' );
	}

	/**
	 * Add bulk actions to media library
	 *
	 * @param array $bulk_actions Current bulk actions.
	 * @return array Modified bulk actions.
	 */
	public function add_bulk_actions( array $bulk_actions ): array {
		$bulk_actions['prorank_optimize']       = __( 'Optimize with ProRank', 'prorank-seo' );
		$bulk_actions['prorank_generate_webp']  = __( 'Generate WebP', 'prorank-seo' );
		$bulk_actions['prorank_generate_avif']  = __( 'Generate AVIF', 'prorank-seo' );
		$bulk_actions['prorank_restore']        = __( 'Restore Original', 'prorank-seo' );

		return $bulk_actions;
	}

	/**
	 * Handle bulk actions
	 *
	 * @param string $redirect_to Redirect URL.
	 * @param string $doaction    Action being performed.
	 * @param array  $post_ids    Post IDs.
	 * @return string Modified redirect URL.
	 */
	public function handle_bulk_actions( string $redirect_to, string $doaction, array $post_ids ): string {
		if ( ! str_starts_with( $doaction, 'prorank_' ) ) {
			return $redirect_to;
		}

		// Verify permissions
		if ( ! current_user_can( 'upload_files' ) ) {
			return $redirect_to;
		}

		$processed = 0;
		$action_type = str_replace( 'prorank_', '', $doaction );

		foreach ( $post_ids as $attachment_id ) {
			// Verify it's an image
			if ( ! wp_attachment_is_image( $attachment_id ) ) {
				continue;
			}

			// Schedule with Action Scheduler for async processing
			if ( function_exists( 'as_enqueue_async_action' ) ) {
				as_enqueue_async_action(
					'prorank_optimize_single_image',
					[
						'attachment_id' => $attachment_id,
						'action_type'   => $action_type,
					],
					'prorank-image-optimization'
				);
				$processed++;
			} else {
				// Process synchronously if Action Scheduler not available
				$this->process_single_image( $attachment_id, $action_type );
				$processed++;
			}
		}

		return add_query_arg(
			[
				'prorank_optimized' => $processed,
				'prorank_action'    => $action_type,
			],
			$redirect_to
		);
	}

	/**
	 * Process single image optimization
	 *
	 * @param int    $attachment_id Attachment ID.
	 * @param string $action_type   Action type (optimize, generate_webp, generate_avif, restore).
	 * @return array|bool|\WP_Error Result array, bool, or error.
	 */
	public function process_single_image( int $attachment_id, string $action_type ) {
		$module = $this->get_image_optimization_module();
		if ( ! $module ) {
			return new \WP_Error( 'module_not_found', __( 'Image optimization module not found.', 'prorank-seo' ) );
		}

		$metadata = wp_get_attachment_metadata( $attachment_id );
		if ( ! $metadata ) {
			return new \WP_Error( 'no_metadata', __( 'Unable to get attachment metadata.', 'prorank-seo' ) );
		}

		switch ( $action_type ) {
			case 'optimize':
			case 'generate_webp':
			case 'generate_avif':
				// All optimization actions use the main generate_optimized_images method
				// Format-specific generation is controlled by module settings
				return $module->generate_optimized_images( $metadata, $attachment_id );

			case 'restore':
				$result = $module->restore_from_backup( $attachment_id );
				if ( $result ) {
					return [ 'success' => true, 'message' => __( 'Image restored successfully.', 'prorank-seo' ) ];
				}
				return new \WP_Error( 'restore_failed', __( 'Failed to restore image. Backup may not exist.', 'prorank-seo' ) );

			default:
				return new \WP_Error( 'invalid_action', __( 'Invalid action type.', 'prorank-seo' ) );
		}
	}

	/**
	 * Show bulk action notice
	 */
	public function show_bulk_action_notice(): void {
		if ( ! isset( $_GET['prorank_optimized'] ) ) {
			return;
		}

		$count = intval( prorank_get_query_var( 'prorank_optimized' ) );
		$action = prorank_get_query_var( 'prorank_action' );
		if ( $action === '' ) {
			$action = 'optimize';
		}

		$messages = [
			/* translators: %d: number of images */
			'optimize'      => _n(
				'%d image scheduled for optimization.',
				'%d images scheduled for optimization.',
				$count,
				'prorank-seo'
			),
			/* translators: %d: number of images */
			'generate_webp' => _n(
				'%d image scheduled for WebP generation.',
				'%d images scheduled for WebP generation.',
				$count,
				'prorank-seo'
			),
			/* translators: %d: number of images */
			'generate_avif' => _n(
				'%d image scheduled for AVIF generation.',
				'%d images scheduled for AVIF generation.',
				$count,
				'prorank-seo'
			),
			/* translators: %d: number of images */
			'restore'       => _n(
				'%d image scheduled for restoration.',
				'%d images scheduled for restoration.',
				$count,
				'prorank-seo'
			),
		];

		$message = $messages[ $action ] ?? $messages['optimize'];

		printf(
			'<div class="notice notice-success is-dismissible"><p>%s</p></div>',
			esc_html( sprintf( $message, $count ) )
		);
	}

	/**
	 * Add optimization column to media library
	 *
	 * @param array $columns Current columns.
	 * @return array Modified columns.
	 */
	public function add_optimization_column( array $columns ): array {
		$columns['prorank_optimization'] = __( 'Optimization', 'prorank-seo' );
		return $columns;
	}

	/**
	 * Display optimization column content
	 *
	 * @param string $column_name  Column name.
	 * @param int    $attachment_id Attachment ID.
	 */
	public function display_optimization_column( string $column_name, int $attachment_id ): void {
		if ( $column_name !== 'prorank_optimization' ) {
			return;
		}

		// Only show for images
		if ( ! wp_attachment_is_image( $attachment_id ) ) {
			echo '<span class="prorank-badge prorank-badge-na">—</span>';
			return;
		}

		$optimized = get_post_meta( $attachment_id, '_prorank_optimized', true );
		$savings = (int) get_post_meta( $attachment_id, '_prorank_bytes_saved', true );
		$original = (int) get_post_meta( $attachment_id, '_prorank_original_size', true );
		$webp_generated = get_post_meta( $attachment_id, '_prorank_webp_generated', true );
		$avif_generated = get_post_meta( $attachment_id, '_prorank_avif_generated', true );

		// Check for queued status
		$queued = false;
		if ( function_exists( 'as_has_scheduled_action' ) ) {
			$queued = as_has_scheduled_action( 'prorank_optimize_single_image', [ 'attachment_id' => $attachment_id ] );
		}

		if ( $queued ) {
			echo '<span class="prorank-badge prorank-badge-queued" title="' . esc_attr__( 'Queued for optimization', 'prorank-seo' ) . '">';
			echo '<span class="dashicons dashicons-clock"></span> ' . esc_html__( 'Queued', 'prorank-seo' );
			echo '</span>';
			return;
		}

		if ( $optimized === '1' && $original > 0 ) {
			$percent = round( ( $savings / $original ) * 100, 1 );

			$formats = [];
			if ( $webp_generated ) {
				$formats[] = 'WebP';
			}
			if ( $avif_generated ) {
				$formats[] = 'AVIF';
			}

			$format_text = ! empty( $formats ) ? ' (' . implode( ', ', $formats ) . ')' : '';
			$title = sprintf(
				/* translators: 1: Percentage saved, 2: Bytes saved, 3: Format list */
				__( 'Saved %1$s%% (%2$s)%3$s', 'prorank-seo' ),
				$percent,
				size_format( $savings ),
				$format_text
			);

			echo '<span class="prorank-badge prorank-badge-success" title="' . esc_attr( $title ) . '">';
			echo '<span class="dashicons dashicons-yes-alt"></span> ' . esc_html( $percent . '%' );
			if ( ! empty( $formats ) ) {
				echo '<small style="display:block;font-size:10px;margin-top:2px;">' . esc_html( implode( ' · ', $formats ) ) . '</small>';
			}
			echo '</span>';
		} else {
			echo '<span class="prorank-badge prorank-badge-pending" title="' . esc_attr__( 'Not optimized', 'prorank-seo' ) . '">';
			echo '<span class="dashicons dashicons-clock"></span> ' . esc_html__( 'Pending', 'prorank-seo' );
			echo '</span>';
			echo '<button type="button" class="button button-small prorank-optimize-now-btn" data-attachment-id="' . esc_attr( $attachment_id ) . '" style="margin-top:4px;">';
			echo esc_html__( 'Optimize', 'prorank-seo' );
			echo '</button>';
		}
	}

	/**
	 * Make column sortable
	 *
	 * @param array $columns Sortable columns.
	 * @return array Modified columns.
	 */
	public function make_column_sortable( array $columns ): array {
		$columns['prorank_optimization'] = 'prorank_optimization';
		return $columns;
	}

	/**
	 * Add optimization status filter dropdown to Media Library list view.
	 */
	public function add_optimization_filter(): void {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || $screen->base !== 'upload' ) {
			return;
		}

		$selected = filter_input( INPUT_GET, 'prorank_opt_filter', FILTER_UNSAFE_RAW );
		$selected = is_string( $selected ) ? sanitize_text_field( $selected ) : '';
		if ( ! in_array( $selected, self::VALID_OPT_FILTERS, true ) ) {
			$selected = '';
		}

		echo '<select name="prorank_opt_filter" class="prorank-opt-filter">';
		echo '<option value="">' . esc_html__( 'Any ProRank State', 'prorank-seo' ) . '</option>';
		echo '<option value="optimized"' . selected( $selected, 'optimized', false ) . '>' . esc_html__( 'Optimized', 'prorank-seo' ) . '</option>';
		echo '<option value="not_optimized"' . selected( $selected, 'not_optimized', false ) . '>' . esc_html__( 'Not optimized', 'prorank-seo' ) . '</option>';
		echo '<option value="webp"' . selected( $selected, 'webp', false ) . '>' . esc_html__( 'WebP generated', 'prorank-seo' ) . '</option>';
		echo '<option value="avif"' . selected( $selected, 'avif', false ) . '>' . esc_html__( 'AVIF generated', 'prorank-seo' ) . '</option>';
		echo '<option value="backup"' . selected( $selected, 'backup', false ) . '>' . esc_html__( 'Has backup', 'prorank-seo' ) . '</option>';
		echo '</select>';
	}

	/**
	 * Filter media items by optimization status.
	 *
	 * @param WP_Query $query Query object.
	 */
	public function filter_media_by_optimization_status( $query ): void {
		if ( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}

		if ( $query->get( 'post_type' ) !== 'attachment' ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && $screen->base !== 'upload' ) {
			return;
		}

		$filter = filter_input( INPUT_GET, 'prorank_opt_filter', FILTER_UNSAFE_RAW );
		$filter = is_string( $filter ) ? sanitize_text_field( $filter ) : '';
		if ( ! in_array( $filter, self::VALID_OPT_FILTERS, true ) ) {
			return;
		}

		$meta_query = $query->get( 'meta_query' );
		if ( ! is_array( $meta_query ) ) {
			$meta_query = [];
		}

		switch ( $filter ) {
			case 'optimized':
				$meta_query[] = [
					'key'     => '_prorank_optimized',
					'value'   => '1',
					'compare' => '=',
				];
				break;
			case 'not_optimized':
				$meta_query[] = [
					'relation' => 'OR',
					[
						'key'     => '_prorank_optimized',
						'compare' => 'NOT EXISTS',
					],
					[
						'key'     => '_prorank_optimized',
						'value'   => '1',
						'compare' => '!=',
					],
				];
				break;
			case 'webp':
				$meta_query[] = [
					'key'     => '_prorank_webp_generated',
					'value'   => '1',
					'compare' => '=',
				];
				break;
			case 'avif':
				$meta_query[] = [
					'key'     => '_prorank_avif_generated',
					'value'   => '1',
					'compare' => '=',
				];
				break;
			case 'backup':
				$meta_query[] = [
					'key'     => '_prorank_backup_path',
					'compare' => 'EXISTS',
				];
				break;
		}

		$query->set( 'meta_query', $meta_query );
	}

	/**
	 * Sort by optimization status
	 *
	 * @param WP_Query $query Query object.
	 */
	public function sort_by_optimization_status( $query ): void {
		if ( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}

		if ( $query->get( 'orderby' ) !== 'prorank_optimization' ) {
			return;
		}

		$query->set( 'meta_key', '_prorank_optimized' );
		$query->set( 'orderby', 'meta_value' );
	}

	/**
	 * Add optimization metabox to attachment edit page
	 */
	public function add_optimization_metabox(): void {
		global $post;

		// Only add for images
		if ( ! wp_attachment_is_image( $post->ID ) ) {
			return;
		}

		add_meta_box(
			'prorank_image_optimization',
			__( 'ProRank Image Optimization', 'prorank-seo' ),
			[ $this, 'render_optimization_metabox' ],
			'attachment',
			'side',
			'high'
		);
	}

	/**
	 * Render optimization metabox
	 *
	 * @param WP_Post $post Post object.
	 */
	public function render_optimization_metabox( WP_Post $post ): void {
		$attachment_id = $post->ID;

		// Get optimization data
		$optimized = get_post_meta( $attachment_id, '_prorank_optimized', true );
		$original_size = (int) get_post_meta( $attachment_id, '_prorank_original_size', true );
		$bytes_saved = (int) get_post_meta( $attachment_id, '_prorank_bytes_saved', true );
		$webp_generated = get_post_meta( $attachment_id, '_prorank_webp_generated', true );
		$avif_generated = get_post_meta( $attachment_id, '_prorank_avif_generated', true );
		$backup_path = get_post_meta( $attachment_id, '_prorank_backup_path', true );

		// Get current file size
		$file_path = get_attached_file( $attachment_id );
		$current_size = file_exists( $file_path ) ? filesize( $file_path ) : 0;

		// Nonce for AJAX
		wp_nonce_field( 'prorank_optimize_attachment', 'prorank_optimize_nonce' );
		?>
		<div id="prorank-attachment-optimization"
			 data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>"
			 class="prorank-attachment-optimization-metabox">

			<?php if ( $optimized === '1' ) : ?>
				<div class="prorank-opt-status prorank-opt-status-success">
					<span class="dashicons dashicons-yes-alt"></span>
					<?php esc_html_e( 'Optimized', 'prorank-seo' ); ?>
				</div>

				<table class="prorank-opt-details">
					<tr>
						<td><?php esc_html_e( 'JPEG Size:', 'prorank-seo' ); ?></td>
						<td><?php echo esc_html( size_format( $current_size ) ); ?></td>
					</tr>
					<?php if ( $webp_generated && $bytes_saved > 0 ) : ?>
					<tr>
						<td><?php esc_html_e( 'WebP Size:', 'prorank-seo' ); ?></td>
						<td>
							<strong style="color: #46b450;"><?php echo esc_html( size_format( $current_size - $bytes_saved ) ); ?></strong>
							<span style="color: #666; font-size: 11px;">
								(<?php echo esc_html( round( ( $bytes_saved / $original_size ) * 100, 1 ) ); ?>% <?php esc_html_e( 'smaller', 'prorank-seo' ); ?>)
							</span>
						</td>
					</tr>
					<?php endif; ?>
					<tr>
						<td><?php esc_html_e( 'Formats:', 'prorank-seo' ); ?></td>
						<td>
							<?php
							$formats = [];
							if ( $webp_generated ) {
								$formats[] = '<span class="prorank-format-badge prorank-format-webp">WebP</span>';
							}
							if ( $avif_generated ) {
								$formats[] = '<span class="prorank-format-badge prorank-format-avif">AVIF</span>';
							}
							if ( empty( $formats ) ) {
								echo '—';
							} else {
								echo wp_kses_post( implode( ' ', $formats ) );
							}
							?>
						</td>
					</tr>
				</table>
				<p style="margin: 10px 0 0; font-size: 11px; color: #666;">
					<?php esc_html_e( 'WebP is served automatically to compatible browsers.', 'prorank-seo' ); ?>
				</p>

				<?php if ( $backup_path && file_exists( $backup_path ) ) : ?>
					<div class="prorank-opt-actions" style="margin-top: 15px;">
						<button type="button" class="button button-secondary prorank-restore-btn" data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>">
							<span class="dashicons dashicons-backup" style="margin-top: 3px;"></span>
							<?php esc_html_e( 'Restore Original', 'prorank-seo' ); ?>
						</button>
					</div>
				<?php endif; ?>

				<div class="prorank-opt-actions" style="margin-top: 10px;">
					<button type="button" class="button button-secondary prorank-reoptimize-btn" data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>">
						<span class="dashicons dashicons-image-rotate" style="margin-top: 3px;"></span>
						<?php esc_html_e( 'Re-optimize', 'prorank-seo' ); ?>
					</button>
				</div>

			<?php else : ?>
				<div class="prorank-opt-status prorank-opt-status-pending">
					<span class="dashicons dashicons-clock"></span>
					<?php esc_html_e( 'Not Optimized', 'prorank-seo' ); ?>
				</div>

				<table class="prorank-opt-details">
					<tr>
						<td><?php esc_html_e( 'File Size:', 'prorank-seo' ); ?></td>
						<td><?php echo esc_html( size_format( $current_size ) ); ?></td>
					</tr>
				</table>

				<div class="prorank-opt-actions" style="margin-top: 15px;">
					<button type="button" class="button button-primary prorank-optimize-btn" data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>">
						<span class="dashicons dashicons-performance" style="margin-top: 3px;"></span>
						<?php esc_html_e( 'Optimize Now', 'prorank-seo' ); ?>
					</button>
				</div>

				<div class="prorank-opt-options" style="margin-top: 15px;">
					<p style="margin-bottom: 8px; font-weight: 600;"><?php esc_html_e( 'Generate specific formats:', 'prorank-seo' ); ?></p>
					<button type="button" class="button button-small prorank-generate-webp-btn" data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>">
						<?php esc_html_e( 'WebP Only', 'prorank-seo' ); ?>
					</button>
					<button type="button" class="button button-small prorank-generate-avif-btn" data-attachment-id="<?php echo esc_attr( $attachment_id ); ?>">
						<?php esc_html_e( 'AVIF Only', 'prorank-seo' ); ?>
					</button>
				</div>
			<?php endif; ?>

			<div class="prorank-opt-spinner" style="display: none; text-align: center; padding: 20px;">
				<span class="spinner is-active" style="float: none;"></span>
				<p class="prorank-opt-spinner-text"><?php esc_html_e( 'Processing...', 'prorank-seo' ); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Add optimization field to media modal
	 *
	 * @param array   $form_fields Form fields.
	 * @param WP_Post $post        Post object.
	 * @return array Modified form fields.
	 */
	public function add_optimization_fields( array $form_fields, WP_Post $post ): array {
		// Only add for images
		if ( ! wp_attachment_is_image( $post->ID ) ) {
			return $form_fields;
		}

		$optimized = get_post_meta( $post->ID, '_prorank_optimized', true );
		$bytes_saved = (int) get_post_meta( $post->ID, '_prorank_bytes_saved', true );
		$original_size = (int) get_post_meta( $post->ID, '_prorank_original_size', true );
		$webp_generated = get_post_meta( $post->ID, '_prorank_webp_generated', true );
		$avif_generated = get_post_meta( $post->ID, '_prorank_avif_generated', true );

		$html = '<div class="prorank-attachment-optimization" data-attachment-id="' . esc_attr( $post->ID ) . '">';

		if ( $optimized === '1' ) {
			$percent = $original_size > 0 ? round( ( $bytes_saved / $original_size ) * 100, 1 ) : 0;

			$html .= '<span class="prorank-status-optimized">';
			$html .= '<span class="dashicons dashicons-yes-alt" style="color: #46b450;"></span> ';
			$html .= esc_html__( 'Optimized', 'prorank-seo' );
			$html .= '</span>';

			$html .= ' <span class="prorank-savings" style="color: #666;">(' . esc_html( size_format( $bytes_saved ) ) . ' / ' . esc_html( $percent ) . '% ' . esc_html__( 'saved', 'prorank-seo' ) . ')</span>';

			// Format badges
			$formats = [];
			if ( $webp_generated ) {
				$formats[] = '<span style="background:#4caf50;color:#fff;padding:2px 6px;border-radius:3px;font-size:10px;margin-left:4px;">WebP</span>';
			}
			if ( $avif_generated ) {
				$formats[] = '<span style="background:#2196f3;color:#fff;padding:2px 6px;border-radius:3px;font-size:10px;margin-left:4px;">AVIF</span>';
			}
			if ( ! empty( $formats ) ) {
				$html .= '<br>' . implode( '', $formats );
			}
		} else {
			$html .= '<button type="button" class="button prorank-optimize-modal-btn" data-attachment-id="' . esc_attr( $post->ID ) . '">';
			$html .= '<span class="dashicons dashicons-performance" style="margin-top: 3px;"></span> ';
			$html .= esc_html__( 'Optimize Now', 'prorank-seo' );
			$html .= '</button>';
			$html .= '<span class="prorank-modal-spinner spinner" style="display:none;float:none;margin-left:10px;"></span>';
			$html .= '<span class="prorank-modal-status" style="margin-left:10px;"></span>';
		}

		$html .= '</div>';

		$form_fields['prorank_optimization'] = [
			'label' => __( 'Optimization', 'prorank-seo' ),
			'input' => 'html',
			'html'  => $html,
		];

		return $form_fields;
	}

	/**
	 * Enqueue scripts for media library optimization
	 *
	 * @param string $hook_suffix Current admin page.
	 */
	public function enqueue_scripts( string $hook_suffix ): void {
		$media_pages = [
			'upload.php',
			'post.php',
			'post-new.php',
			'media-upload.php',
		];

		global $post;
		$is_attachment_page = ( $post && $post->post_type === 'attachment' );

		if ( ! in_array( $hook_suffix, $media_pages, true ) && ! $is_attachment_page ) {
			return;
		}

		// Enqueue CSS
		wp_enqueue_style(
			'prorank-media-library-optimization',
			\PRORANK_PLUGIN_URL . 'assets/css/media-library-optimization.css',
			[],
			\PRORANK_VERSION
		);

		// Enqueue JS
		wp_enqueue_script(
			'prorank-media-library-optimization',
			\PRORANK_PLUGIN_URL . 'assets/js/media-library-optimization.js',
			[ 'jquery' ],
			\PRORANK_VERSION,
			true
		);

		// Localize script
		wp_localize_script( 'prorank-media-library-optimization', 'prorankMediaOptimization', [
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'prorank_media_optimization' ),
			'i18n'    => [
				'optimizing'    => __( 'Optimizing...', 'prorank-seo' ),
				'restoring'     => __( 'Restoring...', 'prorank-seo' ),
				'generating'    => __( 'Generating...', 'prorank-seo' ),
				'success'       => __( 'Success!', 'prorank-seo' ),
				'error'         => __( 'Error', 'prorank-seo' ),
				'optimized'     => __( 'Optimized', 'prorank-seo' ),
				'pending'       => __( 'Pending', 'prorank-seo' ),
				'saved'         => __( 'saved', 'prorank-seo' ),
				'confirmRestore' => __( 'Are you sure you want to restore the original image? This will remove all optimizations.', 'prorank-seo' ),
			],
		] );
	}

	/**
	 * AJAX handler for single image optimization
	 */
	public function ajax_optimize_single_image(): void {
		check_ajax_referer( 'prorank_media_optimization', 'nonce' );

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( __( 'Insufficient permissions', 'prorank-seo' ) );
		}

			$attachment_id = intval( prorank_get_post_var( 'attachment_id' ) );
			$action_type = prorank_get_post_var( 'action_type' );
			if ( $action_type === '' ) {
				$action_type = 'optimize';
			}

		if ( ! $attachment_id ) {
			wp_send_json_error( __( 'Invalid attachment ID', 'prorank-seo' ) );
		}

		$result = $this->process_single_image( $attachment_id, $action_type );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		// Get updated stats
		$stats = $this->get_optimization_stats( $attachment_id );

		wp_send_json_success( [
			'message' => __( 'Image optimized successfully', 'prorank-seo' ),
			'stats'   => $stats,
		] );
	}

	/**
	 * AJAX handler for restoring original image
	 */
	public function ajax_restore_single_image(): void {
		check_ajax_referer( 'prorank_media_optimization', 'nonce' );

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( __( 'Insufficient permissions', 'prorank-seo' ) );
		}

			$attachment_id = intval( prorank_get_post_var( 'attachment_id' ) );

		if ( ! $attachment_id ) {
			wp_send_json_error( __( 'Invalid attachment ID', 'prorank-seo' ) );
		}

		$result = $this->process_single_image( $attachment_id, 'restore' );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		wp_send_json_success( [
			'message' => __( 'Original image restored successfully', 'prorank-seo' ),
		] );
	}

	/**
	 * AJAX handler to get optimization status
	 */
	public function ajax_get_optimization_status(): void {
		check_ajax_referer( 'prorank_media_optimization', 'nonce' );

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( __( 'Insufficient permissions', 'prorank-seo' ) );
		}

			$attachment_id = intval( prorank_get_post_var( 'attachment_id' ) );

		if ( ! $attachment_id ) {
			wp_send_json_error( __( 'Invalid attachment ID', 'prorank-seo' ) );
		}

		$stats = $this->get_optimization_stats( $attachment_id );

		wp_send_json_success( $stats );
	}

	/**
	 * Get optimization stats for an attachment
	 *
	 * @param int $attachment_id Attachment ID.
	 * @return array Stats array.
	 */
	private function get_optimization_stats( int $attachment_id ): array {
		$optimized = get_post_meta( $attachment_id, '_prorank_optimized', true );
		$original_size = (int) get_post_meta( $attachment_id, '_prorank_original_size', true );
		$bytes_saved = (int) get_post_meta( $attachment_id, '_prorank_bytes_saved', true );
		$webp_generated = get_post_meta( $attachment_id, '_prorank_webp_generated', true );
		$avif_generated = get_post_meta( $attachment_id, '_prorank_avif_generated', true );
		$backup_path = get_post_meta( $attachment_id, '_prorank_backup_path', true );

		$file_path = get_attached_file( $attachment_id );
		$has_current_file = is_string( $file_path ) && $file_path !== '' && file_exists( $file_path );
		$current_size = $has_current_file ? (int) filesize( $file_path ) : 0;
		$has_backup = is_string( $backup_path ) && $backup_path !== '' && file_exists( $backup_path );

		$percent = ( $original_size > 0 ) ? round( ( $bytes_saved / $original_size ) * 100, 1 ) : 0;

		return [
			'optimized'       => $optimized === '1',
			'original_size'   => $original_size,
			'current_size'    => $current_size,
			'bytes_saved'     => $bytes_saved,
			'percent_saved'   => $percent,
			'webp_generated'  => (bool) $webp_generated,
			'avif_generated'  => (bool) $avif_generated,
			'has_backup'      => $has_backup,
			'original_size_formatted' => size_format( $original_size ),
			'current_size_formatted'  => size_format( $current_size ),
			'bytes_saved_formatted'   => size_format( $bytes_saved ),
		];
	}

	/**
	 * Get image optimization module
	 *
	 * @return \ProRank\SEO\Modules\Performance\ImageOptimizationModule|null
	 */
	private function get_image_optimization_module() {
		$module_manager = $this->plugin->modules();
		if ( ! $module_manager ) {
			return null;
		}

		$module = $module_manager->get_module( 'image_optimization' );
		if ( $module && $module instanceof \ProRank\SEO\Modules\Performance\ImageOptimizationModule ) {
			return $module;
		}

		return null;
	}
}

// Register Action Scheduler hook for async processing
add_action( 'prorank_optimize_single_image', function( $attachment_id, $action_type = 'optimize' ) {
	$plugin = \ProRank\SEO\Plugin::get_instance();
	if ( ! $plugin ) {
		return;
	}

	$media_optimization = new MediaLibraryOptimization( $plugin );
	$media_optimization->process_single_image( $attachment_id, $action_type );
}, 10, 2 );
