<?php
/**
 * BaseCloud Boost — Media Settings
 *
 * @package BaseCloud\Boost
 */

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

$options = (array) get_option( BCBOOST_OPTIONS_KEY, [] );

$webp_ok        = \BaseCloud\Boost\Optimizer\Image_Compressor::webp_supported();
$avif_ok        = \BaseCloud\Boost\Optimizer\Image_Compressor::avif_supported();
$compress_stats = ( new \BaseCloud\Boost\Optimizer\Image_Compressor() )->get_stats();

// When this server cannot create AVIF files the toggle below renders disabled.
// A disabled checkbox never submits, so we must NOT list serve_avif as one of
// this tab's checkboxes — otherwise saving the form would silently force the
// stored value to false (existing .avif files from other tools are still served).
$tab_checkboxes = 'lazy_load_images,lazy_load_iframes,lazy_load_videos,auto_sizes,preload_lcp_image,auto_preconnect,serve_webp,optimize_images,compress_images,video_facade,serve_webm,self_host_fonts,google_fonts_optimize,google_fonts_async';
if ( $avif_ok ) {
	$tab_checkboxes .= ',serve_avif';
}
?>
<div class="bcboost-wrap">
	<?php include __DIR__ . '/partials/header.php'; ?>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'BCBOOST_save_settings' ); ?>
		<input type="hidden" name="action" value="BCBOOST_save_settings">
		<input type="hidden" name="BCBOOST_tab_checkboxes" value="<?php echo esc_attr( $tab_checkboxes ); ?>">

		<div class="bcboost-card bcboost-card--accent-blue">
			<h3><span class="bcboost-section-icon">🖼️</span> <?php esc_html_e( 'Lazy Loading', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Lazy Load Images', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Defer below-fold images with the browser\'s reliable native loading. The first image (LCP) always loads eagerly with high fetchpriority. Images are never hidden, so they always appear.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="lazy_load_images" value="1" <?php checked( ! empty( $options['lazy_load_images'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Lazy Load iFrames', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Defer loading of embedded iframes (YouTube, maps, etc.) until the user scrolls to them.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="lazy_load_iframes" value="1" <?php checked( ! empty( $options['lazy_load_iframes'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Lazy Load Videos', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Set preload="none" on HTML5 video elements so browsers do not buffer video data until the user interacts.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="lazy_load_videos" value="1" <?php checked( ! empty( $options['lazy_load_videos'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Right-Size Lazy Images (Mobile Bytes Saver)', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Let the browser download the image size that matches how large the image actually renders — instead of a viewport-width guess — for every lazy-loaded responsive image (adds sizes="auto"). On phones this typically cuts image downloads substantially and fixes the PageSpeed "Properly size images" flag. The same mechanism WordPress 6.7 introduced, applied by Boost on older WordPress and builder markup too. Older browsers simply ignore it.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="auto_sizes" value="1" <?php checked( $options['auto_sizes'] ?? true ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-blue">
			<h3><span class="bcboost-section-icon">🎯</span> <?php esc_html_e( 'LCP / Above-the-Fold Images', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Preload the LCP Hero Image', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Auto-detect the page\'s hero image — the first content image, an inline background-image, a slider\'s first slide, or a section background declared in the page\'s own inline/combined CSS — keep it out of lazy-loading and preload it with fetchpriority=high so it starts downloading immediately. The single biggest Largest Contentful Paint (LCP) lever. When detection is not confident (e.g. the hero background lives in an external stylesheet), Boost deliberately preloads nothing: add a custom field named bcboost_lcp_image containing the exact image URL to that page to force the right hero.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="preload_lcp_image" value="1" <?php checked( ! empty( $options['preload_lcp_image'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Auto-Preconnect Hero & CDN Origin', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Open the network connection to your CDN and to the origin serving the hero image early — before the browser asks for them — so the Largest Contentful Paint (LCP) image starts downloading a round-trip sooner. A safe, standards-based resource hint (https, cross-origin only). Recommended.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="auto_preconnect" value="1" <?php checked( $options['auto_preconnect'] ?? true ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lazy_skip_count"><?php esc_html_e( 'Above-the-Fold Images Kept Eager', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'How many of the first images on the page load immediately instead of being lazy-loaded — the hero plus the next few. On phones the first screen usually holds 2–3 images, and lazy-loading them delays the Largest Contentful Paint. 2 is the safe default; raise it only if your hero sits below other images.', 'basecloud-boost' ); ?></span>
				<input type="number" id="lazy_skip_count" name="lazy_skip_count" class="bcboost-input" min="0" max="10" step="1" value="<?php echo (int) ( $options['lazy_skip_count'] ?? 2 ); ?>" style="margin-top:10px;max-width:120px;">
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lazy_exclude"><?php esc_html_e( 'Never Lazy-Load These Images', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Above-the-fold images that must load immediately — e.g. your hero/banner. One URL fragment or CSS class per line. Boost already keeps any image the theme marks high-priority eager; add anything it misses here to protect your Largest Contentful Paint (LCP).', 'basecloud-boost' ); ?></span>
				<textarea id="lazy_exclude" name="lazy_exclude" class="bcboost-textarea bcboost-input--wide" rows="3" style="margin-top:10px;font-family:monospace;" placeholder="hero-banner.jpg&#10;wp-image-955&#10;/uploads/2025/08/Office-Worker"><?php echo esc_textarea( $options['lazy_exclude'] ?? '' ); ?></textarea>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-green">
			<h3><span class="bcboost-section-icon">🌐</span> <?php esc_html_e( 'Modern Image Formats', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Serve WebP Images', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Automatically serve .webp versions of images when they exist alongside the originals. WebP images are typically 25–35% smaller, supported by every modern browser, and rock-solid — this is the Boost standard for modern image delivery.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="serve_webp" value="1" <?php checked( ! empty( $options['serve_webp'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Serve AVIF Images (advanced, off by default)', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc">
						<?php if ( $avif_ok ) : ?>
							<?php esc_html_e( 'AVIF can be 20–50% smaller than WebP, but it has produced broken or blank images on servers whose AVIF encoder emits files it cannot verify — so Boost now ships WebP-only by default. Enable this only if your host has a proven AVIF pipeline; every AVIF Boost creates is decode-validated before it is ever served, and anything unverifiable falls back to WebP or the original.', 'basecloud-boost' ); ?>
						<?php else : ?>
							<?php echo esc_html( \BaseCloud\Boost\Optimizer\Image_Compressor::unsupported_reason( 'avif' ) ); ?>
							<?php esc_html_e( 'WebP serving above is unaffected.', 'basecloud-boost' ); ?>
						<?php endif; ?>
					</span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="serve_avif" value="1" <?php checked( ! empty( $options['serve_avif'] ) ); ?> <?php disabled( ! $avif_ok ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-green">
			<h3><span class="bcboost-section-icon">🗜️</span> <?php esc_html_e( 'Image Compression', 'basecloud-boost' ); ?></h3>

			<p class="bcboost-field-desc" style="margin-bottom:16px;">
				<?php
				if ( $avif_ok ) {
					esc_html_e( 'BaseCloud Boost creates high-quality, much smaller WebP and AVIF copies of every JPEG and PNG. Your original files are never changed or deleted — supported browsers are simply served the lighter copy, so quality stays the same while pages load far faster.', 'basecloud-boost' );
				} else {
					esc_html_e( 'BaseCloud Boost creates a high-quality, much smaller WebP copy of every JPEG and PNG. Your original files are never changed or deleted — supported browsers are simply served the lighter WebP, so quality stays the same while pages load far faster.', 'basecloud-boost' );
				}
				?>
			</p>

			<?php if ( ! $webp_ok ) : ?>
				<div class="bcboost-cdn-description" style="border-color:rgba(248,113,113,.4)">
					<p>
						<?php echo esc_html( \BaseCloud\Boost\Optimizer\Image_Compressor::unsupported_reason( 'webp' ) ); ?>
						<?php esc_html_e( 'Compression is unavailable until then — nothing else on this page is affected.', 'basecloud-boost' ); ?>
					</p>
				</div>
			<?php else : ?>
				<p class="bcboost-field-desc" style="margin-bottom:16px;">
					<?php
					printf(
						/* translators: 1: engine used for WebP (GD/Imagick), 2: engine used for AVIF (or "not available") */
						esc_html__( 'Conversion engines — WebP: %1$s · AVIF: %2$s.', 'basecloud-boost' ),
						esc_html( \BaseCloud\Boost\Optimizer\Image_Compressor::engine_label( 'webp' ) ),
						esc_html( \BaseCloud\Boost\Optimizer\Image_Compressor::engine_label( 'avif' ) )
					);
					?>
				</p>
			<?php endif; ?>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Compress New Uploads', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Automatically generate a WebP copy whenever you upload an image. Runs in the background and never blocks or alters the original upload.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="compress_images" value="1" <?php checked( ! empty( $options['compress_images'] ) ); ?> <?php disabled( ! $webp_ok ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="compression_quality"><?php esc_html_e( 'Compression Quality', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'WebP quality from 40 to 100. 82 is the recommended sweet spot — visually identical to the original at roughly a third of the file size. Higher keeps more detail; lower saves more space.', 'basecloud-boost' ); ?></span>
				<input type="number" id="compression_quality" name="compression_quality" class="bcboost-input" min="40" max="100" step="1" value="<?php echo (int) ( $options['compression_quality'] ?? 82 ); ?>" style="margin-top:10px;max-width:120px;">
			</div>

			<div class="bcboost-field" style="margin-top:18px;border-top:1px solid rgba(255,255,255,.07);padding-top:18px;">
				<span class="bcboost-field-label"><?php esc_html_e( 'Bulk Compress Existing Library', 'basecloud-boost' ); ?></span>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Generate WebP copies for every image already in your Media Library. Keep this tab open while it runs — progress is shown below. Safe to stop and resume at any time.', 'basecloud-boost' ); ?></span>

				<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px;">
					<button type="button" id="bcboost-compress-start" class="bcboost-btn bcboost-btn--primary" <?php disabled( ! $webp_ok ); ?><?php echo ! $webp_ok ? ' title="' . esc_attr( \BaseCloud\Boost\Optimizer\Image_Compressor::unsupported_reason( 'webp' ) ) . '"' : ''; ?>>
						<span class="dashicons dashicons-images-alt2"></span>
						<?php esc_html_e( 'Start Bulk Compression', 'basecloud-boost' ); ?>
					</button>
					<button type="button" id="bcboost-compress-stop" class="bcboost-btn bcboost-btn--glass" style="display:none;">
						<?php esc_html_e( 'Stop', 'basecloud-boost' ); ?>
					</button>
				</div>

				<?php if ( ! $webp_ok ) : ?>
					<p class="bcboost-field-desc" style="margin-top:10px;color:#f87171;">
						<?php echo esc_html( \BaseCloud\Boost\Optimizer\Image_Compressor::unsupported_reason( 'webp' ) ); ?>
					</p>
				<?php endif; ?>

				<div id="bcboost-compress-progress-wrap" style="display:none;margin-top:16px;">
					<div class="bcboost-progress" style="background:rgba(255,255,255,.08);border-radius:999px;height:10px;overflow:hidden;">
						<div id="bcboost-compress-progress-fill" style="height:100%;width:0%;background:linear-gradient(90deg,#4ade80,#22c55e);transition:width .4s ease;"></div>
					</div>
					<p id="bcboost-compress-progress-label" class="bcboost-field-desc" style="margin-top:8px;">0%</p>
				</div>

				<p id="bcboost-compress-feedback" class="bcboost-feedback" style="display:none;"></p>

				<div id="bcboost-compress-failures" style="display:none;margin-top:10px;"></div>

				<p class="bcboost-field-desc" style="margin-top:12px;" id="bcboost-compress-stats">
					<?php
					printf(
						/* translators: 1: number of images, 2: human-readable size saved */
						esc_html__( 'Lifetime: %1$s optimized image copies created, %2$s saved.', 'basecloud-boost' ),
						'<strong>' . esc_html( number_format_i18n( $compress_stats['images'] ) ) . '</strong>',
						'<strong>' . esc_html( size_format( $compress_stats['bytes_saved'] ) ?: '0 B' ) . '</strong>'
					);
					?>
				</p>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-purple">
			<h3><span class="bcboost-section-icon">▶️</span> <?php esc_html_e( 'Video Facade', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Enable Video Facade', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Replace YouTube and Vimeo iframes with lightweight click-to-play thumbnails. Saves 500+ KB of JavaScript per embedded video until the user actually clicks to play.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="video_facade" value="1" <?php checked( ! empty( $options['video_facade'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Serve WebM Video When Available', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'When a .webm copy of a self-hosted .mp4 exists in your Media Library folder, offer it first — supporting browsers stream the much smaller WebM while everyone else keeps the MP4. Boost never converts video itself (server conversion would be slow and lose quality): create the WebM copy once with any converter and upload it next to the MP4. Tip: for hero background videos, always set a poster image — Boost detects it and preloads it as the page\'s hero, which is the real LCP win for video headers.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="serve_webm" value="1" <?php checked( $options['serve_webm'] ?? true ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>
		</div>

		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">🔤</span> <?php esc_html_e( 'Google Fonts', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Self-Host Google Fonts', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Download Google Fonts (CSS + woff2) to this server once and serve them from your own domain, inlined into the page. Removes the render-blocking request to fonts.googleapis.com and the extra DNS/TLS to fonts.gstatic.com — a common PageSpeed flag. Recommended.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="self_host_fonts" value="1" <?php checked( ! empty( $options['self_host_fonts'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Optimize Google Fonts', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Automatically append display=swap to Google Fonts URLs to prevent invisible text during font loading (eliminates render-blocking FOIT).', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="google_fonts_optimize" value="1" <?php checked( ! empty( $options['google_fonts_optimize'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Load Fonts Asynchronously', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc">
						<?php esc_html_e( 'Load Google Fonts via rel="preload" to eliminate render-blocking. Fonts are swapped in after the page paints.', 'basecloud-boost' ); ?>
						<span class="bcboost-field-warning">⚠️ <?php esc_html_e( 'May cause a brief flash of unstyled text (FOUT) on slow connections.', 'basecloud-boost' ); ?></span>
					</span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="google_fonts_async" value="1" <?php checked( ! empty( $options['google_fonts_async'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>
		</div>

		<div class="bcboost-form-footer">
			<button type="submit" class="bcboost-btn bcboost-btn--primary">
				<span class="dashicons dashicons-saved"></span>
				<?php esc_html_e( 'Save Settings', 'basecloud-boost' ); ?>
			</button>
		</div>
	</form>
</div>
