<?php
/**
 * Scans page — interactive AJAX scan runner.
 *
 * @package WPLens
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:disable WordPress.Security.NonceVerification.Recommended

$repo         = new \WPLens\Scans\ScanRepository();
$recent       = $repo->recent( 25 );
$prov_default = \WPLens\AI\ProviderRegistry::default();
$ai_ready     = $prov_default && $prov_default->is_configured();
?>
<div class="wrap lens-wrap">
	<h1>
		<img class="lens-icon" src="<?php echo esc_url( WPLENS_PLUGIN_URL . 'assets/icon.svg' ); ?>" alt="" />
		<?php esc_html_e( 'AEO Scans', 'lens-ai-visibility-monitor' ); ?>
	</h1>

	<div class="lens-card" id="lens-bulk-runner" style="margin-bottom:20px;">
		<header style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
			<h2 style="margin:0;font-size:18px;"><?php esc_html_e( 'Bulk scan', 'lens-ai-visibility-monitor' ); ?></h2>
			<span class="lens-pill info"><?php esc_html_e( 'Scan many posts at once', 'lens-ai-visibility-monitor' ); ?></span>
		</header>

		<p style="color:#50575e;margin-top:0;">
			<?php esc_html_e( 'Pick what to scan, then click Start. Scans run one at a time so OpenAI rate limits and PHP timeouts are not a concern — leave this tab open and progress will update live. Cancel anytime.', 'lens-ai-visibility-monitor' ); ?>
		</p>

		<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(220px, 1fr));gap:14px;margin:14px 0;">
			<div>
				<label for="lens-bulk-type" style="display:block;font-weight:600;font-size:12px;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;color:#50575e;">
					<?php esc_html_e( 'Post type', 'lens-ai-visibility-monitor' ); ?>
				</label>
				<select id="lens-bulk-type" class="lens-select">
					<option value="any"><?php esc_html_e( 'Posts and pages', 'lens-ai-visibility-monitor' ); ?></option>
					<option value="post"><?php esc_html_e( 'Posts only', 'lens-ai-visibility-monitor' ); ?></option>
					<option value="page"><?php esc_html_e( 'Pages only', 'lens-ai-visibility-monitor' ); ?></option>
				</select>
			</div>
			<div>
				<label for="lens-bulk-filter" style="display:block;font-weight:600;font-size:12px;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;color:#50575e;">
					<?php esc_html_e( 'Which posts', 'lens-ai-visibility-monitor' ); ?>
					<span class="lens-help" data-tooltip="<?php esc_attr_e( 'Unscanned skips anything already in scan history. Stale re-scans posts whose last scan is older than 30 days.', 'lens-ai-visibility-monitor' ); ?>">?</span>
				</label>
				<select id="lens-bulk-filter" class="lens-select">
					<option value="unscanned"><?php esc_html_e( 'Only unscanned posts', 'lens-ai-visibility-monitor' ); ?></option>
					<option value="stale"><?php esc_html_e( 'Stale (no scan in 30 days)', 'lens-ai-visibility-monitor' ); ?></option>
					<option value="all"><?php esc_html_e( 'Everything (re-scan all)', 'lens-ai-visibility-monitor' ); ?></option>
				</select>
			</div>
			<div style="display:flex;align-items:flex-end;">
				<label style="display:flex;align-items:center;gap:8px;">
					<input type="checkbox" id="lens-bulk-with-ai" <?php echo esc_attr( $ai_ready ? '' : 'disabled' ); ?>>
					<?php esc_html_e( 'Include AI-enriched scoring', 'lens-ai-visibility-monitor' ); ?>
					<span class="lens-help" data-tooltip="<?php esc_attr_e( 'Adds the 0-100 citability score and ranked fixes. Costs roughly $0.001-$0.005 per post on gpt-4o-mini.', 'lens-ai-visibility-monitor' ); ?>">?</span>
				</label>
			</div>
		</div>

		<div id="lens-bulk-estimate" style="font-size:13px;color:#1d2327;margin:12px 0 14px;min-height:20px;padding:10px 12px;background:#f0f7ff;border:1px solid #c0d7ed;border-radius:4px;">
			<?php esc_html_e( 'Calculating…', 'lens-ai-visibility-monitor' ); ?>
		</div>

		<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
			<button id="lens-bulk-start" type="button" class="lens-btn primary" style="padding:8px 18px;font-size:14px;">
				<span class="spinner"></span>
				<?php esc_html_e( 'Start bulk scan', 'lens-ai-visibility-monitor' ); ?>
			</button>
			<button id="lens-bulk-cancel" type="button" class="lens-btn" style="display:none;color:#b32d2e;border-color:#b32d2e;">
				<?php esc_html_e( 'Cancel', 'lens-ai-visibility-monitor' ); ?>
			</button>
			<button id="lens-bulk-refresh" type="button" class="lens-btn ghost" style="margin-left:auto;">
				<span class="spinner"></span>
				<?php esc_html_e( 'Refresh count', 'lens-ai-visibility-monitor' ); ?>
			</button>
		</div>

		<div id="lens-bulk-progress" style="display:none;margin-top:18px;">
			<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
				<span id="lens-bulk-progress-label" style="font-weight:600;color:#1d2327;font-size:13px;"></span>
				<span id="lens-bulk-progress-eta" style="color:#646970;font-size:12px;"></span>
			</div>
			<div style="height:10px;background:#f0f0f1;border-radius:5px;overflow:hidden;">
				<div id="lens-bulk-progress-bar" style="height:100%;width:0%;background:#2271b1;transition:width .3s;"></div>
			</div>
			<div id="lens-bulk-log" style="margin-top:14px;max-height:280px;overflow-y:auto;background:#fbfbfc;border:1px solid #dcdcde;border-radius:6px;padding:8px;font-size:12px;font-family:ui-monospace,Consolas,monospace;display:none;"></div>
		</div>

		<div id="lens-bulk-summary" style="display:none;margin-top:18px;padding:14px;border-radius:6px;"></div>
	</div>

	<div class="lens-card" id="lens-scan-runner">
		<h2 style="margin-top:0;"><?php esc_html_e( 'Run a scan', 'lens-ai-visibility-monitor' ); ?></h2>

		<div class="lens-picker" style="max-width:520px;">
			<label for="lens-post-search" style="display:block;font-weight:600;margin-bottom:6px;font-size:13px;">
				<?php esc_html_e( 'Pick a post or page', 'lens-ai-visibility-monitor' ); ?>
				<span class="lens-help" data-tooltip="<?php esc_attr_e( 'Start typing the title. Search includes drafts and pending posts.', 'lens-ai-visibility-monitor' ); ?>">?</span>
			</label>
			<div class="lens-search">
				<input
					id="lens-post-search"
					type="search"
					class="lens-input lens-picker-input"
					autocomplete="off"
					placeholder="<?php esc_attr_e( 'Type a title…', 'lens-ai-visibility-monitor' ); ?>"
				/>
				<input type="hidden" id="lens-post-id" />
			</div>
			<div class="lens-picker-results" role="listbox"></div>
		</div>

		<div style="display:flex;gap:18px;align-items:center;margin-top:14px;flex-wrap:wrap;">
			<label style="display:flex;gap:6px;align-items:center;">
				<input type="checkbox" id="lens-with-ai" <?php echo esc_attr( $ai_ready ? '' : 'disabled' ); ?>>
				<?php esc_html_e( 'Also run AI-enriched scoring', 'lens-ai-visibility-monitor' ); ?>
				<span class="lens-help" data-tooltip="<?php esc_attr_e( 'Uses your OpenAI key. Adds a 0-100 citability score and 3 ranked fixes.', 'lens-ai-visibility-monitor' ); ?>">?</span>
			</label>
			<?php if ( ! $ai_ready ) : ?>
				<span class="lens-pill warn">
					<?php
					printf(
						/* translators: %s — settings link */
						esc_html__( 'Add an OpenAI key in %s to unlock AI scoring.', 'lens-ai-visibility-monitor' ),
						'<a href="' . esc_url( admin_url( 'admin.php?page=lens-settings' ) ) . '">' . esc_html__( 'Settings', 'lens-ai-visibility-monitor' ) . '</a>'
					);
					?>
				</span>
			<?php endif; ?>
			<button id="lens-run-scan" type="button" class="lens-btn primary" disabled>
				<span class="spinner"></span>
				<?php esc_html_e( 'Run scan', 'lens-ai-visibility-monitor' ); ?>
			</button>
		</div>
	</div>

	<div class="lens-card" id="lens-scan-result" style="display:none;margin-top:20px;">
		<header style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
			<h2 style="margin:0;font-size:18px;" id="lens-scan-result-title"></h2>
			<span id="lens-scan-result-score"></span>
		</header>
		<div id="lens-scan-result-bar" style="height:8px;background:#f0f0f1;border-radius:4px;overflow:hidden;margin-bottom:18px;">
			<div id="lens-scan-result-fill" style="height:100%;width:0%;background:#2271b1;transition:width .4s;"></div>
		</div>
		<div id="lens-scan-result-findings"></div>
		<div id="lens-scan-result-ai" style="display:none;margin-top:18px;padding:16px;background:#fbfbfc;border-radius:6px;border:1px solid #dcdcde;">
			<strong style="display:block;margin-bottom:8px;"><?php esc_html_e( 'AI-enriched analysis', 'lens-ai-visibility-monitor' ); ?></strong>
			<pre id="lens-scan-result-ai-text" style="white-space:pre-wrap;margin:0;font-family:inherit;font-size:13px;line-height:1.5;"></pre>
		</div>
	</div>

	<div class="lens-card" style="margin-top:20px;">
		<header style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
			<h2 style="margin:0;font-size:18px;"><?php esc_html_e( 'Recent scans', 'lens-ai-visibility-monitor' ); ?></h2>
		</header>
		<?php if ( empty( $recent ) ) : ?>
			<div class="lens-empty">
				<h3><?php esc_html_e( 'No scans yet', 'lens-ai-visibility-monitor' ); ?></h3>
				<p><?php esc_html_e( 'Pick a post above and click "Run scan" to get started.', 'lens-ai-visibility-monitor' ); ?></p>
			</div>
		<?php else : ?>
			<table class="lens-table">
				<thead><tr>
					<th><?php esc_html_e( 'Post', 'lens-ai-visibility-monitor' ); ?></th>
					<th><?php esc_html_e( 'Type', 'lens-ai-visibility-monitor' ); ?></th>
					<th><?php esc_html_e( 'Provider', 'lens-ai-visibility-monitor' ); ?></th>
					<th><?php esc_html_e( 'Score', 'lens-ai-visibility-monitor' ); ?></th>
					<th><?php esc_html_e( 'When', 'lens-ai-visibility-monitor' ); ?></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $recent as $row ) :
					$score = isset( $row['score'] ) ? (int) $row['score'] : null;
					$cls   = null === $score ? '' : ( $score >= 75 ? 's-high' : ( $score >= 50 ? 's-mid' : 's-low' ) );
					$title = get_the_title( (int) $row['post_id'] );
				?>
					<tr>
						<td><a href="<?php echo esc_url( get_edit_post_link( (int) $row['post_id'] ) ); ?>"><?php echo esc_html( '' !== $title ? $title : sprintf( '#%d', (int) $row['post_id'] ) ); ?></a></td>
						<td class="muted"><?php echo esc_html( $row['scan_type'] ); ?></td>
						<td class="muted"><?php echo esc_html( $row['ai_provider'] ?? '—' ); ?></td>
						<td><?php echo null === $score ? '<span class="muted">—</span>' : '<span class="lens-score ' . esc_attr( $cls ) . '">' . esc_html( $score ) . '</span>'; ?></td>
						<td class="muted"><?php echo esc_html( $row['created_at'] ); ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</div>
</div>
