<!-- #region ValidationHistoryPage [C:3] [TYPE Page] [SEMANTICS validation-tasks,history,run-list] -->
<!-- @BRIEF History page showing all validation runs across all tasks, with status filtering. -->
<!-- @RELATION DEPENDS_ON -> [I18nModule] -->
<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { t } from '$lib/i18n/index.svelte.js';

	/** @type {{ data: import('./$types').PageData }} */
	let { data } = $props();

	let runs = $state(data.runs ?? []);
	let total = $state(data.total ?? 0);
	let currentPage = $state(data.page ?? 1);
	let pageSize = $state(data.page_size ?? 20);
	let statusFilter = $state(data.statusFilter ?? '');
	let loading = $state(false);
	let error = $state(data.error ?? null);

	const totalPages = $derived(Math.ceil(total / pageSize) || 1);

	function getStatusBadge(status: string): string {
		const map: Record<string, string> = {
			PASS: 'bg-green-100 text-green-700',
			WARN: 'bg-yellow-100 text-yellow-700',
			FAIL: 'bg-red-100 text-red-700',
			UNKNOWN: 'bg-gray-100 text-gray-500',
			RUNNING: 'bg-blue-100 text-blue-700',
			PENDING: 'bg-yellow-100 text-yellow-700',
		};
		return map[status] || 'bg-gray-100 text-gray-500';
	}

	function formatDate(ts: string | null): string {
		if (!ts) return '—';
		return new Date(ts).toLocaleString();
	}

	function formatDuration(started: string | null, finished: string | null): string {
		if (!started) return '—';
		const start = new Date(started).getTime();
		const end = finished ? new Date(finished).getTime() : Date.now();
		const ms = end - start;
		if (ms < 1000) return `${ms}ms`;
		if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
		return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
	}

	function getRunLink(run: any): string | null {
		if (!run.policy_id) return null;
		// If we have a ValidationRun.id, link to the run report
		if (run.run_id) {
			return `/validation-tasks/${encodeURIComponent(run.policy_id)}/runs/${encodeURIComponent(run.run_id)}`;
		}
		// Otherwise link to the task detail page showing run history
		return `/validation-tasks/${encodeURIComponent(run.policy_id)}`;
	}

	function viewRun(run: any) {
		const link = getRunLink(run);
		if (link) goto(link);
	}

	async function applyFilter() {
		loading = true;
		error = null;
		try {
			const qs = new URLSearchParams();
			qs.append('page', '1');
			qs.append('page_size', String(pageSize));
			if (statusFilter) qs.append('status', statusFilter);

			const { fetchApi } = await import('$lib/api');
			const result = await fetchApi(`/validation-tasks/runs/all?${qs.toString()}`);

			runs = result?.items ?? result?.results ?? [];
			total = result?.total ?? 0;
			currentPage = 1;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to load runs';
		} finally {
			loading = false;
		}
	}
</script>

<svelte:head>
	<title>{$t.validation?.history_page || 'Validation History'}</title>
</svelte:head>

<div class="max-w-7xl mx-auto px-4 py-6">
	<div class="flex items-center justify-between mb-6">
		<h1 class="text-2xl font-bold text-gray-900">{$t.validation?.history_page || 'Validation History'}</h1>
		<select
			value={statusFilter}
			onchange={(e) => { statusFilter = (e.target as HTMLSelectElement).value; applyFilter(); }}
			class="px-3 py-2 border border-gray-300 rounded-lg text-sm"
		>
			<option value="">{$t.validation?.all_statuses || 'All statuses'}</option>
			<option value="PASS">PASS</option>
			<option value="WARN">WARN</option>
			<option value="FAIL">FAIL</option>
			<option value="RUNNING">{$t.validation?.running || 'Running'}</option>
			<option value="PENDING">{$t.validation?.pending || 'Pending'}</option>
		</select>
	</div>

	{#if error}
		<div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6 text-sm text-red-700" role="alert">
			{error}
		</div>
	{/if}

	<div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
		{#if loading}
			<div class="p-8 text-center text-sm text-gray-400">
				<div class="inline-block animate-spin h-5 w-5 border-2 border-blue-500 border-t-transparent rounded-full mb-2"></div>
				<p>{$t.common?.loading || 'Loading...'}</p>
			</div>
		{:else if runs.length === 0}
			<div class="p-8 text-center text-sm text-gray-500">
				<p>{$t.validation?.no_runs || 'No validation runs found.'}</p>
			</div>
		{:else}
			<table class="min-w-full divide-y divide-gray-200">
				<thead class="bg-gray-50">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.status || 'Status'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.dashboard || 'Dashboard'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.environment || 'Environment'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.started || 'Started'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.duration || 'Duration'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.summary || 'Summary'}</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-100">
					{#each runs as run (run.id)}
						<tr
							onclick={() => viewRun(run)}
							class="{run.policy_id ? 'hover:bg-gray-50 cursor-pointer' : ''} transition-colors"
						>
							<td class="px-4 py-3">
								<span class={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusBadge(run.status)}`}>
									{run.status}
								</span>
							</td>
							<td class="px-4 py-3 text-sm text-gray-900 font-medium">{run.dashboard_title || run.dashboard_name || run.dashboard_id || '—'}</td>
							<td class="px-4 py-3 text-sm text-gray-500">{run.environment_id || '—'}</td>
							<td class="px-4 py-3 text-sm text-gray-500">{formatDate(run.started_at || run.timestamp)}</td>
							<td class="px-4 py-3 text-sm text-gray-500">{formatDuration(run.started_at, run.finished_at)}</td>
							<td class="px-4 py-3 text-sm text-gray-600 max-w-xs truncate">{run.summary || '—'}</td>
						</tr>
					{/each}
				</tbody>
			</table>

			<!-- Pagination -->
			{#if totalPages > 1}
				<div class="flex items-center justify-between px-4 py-3 bg-gray-50 border-t border-gray-200">
					<p class="text-sm text-gray-500">
						{($t.validation?.showing || 'Showing {from}-{to} of {total}')
							.replace('{from}', String((currentPage - 1) * pageSize + 1))
							.replace('{to}', String(Math.min(currentPage * pageSize, total)))
							.replace('{total}', String(total))}
					</p>
					<nav class="flex gap-1">
						<button
							disabled={currentPage <= 1}
							onclick={() => { currentPage--; applyFilter(); }}
							class="px-3 py-1 text-sm border border-gray-300 rounded-md disabled:opacity-50 hover:bg-gray-100"
						>←</button>
						<button
							disabled={currentPage >= totalPages}
							onclick={() => { currentPage++; applyFilter(); }}
							class="px-3 py-1 text-sm border border-gray-300 rounded-md disabled:opacity-50 hover:bg-gray-100"
						>→</button>
					</nav>
				</div>
			{/if}
		{/if}
	</div>
</div>
<!-- #endregion ValidationHistoryPage -->
