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

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

use BaseCloud\Boost\Core\Cache_Preloader;

$preloader = new Cache_Preloader();
$progress  = $preloader->get_preload_progress();
$options   = (array) get_option( BCBOOST_OPTIONS_KEY, [] );
$status    = $progress['status'] ?? 'idle';
?>
<div class="bcboost-wrap">
	<?php include __DIR__ . '/partials/header.php'; ?>

	<div class="bcboost-card bcboost-card--accent-green">
		<h3><span class="bcboost-section-icon">🔄</span> <?php esc_html_e( 'Preloader Status', 'basecloud-boost' ); ?></h3>

		<div class="bcboost-preloader-status bcboost-preloader-status--<?php echo esc_attr( $status ); ?>">
			<span class="bcboost-status-dot"></span>
			<?php
			switch ( $status ) {
				case 'starting':
				case 'running':
					esc_html_e( 'Preloader Running', 'basecloud-boost' );
					break;
				case 'completed':
					esc_html_e( 'Preloader Completed', 'basecloud-boost' );
					break;
				case 'stopped':
					esc_html_e( 'Preloader Stopped', 'basecloud-boost' );
					break;
				case 'skipped':
					esc_html_e( 'Preloader Skipped — Boost page cache is inactive on this host', 'basecloud-boost' );
					break;
				default:
					esc_html_e( 'Preloader Idle', 'basecloud-boost' );
			}
			?>
		</div>

		<?php if ( $status !== 'idle' && $status !== 'skipped' ) : ?>
			<div class="bcboost-preload-meta" style="margin-top:12px;display:flex;flex-wrap:wrap;gap:8px 20px;font-size:12px;opacity:.85;">
				<span>
					<strong><?php esc_html_e( 'Mode:', 'basecloud-boost' ); ?></strong>
					<?php
					if ( ( $progress['mode'] ?? '' ) === 'chained' ) {
						esc_html_e( 'Chained loopback (warms without visitor traffic)', 'basecloud-boost' );
					} elseif ( ( $progress['mode'] ?? '' ) === 'cron' ) {
						esc_html_e( 'WP-Cron fallback', 'basecloud-boost' );
						if ( ( $progress['fallback_reason'] ?? '' ) === 'loopback_blocked' ) {
							echo ' ' . esc_html__( '(host blocks loopback requests)', 'basecloud-boost' );
						} elseif ( ( $progress['fallback_reason'] ?? '' ) === 'chain_stalled' ) {
							echo ' ' . esc_html__( '(loopback chain stalled)', 'basecloud-boost' );
						}
					} else {
						echo esc_html( '—' );
					}
					?>
				</span>
				<span>
					<strong><?php esc_html_e( 'Warmed:', 'basecloud-boost' ); ?></strong>
					<?php echo (int) ( $progress['completed'] ?? 0 ); ?>
				</span>
				<span>
					<strong><?php esc_html_e( 'In queue:', 'basecloud-boost' ); ?></strong>
					<?php echo (int) ( $progress['remaining'] ?? 0 ); ?>
				</span>
				<?php if ( ! empty( $progress['started_at'] ) ) : ?>
					<span>
						<strong><?php esc_html_e( 'Last run:', 'basecloud-boost' ); ?></strong>
						<?php
						printf(
							/* translators: %s: human time diff, e.g. "5 mins" */
							esc_html__( 'started %s ago', 'basecloud-boost' ),
							esc_html( human_time_diff( (int) $progress['started_at'] ) )
						);
						if ( ! empty( $progress['finished_at'] ) ) {
							printf(
								/* translators: %s: human time diff, e.g. "2 mins" */
								', ' . esc_html__( 'finished %s ago', 'basecloud-boost' ),
								esc_html( human_time_diff( (int) $progress['finished_at'] ) )
							);
						}
						?>
					</span>
				<?php endif; ?>
			</div>
		<?php endif; ?>

		<?php if ( in_array( $status, [ 'starting', 'running', 'completed' ], true ) ) : ?>
			<div style="margin-top:18px;">
				<div class="bcboost-progress-bar">
					<div class="bcboost-progress-fill" id="bcboost-progress-fill" style="width: <?php echo (int) $progress['percentage']; ?>%"></div>
				</div>
				<div class="bcboost-progress-label" id="bcboost-progress-label">
					<?php printf(
						esc_html__( '%1$d of %2$d pages (%3$d%%)', 'basecloud-boost' ),
						(int) $progress['completed'],
						(int) $progress['total'],
						(int) $progress['percentage']
					); ?>
				</div>
				<?php if ( ! empty( $progress['current_url'] ) ) : ?>
					<div class="bcboost-current-url"><?php echo esc_html( $progress['current_url'] ); ?></div>
				<?php endif; ?>
			</div>
		<?php endif; ?>

		<div class="bcboost-actions-row" style="margin-top:18px;">
			<button class="bcboost-btn bcboost-btn--primary" id="bcboost-start-preloader">
				<span class="dashicons dashicons-controls-play"></span>
				🚀 <?php esc_html_e( 'Launch Preloader', 'basecloud-boost' ); ?>
			</button>
			<button class="bcboost-btn bcboost-btn--danger" id="bcboost-stop-preloader">
				<span class="dashicons dashicons-controls-pause"></span>
				<?php esc_html_e( 'Stop', 'basecloud-boost' ); ?>
			</button>
		</div>
		<div id="bcboost-preloader-feedback" class="bcboost-feedback" style="display:none;margin-top:14px;"></div>
	</div>

	<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="preload_on_purge,preload_links">

		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">⚙️</span> <?php esc_html_e( 'Preload Configuration', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Auto-Preload After Cache Clear', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Automatically start the preloader whenever the cache is cleared.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="preload_on_purge" value="1" <?php checked( ! empty( $options['preload_on_purge'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<p class="bcboost-field-hint" style="margin:4px 0 12px;font-size:12px;opacity:.8;">
				<?php esc_html_e( 'The preloader chains its own background requests, so it re-warms the whole site in minutes without visitor traffic. On quiet/low-traffic sites we still recommend a real system cron — add define( \'DISABLE_WP_CRON\', true ); to wp-config.php and a server cron hitting wp-cron.php every minute — so the very first tick after a purge (and the fallback mode on hosts that block loopback requests) never has to wait for a visitor.', 'basecloud-boost' ); ?>
			</p>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Prefetch Links on Hover', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Speculatively prefetch internal page links when the user hovers over them (65ms delay). Makes navigation feel instant.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="preload_links" value="1" <?php checked( ! empty( $options['preload_links'] ) ); ?>>
					<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( 'Resource Hints', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="prefetch_dns"><?php esc_html_e( 'DNS Prefetch Origins', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Third-party origins to prefetch DNS for. One per line. e.g. //fonts.googleapis.com', 'basecloud-boost' ); ?></span>
				<textarea id="prefetch_dns" name="prefetch_dns" class="bcboost-textarea bcboost-input--wide" style="margin-top:10px;"><?php echo esc_textarea( $options['prefetch_dns'] ?? '' ); ?></textarea>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="preload_fonts"><?php esc_html_e( 'Preload Fonts', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Font file URLs to preload (woff2/woff/ttf). One per line. e.g. /wp-content/themes/mytheme/fonts/myfont.woff2', 'basecloud-boost' ); ?></span>
				<textarea id="preload_fonts" name="preload_fonts" class="bcboost-textarea bcboost-input--wide" style="margin-top:10px;"><?php echo esc_textarea( $options['preload_fonts'] ?? '' ); ?></textarea>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="preload_key_requests"><?php esc_html_e( 'Preload Key Requests', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Critical asset URLs to preload (CSS, JS, images). One per line. e.g. /wp-content/themes/mytheme/style.css', 'basecloud-boost' ); ?></span>
				<textarea id="preload_key_requests" name="preload_key_requests" class="bcboost-textarea bcboost-input--wide" style="margin-top:10px;"><?php echo esc_textarea( $options['preload_key_requests'] ?? '' ); ?></textarea>
			</div>
		</div>

		<div class="bcboost-card bcboost-card--accent-purple">
			<h3><span class="bcboost-section-icon">⚡</span> <?php esc_html_e( 'Speculation Rules (Instant Navigation)', 'basecloud-boost' ); ?></h3>

			<p class="bcboost-field-desc" style="margin-bottom:16px;"><?php esc_html_e( 'The Speculation Rules API (Chrome 109+) allows the browser to prefetch or prerender internal pages before the user navigates. Prerending makes page transitions feel instant — the destination page is fully loaded in a background tab.', 'basecloud-boost' ); ?></p>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="speculation_rules"><?php esc_html_e( 'Mode', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Prefetch fetches the document; Prerender fully renders it in the background. Prerender gives instant navigation but uses more memory.', 'basecloud-boost' ); ?></span>
				<select id="speculation_rules" name="speculation_rules" class="bcboost-select" style="margin-top:10px;">
					<option value="off"      <?php selected( ( $options['speculation_rules'] ?? 'prefetch' ), 'off' ); ?>><?php esc_html_e( 'Off', 'basecloud-boost' ); ?></option>
					<option value="prefetch" <?php selected( ( $options['speculation_rules'] ?? 'prefetch' ), 'prefetch' ); ?>><?php esc_html_e( 'Prefetch', 'basecloud-boost' ); ?></option>
					<option value="prerender"<?php selected( ( $options['speculation_rules'] ?? 'prefetch' ), 'prerender' ); ?>><?php esc_html_e( 'Prerender (Instant Navigation)', 'basecloud-boost' ); ?></option>
				</select>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="speculation_eagerness"><?php esc_html_e( 'Eagerness', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Conservative: triggers on mousedown. Moderate: triggers on hover (200ms). Eager: triggers immediately on visibility. Moderate is the recommended balance for most sites.', 'basecloud-boost' ); ?></span>
				<select id="speculation_eagerness" name="speculation_eagerness" class="bcboost-select" style="margin-top:10px;">
					<option value="conservative" <?php selected( ( $options['speculation_eagerness'] ?? 'moderate' ), 'conservative' ); ?>><?php esc_html_e( 'Conservative (mousedown)', 'basecloud-boost' ); ?></option>
					<option value="moderate"     <?php selected( ( $options['speculation_eagerness'] ?? 'moderate' ), 'moderate' ); ?>><?php esc_html_e( 'Moderate (hover)', 'basecloud-boost' ); ?></option>
					<option value="eager"        <?php selected( ( $options['speculation_eagerness'] ?? 'moderate' ), 'eager' ); ?>><?php esc_html_e( 'Eager (immediate)', 'basecloud-boost' ); ?></option>
				</select>
			</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>
