<?php
/**
 * Speed Test Tab Template
 *
 * @package SpeedInChina
 */

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

$speeinch_current_tab   = '';
$speeinch_can_use_cloud = function_exists( 'speeinch_can_collect_data' ) && speeinch_can_collect_data();
$speeinch_is_connecting = function_exists( 'speeinch_is_connecting' ) && speeinch_is_connecting();
$speeinch_admin_email   = get_bloginfo( 'admin_email' );
?>
<div class="wrap speeinch-wrap">
	<h1><?php esc_html_e( 'Speed in China', 'speed-in-china' ); ?></h1>

	<?php require_once SPEEINCH_PLUGIN_PATH . 'admin/templates/nav-tabs.php'; ?>

	<?php if ( $speeinch_is_connecting ) : ?>
		<?php /* Pending email-confirmation state. Shows AFTER user clicks Allow & Continue but BEFORE they click the email link. R3 still applies — outbound calls remain gated by speeinch_can_collect_data(). */ ?>
		<div class="speeinch_container speeinch-empty-state speeinch-empty-state--pending">
			<h2><?php esc_html_e( '📧 Almost there — check your inbox', 'speed-in-china' ); ?></h2>
			<p class="speeinch-prose-narrow">
				<?php
				printf(
					/* translators: %s: admin email address */
					esc_html__( 'We sent a confirmation email to %s. Click the link in that email to finish connecting and unlock China-side speed tests.', 'speed-in-china' ),
					'<strong>' . esc_html( $speeinch_admin_email ) . '</strong>'
				);
				?>
			</p>
			<p class="description speeinch-prose-narrow">
				<?php esc_html_e( 'Local features (Google Fonts localization and Resource Analysis) are already active and do not require email confirmation.', 'speed-in-china' ); ?>
			</p>
			<p>
				<a class="button" href="<?php echo esc_url( function_exists( 'speeinch_cancel_pending_url' ) ? speeinch_cancel_pending_url() : admin_url( 'plugins.php' ) ); ?>">
					<?php esc_html_e( 'Cancel and use anonymous mode', 'speed-in-china' ); ?>
				</a>
			</p>
		</div>
	<?php elseif ( ! $speeinch_can_use_cloud ) : ?>
		<?php /* Anonymous mode: show contextual Connect CTA per WP.org Guideline #11. */ ?>
		<div class="speeinch_container speeinch-empty-state speeinch-empty-state--cloud">
			<h2><?php esc_html_e( '🌐 Connect to run China-side speed tests', 'speed-in-china' ); ?></h2>
			<p class="speeinch-prose-narrow">
				<?php esc_html_e( 'Tests run from a Globalping probe in mainland China to give you accurate, China-real-network performance data. Connecting shares your site URL and minimal technical data with us and with Freemius (for licensing).', 'speed-in-china' ); ?>
			</p>
			<p>
				<a class="button button-primary button-hero" href="<?php echo esc_url( function_exists( 'speeinch_reconnect_url' ) ? speeinch_reconnect_url() : admin_url( 'plugins.php' ) ); ?>">
					<?php esc_html_e( 'Connect', 'speed-in-china' ); ?>
				</a>
			</p>
			<p class="description speeinch-prose-narrow">
				<?php
				printf(
					/* translators: %s: privacy policy URL */
					esc_html__( 'Read our %s before connecting. Google Fonts localization and Resource Analysis work without connecting.', 'speed-in-china' ),
					'<a href="https://speedinchinaplugin.com/terms/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Privacy Policy & Terms', 'speed-in-china' ) . '</a>'
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<?php
	$speeinch_manual_api_run = get_option( 'speeinch_manual_api_run' );
	// Gate on SPEEINCH_DEBUG (NOT WP_DEBUG) so this matches the AJAX
	// handler's bypass logic in admin/class-admin-controller.php. Otherwise
	// production sites with WP_DEBUG=true (common on staging) would render
	// the button enabled while the server still enforces the 30-day cooldown.
	$speeinch_bypass_cooldown = defined( 'SPEEINCH_DEBUG' ) && SPEEINCH_DEBUG;
	$speeinch_is_on_cooldown  = ! $speeinch_bypass_cooldown && $speeinch_manual_api_run && time() < $speeinch_manual_api_run;
	$speeinch_last_history    = get_option( 'speeinch_speed_test_history', array() );
	$speeinch_last_result     = ! empty( $speeinch_last_history ) ? $speeinch_last_history[0] : null;
	?>

	<?php /* Live response area. JS shows status / errors / success here. aria-live ensures screen readers announce changes. */ ?>
	<div id="speeinch_form_response" class="speeinch-hidden-init" aria-live="polite" role="status"></div>

	<?php /* Visible "test running" indicator with explicit timeout expectation, toggled by JS during the AJAX call. `hidden` keeps it out of the a11y tree until the test starts. */ ?>
	<div id="speeinch-test-progress" class="notice notice-info inline speeinch-test-progress" hidden aria-live="polite">
		<p>
			<span class="dashicons dashicons-update speeinch-spinner" aria-hidden="true"></span>
			<?php esc_html_e( 'Test running… probes in mainland China typically respond within 30–90 seconds. Please keep this tab open.', 'speed-in-china' ); ?>
		</p>
	</div>

	<!-- Results container (hidden by default, shown by JS after a fresh test) -->
	<div id="speeinch-results-container" class="speeinch_container speeinch-hidden-init">
		<h2 class="title"><?php esc_html_e( 'Your latest speed test result:', 'speed-in-china' ); ?></h2>
		<ul class="speeinch_test_results" id="speeinch-summary-stats"></ul>
		<table id="speeinch_form_result" class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Location', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'DNS', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TCP', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TLS', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TTFB', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'Download', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'Total', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'Status', 'speed-in-china' ); ?></th>
				</tr>
			</thead>
			<tbody></tbody>
		</table>
	</div>

	<!-- Speed test form (only visible after Connect). -->
	<?php if ( $speeinch_can_use_cloud ) : ?>
		<?php
		// Preflight reachability hint: cached 1h. If our backend is unreachable
		// from this host (e.g. sandbox provider blocking outbound HTTPS), warn
		// the user up front instead of letting them click and wait for a timeout.
		$speeinch_backend_ok = function_exists( 'speeinch_backend_reachable' ) ? speeinch_backend_reachable() : true;
		?>
		<?php if ( ! $speeinch_backend_ok ) : ?>
		<div class="notice notice-warning inline speeinch-pad-notice">
			<p>
				<strong><?php esc_html_e( 'Heads up:', 'speed-in-china' ); ?></strong>
				<?php
				printf(
					/* translators: %s: backend hostname */
					esc_html__( 'This site cannot currently reach our speed-test backend (%s). Sandbox hosts (TasteWP, WordPress Playground, some shared hosts) often block outbound HTTPS, which prevents the Start Speed Test button from completing. Local-only features (Google Fonts localization, Resource Analysis) keep working.', 'speed-in-china' ),
					'<code>api.speedinchinaplugin.com</code>'
				);
				?>
			</p>
		</div>
	<?php endif; ?>
	<div class="speeinch_container speeinch-test-area">
		<div id="speeinch-lottie-container" class="speeinch-text-center">
			<lottie-player
				id="speeinch-speed-animation"
				src="<?php echo esc_url( SPEEINCH_PLUGIN_URL . 'assets/js/vendor/dotlottie/Speedometer.json' ); ?>"
				background="transparent"
				speed="1"
				class="speeinch-lottie-canvas"
			></lottie-player>
		</div>

		<form id="speeinch_speed_test_form" method="POST" novalidate="novalidate">
			<input type="hidden" id="form_action" name="action" value="speeinch_run_api_manual" />
			<?php wp_nonce_field( 'speeinch_nonce', '_wpnonce' ); ?>
			<input type="hidden" name="security" value="<?php echo esc_attr( wp_create_nonce( 'speeinch_nonce' ) ); ?>" />

			<p class="submit speeinch-text-center">
				<button type="submit" name="submit" id="speeinch-run-test-btn" class="button button-primary button-hero" <?php disabled( $speeinch_is_on_cooldown ); ?>>
					&#9201; <?php esc_html_e( 'Start Speed Test', 'speed-in-china' ); ?>
				</button>
				<span class="spinner"></span>
			</p>

			<?php if ( $speeinch_is_on_cooldown ) : ?>
				<div class="speeinch-cooldown-notice speeinch-cooldown-wrap">
					<div id="speeinch-countdown-timer" class="speeinch-countdown" data-next-run="<?php echo esc_attr( $speeinch_manual_api_run ); ?>">
						<p class="speeinch-cooldown-heading">
							⏳ <?php esc_html_e( 'Next test available in:', 'speed-in-china' ); ?>
						</p>
						<div class="speeinch-countdown-boxes">
							<div class="speeinch-countdown-unit">
								<span id="speeinch-cd-days" class="speeinch-cd-number">--</span>
								<span class="speeinch-cd-label"><?php esc_html_e( 'Days', 'speed-in-china' ); ?></span>
							</div>
							<div class="speeinch-countdown-unit">
								<span id="speeinch-cd-hours" class="speeinch-cd-number">--</span>
								<span class="speeinch-cd-label"><?php esc_html_e( 'Hours', 'speed-in-china' ); ?></span>
							</div>
							<div class="speeinch-countdown-unit">
								<span id="speeinch-cd-mins" class="speeinch-cd-number">--</span>
								<span class="speeinch-cd-label"><?php esc_html_e( 'Minutes', 'speed-in-china' ); ?></span>
							</div>
							<div class="speeinch-countdown-unit">
								<span id="speeinch-cd-secs" class="speeinch-cd-number">--</span>
								<span class="speeinch-cd-label"><?php esc_html_e( 'Seconds', 'speed-in-china' ); ?></span>
							</div>
						</div>
					</div>
				</div>
			<?php endif; ?>
		</form>
	</div>
	<?php endif; // $speeinch_can_use_cloud (test form). ?>

	<?php
	/*
	 * =============================================
	 * Persisted Last Test Result (server-rendered)
	 * =============================================
	 */
	if ( $speeinch_last_result && ! empty( $speeinch_last_result['locations'] ) ) :
		$speeinch_tested_domain = isset( $speeinch_last_result['domain'] ) ? $speeinch_last_result['domain'] : '';
		$speeinch_tested_time   = isset( $speeinch_last_result['timestamp'] ) ? $speeinch_last_result['timestamp'] : '';

		// Calculate average total time.
		$speeinch_total_sum = 0;
		$speeinch_loc_count = count( $speeinch_last_result['locations'] );
		foreach ( $speeinch_last_result['locations'] as $speeinch_loc ) {
			$speeinch_t          = isset( $speeinch_loc['timings'] ) ? $speeinch_loc['timings'] : array();
			$speeinch_total_sum += isset( $speeinch_t['total'] ) ? floatval( $speeinch_t['total'] ) : 0;
		}
		$speeinch_avg_total = $speeinch_loc_count > 0 ? round( $speeinch_total_sum / $speeinch_loc_count ) : 0;
		$speeinch_avg_class = $speeinch_avg_total < 1000 ? 'speeinch-status-good' : ( $speeinch_avg_total < 3000 ? 'speeinch-status-warning' : 'speeinch-status-bad' );
		?>
	<div class="speeinch_container speeinch-persisted-result" id="speeinch-persisted-result">
		<h3>
			📊 <?php esc_html_e( 'Last Speed Test Result', 'speed-in-china' ); ?>
			<?php if ( $speeinch_tested_time ) : ?>
				<small class="speeinch-result-meta">
					<?php echo esc_html( $speeinch_tested_time ); ?>
					<?php if ( $speeinch_tested_domain ) : ?>
						— <?php echo esc_html( $speeinch_tested_domain ); ?>
					<?php endif; ?>
				</small>
			<?php endif; ?>
		</h3>

		<div class="speeinch-persisted-summary speeinch-persisted-summary--flex">
			<div class="speeinch-stat-card">
				<span class="speeinch-stat-value <?php echo esc_attr( $speeinch_avg_class ); ?>"><?php echo esc_html( $speeinch_avg_total ); ?>ms</span>
				<span class="speeinch-stat-label"><?php esc_html_e( 'Avg Total', 'speed-in-china' ); ?></span>
			</div>
			<div class="speeinch-stat-card">
				<span class="speeinch-stat-value"><?php echo esc_html( $speeinch_loc_count ); ?></span>
				<span class="speeinch-stat-label"><?php esc_html_e( 'Locations', 'speed-in-china' ); ?></span>
			</div>
		</div>

		<table class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Location', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'DNS', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TCP', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TLS', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'TTFB', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'Total', 'speed-in-china' ); ?></th>
					<th><?php esc_html_e( 'Status', 'speed-in-china' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php
				foreach ( $speeinch_last_result['locations'] as $speeinch_loc ) :
					$speeinch_t           = isset( $speeinch_loc['timings'] ) ? $speeinch_loc['timings'] : array();
					$speeinch_status_code = isset( $speeinch_loc['statusCode'] ) ? intval( $speeinch_loc['statusCode'] ) : 0;
					$speeinch_status_icon = ( $speeinch_status_code >= 200 && $speeinch_status_code < 400 ) ? 'dashicons-yes-alt' : 'dashicons-dismiss';
					?>
				<tr>
					<td>
					<?php
						$speeinch_city = '';
					if ( ! empty( $speeinch_loc['city'] ) ) {
						$speeinch_city = $speeinch_loc['city'];
					} elseif ( ! empty( $speeinch_loc['location'] ) ) {
						$speeinch_city = $speeinch_loc['location'];
					} else {
						$speeinch_city = 'Unknown';
					}
						echo esc_html( $speeinch_city );
					if ( ! empty( $speeinch_loc['country'] ) ) {
						echo ', ' . esc_html( $speeinch_loc['country'] );
					}
					?>
					</td>
					<td><?php echo isset( $speeinch_t['dns'] ) ? esc_html( round( $speeinch_t['dns'] ) . 'ms' ) : '—'; ?></td>
					<td><?php echo isset( $speeinch_t['tcp'] ) ? esc_html( round( $speeinch_t['tcp'] ) . 'ms' ) : '—'; ?></td>
					<td><?php echo isset( $speeinch_t['tls'] ) ? esc_html( round( $speeinch_t['tls'] ) . 'ms' ) : '—'; ?></td>
					<td><?php echo isset( $speeinch_t['firstByte'] ) ? esc_html( round( $speeinch_t['firstByte'] ) . 'ms' ) : '—'; ?></td>
					<td><strong><?php echo isset( $speeinch_t['total'] ) ? esc_html( round( $speeinch_t['total'] ) . 'ms' ) : '—'; ?></strong></td>
					<td><span class="dashicons <?php echo esc_attr( $speeinch_status_icon ); ?>"></span> HTTP <?php echo esc_html( $speeinch_status_code ); ?></td>
				</tr>
				<?php endforeach; ?>
			</tbody>
		</table>

		<?php if ( ! empty( $speeinch_last_result['suggestions'] ) ) : ?>
		<p class="speeinch-cta-row">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=speed-in-china&tab=optimizations' ) ); ?>" class="button button-primary">
				<?php esc_html_e( '💡 Check Our Optimization Suggestions', 'speed-in-china' ); ?>
			</a>
		</p>
		<?php endif; ?>
	</div>
	<?php endif; ?>
</div>
