<?php
/**
 * BaseCloud Boost — Lighthouse / PageSpeed Settings View
 *
 * @package BaseCloud\Boost
 */

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

use BaseCloud\Boost\Core\Metrics_Collector;

$options  = (array) get_option( BCBOOST_OPTIONS_KEY, [] );
$metrics  = new Metrics_Collector();
$stats    = $metrics->get_all();

$last_sent = $stats['last_lighthouse_sent']
	? human_time_diff( (int) $stats['last_lighthouse_sent'] ) . ' ' . __( 'ago', 'basecloud-boost' )
	: __( 'Never', 'basecloud-boost' );

$lh_errors = (int) ( $stats['lighthouse_errors'] ?? 0 );

$default_url = ! empty( $options['lighthouse_default_url'] ) ? $options['lighthouse_default_url'] : get_site_url();

$schedule_labels = [
	'hourly'     => __( 'Hourly', 'basecloud-boost' ),
	'twicedaily' => __( 'Twice Daily', 'basecloud-boost' ),
	'daily'      => __( 'Daily', 'basecloud-boost' ),
	'weekly'     => __( 'Weekly', 'basecloud-boost' ),
];
$current_schedule = $options['lighthouse_schedule'] ?? 'daily';
?>
<div class="bcboost-wrap">

	<?php require __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="lighthouse_webhook_enabled">

		<!-- Lighthouse Webhook Configuration -->
		<div class="bcboost-card bcboost-card--accent-blue">
			<h3><span class="bcboost-section-icon">🔦</span> <?php esc_html_e( 'Lighthouse Webhook', 'basecloud-boost' ); ?></h3>
			<p class="bcboost-card-desc"><?php esc_html_e( 'Send Lighthouse PageSpeed audit results to any webhook endpoint — integrate with Slack, Zapier, Make, or your own dashboard.', 'basecloud-boost' ); ?></p>

			<div class="bcboost-field bcboost-field--toggle">
				<label>
					<span class="bcboost-field-label"><?php esc_html_e( 'Enable Lighthouse Webhook', 'basecloud-boost' ); ?></span>
					<span class="bcboost-field-desc"><?php esc_html_e( 'Automatically send Lighthouse audit results (mobile + desktop) to your configured webhook URL.', 'basecloud-boost' ); ?></span>
				</label>
				<label class="bcboost-toggle">
					<input type="checkbox" name="lighthouse_webhook_enabled" value="1" <?php checked( ! empty( $options['lighthouse_webhook_enabled'] ) ); ?>>
					<span class="bcboost-toggle-slider"></span>
				</label>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lighthouse_webhook_url"><?php esc_html_e( 'Webhook URL', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'The HTTPS endpoint that will receive POST requests with the Lighthouse JSON payload.', 'basecloud-boost' ); ?></span>
				<input
					type="url"
					id="lighthouse_webhook_url"
					name="lighthouse_webhook_url"
					class="bcboost-input"
					placeholder="https://hooks.example.com/lighthouse"
					value="<?php echo esc_attr( $options['lighthouse_webhook_url'] ?? '' ); ?>"
					autocomplete="off"
				>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lighthouse_webhook_secret"><?php esc_html_e( 'Signing Secret (optional)', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'A shared secret for HMAC-SHA256 payload signing. Sent as X-BCBoost-Signature header.', 'basecloud-boost' ); ?></span>
				<input
					type="password"
					id="lighthouse_webhook_secret"
					name="lighthouse_webhook_secret"
					class="bcboost-input"
					placeholder="<?php echo \BaseCloud\Boost\Core\Crypto::has_secret( (string) ( $options['lighthouse_webhook_secret'] ?? '' ) ) ? esc_attr__( 'Saved &amp; encrypted — leave blank to keep', 'basecloud-boost' ) : esc_attr__( 'Leave blank to skip signing', 'basecloud-boost' ); ?>"
					value=""
					autocomplete="new-password"
				>
			</div>
		</div>

		<!-- Delivery Schedule -->
		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">🕐</span> <?php esc_html_e( 'Delivery Schedule', 'basecloud-boost' ); ?></h3>
			<p class="bcboost-card-desc"><?php esc_html_e( 'How often WP-Cron should automatically run Lighthouse audits and send results to your webhook. Each run audits both mobile and desktop.', 'basecloud-boost' ); ?></p>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lighthouse_schedule"><?php esc_html_e( 'Audit Frequency', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'Changes take effect immediately after saving.', 'basecloud-boost' ); ?></span>
				<select id="lighthouse_schedule" name="lighthouse_schedule" class="bcboost-input" style="max-width:240px;">
					<?php foreach ( $schedule_labels as $val => $label ) : ?>
						<option value="<?php echo esc_attr( $val ); ?>" <?php selected( $current_schedule, $val ); ?>><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>
		</div>

		<!-- PageSpeed Insights API -->
		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">⚡</span> <?php esc_html_e( 'PageSpeed Insights API', 'basecloud-boost' ); ?></h3>
			<p class="bcboost-card-desc"><?php esc_html_e( 'Audits use the Google PageSpeed Insights API (powered by Lighthouse). Without an API key, Google rate-limits anonymous requests to ~25/day.', 'basecloud-boost' ); ?></p>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lighthouse_psi_api_key"><?php esc_html_e( 'PSI API Key (recommended)', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'A Google Cloud API key with the PageSpeed Insights API enabled. Removes the anonymous rate limit.', 'basecloud-boost' ); ?></span>
				<input
					type="password"
					id="lighthouse_psi_api_key"
					name="lighthouse_psi_api_key"
					class="bcboost-input"
					placeholder="<?php echo \BaseCloud\Boost\Core\Crypto::has_secret( (string) ( $options['lighthouse_psi_api_key'] ?? '' ) ) ? esc_attr__( 'Saved &amp; encrypted — leave blank to keep', 'basecloud-boost' ) : 'AIza...'; ?>"
					value=""
					autocomplete="off"
				>
			</div>

			<div class="bcboost-field">
				<label class="bcboost-field-label" for="lighthouse_default_url"><?php esc_html_e( 'Default Audit URL', 'basecloud-boost' ); ?></label>
				<span class="bcboost-field-desc"><?php esc_html_e( 'URL used for scheduled and test audits. Defaults to the site home URL if blank.', 'basecloud-boost' ); ?></span>
				<input
					type="url"
					id="lighthouse_default_url"
					name="lighthouse_default_url"
					class="bcboost-input"
					placeholder="<?php echo esc_attr( get_site_url() ); ?>"
					value="<?php echo esc_attr( $options['lighthouse_default_url'] ?? '' ); ?>"
					autocomplete="off"
				>
			</div>
		</div>

		<!-- Webhook Status & Actions -->
		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">📡</span> <?php esc_html_e( 'Webhook Status', 'basecloud-boost' ); ?></h3>

			<div class="bcboost-webhook-status-row">
				<div class="bcboost-webhook-stat">
					<span class="bcboost-webhook-stat-label"><?php esc_html_e( 'Last Sent', 'basecloud-boost' ); ?></span>
					<span class="bcboost-webhook-stat-value"><?php echo esc_html( $last_sent ); ?></span>
				</div>
				<div class="bcboost-webhook-stat">
					<span class="bcboost-webhook-stat-label"><?php esc_html_e( 'Delivery Errors', 'basecloud-boost' ); ?></span>
					<span class="bcboost-webhook-stat-value <?php echo $lh_errors > 0 ? 'bcboost-text-danger' : ''; ?>"><?php echo esc_html( $lh_errors ); ?></span>
				</div>
				<div class="bcboost-webhook-stat">
					<span class="bcboost-webhook-stat-label"><?php esc_html_e( 'Audits Per Run', 'basecloud-boost' ); ?></span>
					<span class="bcboost-webhook-stat-value"><?php esc_html_e( 'Mobile + Desktop', 'basecloud-boost' ); ?></span>
				</div>
				<div class="bcboost-webhook-stat">
					<span class="bcboost-webhook-stat-label"><?php esc_html_e( 'Schedule', 'basecloud-boost' ); ?></span>
					<span class="bcboost-webhook-stat-value"><?php echo esc_html( $schedule_labels[ $current_schedule ] ?? ucfirst( $current_schedule ) ); ?></span>
				</div>
			</div>

			<div class="bcboost-webhook-actions">
				<button type="button" class="bcboost-btn bcboost-btn--secondary" id="bcboost-lh-webhook-test">
					<span class="dashicons dashicons-external"></span>
					<?php esc_html_e( 'Test Webhook', 'basecloud-boost' ); ?>
				</button>
				<button type="button" class="bcboost-btn bcboost-btn--secondary" id="bcboost-lh-send-now">
					<span class="dashicons dashicons-cloud-upload"></span>
					<?php esc_html_e( 'Send Now', 'basecloud-boost' ); ?>
				</button>
			</div>
			<div id="bcboost-lh-webhook-feedback" class="bcboost-feedback" style="display:none;margin-top:14px;"></div>
		</div>

		<!-- Payload Preview -->
		<div class="bcboost-card">
			<h3><span class="bcboost-section-icon">📋</span> <?php esc_html_e( 'Payload Preview', 'basecloud-boost' ); ?></h3>
			<p class="bcboost-card-desc"><?php esc_html_e( 'This is the JSON structure that will be POST-ed to your webhook. Run a live audit below to see real values.', 'basecloud-boost' ); ?></p>
			<pre class="bcboost-payload-preview" id="bcboost-lh-static-payload"><code><?php echo esc_html( wp_json_encode( [
				'event'          => 'BCBOOST_lighthouse',
				'plugin_version' => BCBOOST_VERSION,
				'site_url'       => get_site_url(),
				'site_name'      => get_bloginfo( 'name' ),
				'tested_url'     => $default_url,
				'strategy'       => 'mobile',
				'timestamp'      => gmdate( 'c' ),
				'scores'         => [ 'performance' => 0, 'accessibility' => 0, 'best_practices' => 0, 'seo' => 0 ],
				'metrics'        => [ 'fcp_ms' => 0, 'lcp_ms' => 0, 'tbt_ms' => 0, 'cls' => 0.0, 'speed_index_ms' => 0, 'tti_ms' => 0, 'ttfb_ms' => 0 ],
			], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></code></pre>
		</div>

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

	<!-- ── Live Lighthouse Audit Panel (runs in the browser via PSI API) ── -->
	<div class="bcboost-card bcboost-card--accent-green" style="margin-top:28px;">
		<h3><span class="bcboost-section-icon">🏎️</span> <?php esc_html_e( 'Run Live Lighthouse Audit', 'basecloud-boost' ); ?></h3>
		<p class="bcboost-card-desc"><?php esc_html_e( 'Trigger an on-demand audit from your browser. Results appear in real time and can be sent to your webhook.', 'basecloud-boost' ); ?></p>

		<div class="bcboost-lighthouse-controls">
			<div class="bcboost-field" style="flex:1;min-width:260px;">
				<label class="bcboost-field-label" for="bcboost-lh-url"><?php esc_html_e( 'URL to Audit', 'basecloud-boost' ); ?></label>
				<input
					type="url"
					id="bcboost-lh-url"
					class="bcboost-input"
					placeholder="<?php echo esc_attr( get_site_url() ); ?>"
					value="<?php echo esc_attr( $default_url ); ?>"
				>
			</div>
			<div class="bcboost-field" style="min-width:160px;">
				<label class="bcboost-field-label" for="bcboost-lh-strategy"><?php esc_html_e( 'Device', 'basecloud-boost' ); ?></label>
				<select id="bcboost-lh-strategy" class="bcboost-input">
					<option value="mobile"><?php esc_html_e( 'Mobile', 'basecloud-boost' ); ?></option>
					<option value="desktop"><?php esc_html_e( 'Desktop', 'basecloud-boost' ); ?></option>
				</select>
			</div>
		</div>

		<div class="bcboost-lighthouse-actions" style="margin-top:16px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
			<button type="button" class="bcboost-btn bcboost-btn--primary" id="bcboost-lh-run">
				<span class="dashicons dashicons-performance"></span>
				<?php esc_html_e( 'Run Audit', 'basecloud-boost' ); ?>
			</button>
			<button type="button" class="bcboost-btn bcboost-btn--secondary" id="bcboost-lh-send" disabled>
				<span class="dashicons dashicons-cloud-upload"></span>
				<?php esc_html_e( 'Send to Webhook', 'basecloud-boost' ); ?>
			</button>
			<span id="bcboost-lh-spinner" style="display:none;" class="bcboost-lh-spinner">
				<span class="dashicons dashicons-update bcboost-spin"></span>
				<?php esc_html_e( 'Running audit…', 'basecloud-boost' ); ?>
			</span>
		</div>

		<div id="bcboost-lh-feedback" class="bcboost-feedback" style="display:none;margin-top:12px;"></div>

		<!-- Score Rings -->
		<div id="bcboost-lh-results" style="display:none;margin-top:28px;">
			<div class="bcboost-lh-scores" style="display:flex;gap:20px;flex-wrap:wrap;justify-content:center;margin-bottom:24px;">
				<?php
				$ring_items = [
					'performance'    => __( 'Performance',    'basecloud-boost' ),
					'accessibility'  => __( 'Accessibility',  'basecloud-boost' ),
					'best-practices' => __( 'Best Practices', 'basecloud-boost' ),
					'seo'            => __( 'SEO',            'basecloud-boost' ),
				];
				foreach ( $ring_items as $cat => $label ) : ?>
				<div class="bcboost-lh-score-card">
					<div class="bcboost-lh-score-ring" data-category="<?php echo esc_attr( $cat ); ?>">
						<svg viewBox="0 0 120 120" width="90" height="90">
							<circle class="bcboost-lh-ring-bg" cx="60" cy="60" r="50" fill="none" stroke-width="10"/>
							<circle class="bcboost-lh-ring-fill" cx="60" cy="60" r="50" fill="none" stroke-width="10" stroke-dasharray="314" stroke-dashoffset="314" transform="rotate(-90 60 60)"/>
							<text class="bcboost-lh-ring-text" x="60" y="65" text-anchor="middle" font-size="26" font-weight="700">—</text>
						</svg>
					</div>
					<span class="bcboost-lh-score-label"><?php echo esc_html( $label ); ?></span>
				</div>
				<?php endforeach; ?>
			</div>

			<!-- Core Web Vitals -->
			<div class="bcboost-lh-metrics">
				<h4 style="margin:0 0 14px;font-size:13px;text-transform:uppercase;letter-spacing:.07em;opacity:.7;"><?php esc_html_e( 'Core Web Vitals & Metrics', 'basecloud-boost' ); ?></h4>
				<div class="bcboost-webhook-status-row" style="flex-wrap:wrap;gap:12px;">
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">FCP</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-fcp">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">LCP</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-lcp">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">TBT</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-tbt">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">CLS</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-cls">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">Speed Index</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-si">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">TTI</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-tti">—</span></div>
					<div class="bcboost-webhook-stat"><span class="bcboost-webhook-stat-label">TTFB</span><span class="bcboost-webhook-stat-value" id="bcboost-lh-ttfb">—</span></div>
				</div>
			</div>

			<!-- Live Payload Preview -->
			<div style="margin-top:20px;">
				<h4 style="margin:0 0 8px;font-size:13px;text-transform:uppercase;letter-spacing:.07em;opacity:.7;"><?php esc_html_e( 'Live Webhook Payload', 'basecloud-boost' ); ?></h4>
				<pre class="bcboost-payload-preview" id="bcboost-lh-payload-preview" style="max-height:260px;overflow:auto;"><code></code></pre>
			</div>
		</div>
	</div>

</div>

<?php // Lighthouse component styles are enqueued via wp_add_inline_style in Admin_Controller. ?>
