<!-- #region ValidationTaskDetailPage [C:4] [TYPE Component] [SEMANTICS validation, task, detail, run-history, page] -->
<!-- @BRIEF Validation task detail page with run history table, task metadata header, and action buttons (Run Now, Edit, Delete). -->
<!-- @RELATION DEPENDS_ON -> [ValidationApi] -->
<!-- @RELATION BINDS_TO -> [I18nModule] -->
<!-- @UX_STATE Loading -> Skeleton header + skeleton table rows -->
<!-- @UX_STATE Error -> Alert with error message + Retry button -->
<!-- @UX_STATE Populated -> Task header + run history table + pagination -->
<!-- @UX_STATE Empty -> Task header + "No runs yet" empty state -->
<!-- @UX_FEEDBACK Toast notifications on run/delete actions -->
<!-- @UX_RECOVERY Retry button on load errors, Back to tasks link -->
<!-- @UX_REACTIVITY Props -> $props(data), LocalState -> $state(...) -->
<script lang="ts">
	import { goto } from '$app/navigation';
	import { t } from '$lib/i18n/index.svelte.js';
	import { addToast } from '$lib/toasts.svelte.js';
	import { triggerValidationRun as triggerRun, deleteValidationTask as deleteTask, getValidationRuns as fetchRuns } from '$lib/api.js';
	import { page } from '$app/state';

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

	let policyId = $derived(page.params.policyId);

	/** @type {'idle'|'loading'|'populated'|'empty'|'error'} */
	let uxState = $state('idle');
	let task = $state(data.task);
	let runs = $state(data.runs);
	let total = $state(data.total);
	let errorMsg = $state(null);

	// Pagination
	let currentPage = $state(1);
	let pageSize = $state(20);

	// Action states
	let isRunning = $state(false);
	let showDeleteConfirm = $state(false);

	// Derived status
	let isScheduled = $derived(task?.schedule_days?.length > 0);

	/** @param {string} status */
	function getStatusBadgeClass(status) {
		const map = {
			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',
			COMPLETED: 'bg-green-100 text-green-700',
		};
		return map[status] || 'bg-gray-100 text-gray-500';
	}

	/** @param {string} status */
	const getRunStatusBadgeClass = getStatusBadgeClass;

	/** @param {number} ms */
	function formatDuration(ms) {
		if (!ms && ms !== 0) return '-';
		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 getAggregateSummary(run) {
		const pass = run.pass_count ?? run.passed ?? 0;
		const warn = run.warn_count ?? run.warnings ?? 0;
		const fail = run.fail_count ?? run.failed ?? 0;
		return ($t.validation?.aggregate_status || '{pass} PASS • {warn} WARN • {fail} FAIL')
			.replace('{pass}', String(pass))
			.replace('{warn}', String(warn))
			.replace('{fail}', String(fail));
	}

	function getTriggerLabel(trigger) {
		if (trigger === 'manual') return $t.validation?.trigger_manual || 'Manual';
		if (trigger === 'scheduled') return $t.validation?.trigger_scheduled || 'Scheduled';
		return trigger || '-';
	}

	async function handleRunNow() {
		isRunning = true;
		try {
			await triggerRun(policyId);
			addToast($t.validation?.run_triggered || 'Validation run triggered.', 'success');
		} catch (err) {
			addToast(err?.message || ($t.validation?.run_failed || 'Failed to trigger run.'), 'error');
		} finally {
			isRunning = false;
		}
	}

	async function handleDelete() {
		try {
			await deleteTask(policyId);
			addToast($t.validation?.delete_success || 'Deleted successfully.', 'success');
			// eslint-disable-next-line svelte/no-navigation-without-resolve
			goto('/validation-tasks');
		} catch (err) {
			addToast(err?.message || ($t.validation?.delete_failed || 'Failed to delete.'), 'error');
		}
	}

	async function handleEdit() {
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto(`/validation-tasks/${encodeURIComponent(policyId)}/edit`);
	}

	async function loadRunHistory() {
		uxState = 'loading';
		errorMsg = null;
		try {
			const result = await fetchRuns(policyId, { page: currentPage, page_size: pageSize });
			const items = Array.isArray(result) ? result : (result?.results || result?.items || []);
			runs = items;
			total = result?.total || result?.count || items.length;
			uxState = items.length === 0 ? 'empty' : 'populated';
		} catch (err) {
			errorMsg = err?.message || ($t.validation?.load_runs_failed || 'Failed to load run history.');
			uxState = 'error';
		}
	}

	function handlePageChange(newPage) {
		currentPage = newPage;
		loadRunHistory();
	}

	function handleViewRun(runId) {
		// eslint-disable-next-line svelte/no-navigation-without-resolve
		goto(`/validation-tasks/${policyId}/runs/${runId}`);
	}

	// Initial state after load
	$effect(() => {
		uxState = data.runs.length === 0 ? 'empty' : 'populated';
	});
</script>

<svelte:head>
	<title>{task?.name || $t.validation?.run_detail || 'Task Detail'}</title>
</svelte:head>

<div class="container mx-auto px-4 py-6 max-w-full xl:max-w-7xl">
	<!-- Back link -->
	<a
		href="/validation-tasks"
		class="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 mb-4 transition-colors"
	>
		<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
			<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
		</svg>
		{$t.validation?.back_to_tasks || '← Back to tasks'}
	</a>

	<!-- Task Header -->
	<div class="bg-white border border-gray-200 rounded-lg p-6 mb-6">
		<div class="flex items-start justify-between">
			<div class="flex-1 min-w-0">
				<div class="flex items-center gap-3 mb-2">
					<h1 class="text-2xl font-bold text-gray-900 truncate">{task?.name || '-'}</h1>
					{#if task?.is_active !== false}
						<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
							{$t.validation?.active || 'Active'}
						</span>
					{:else}
						<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500">
							{$t.validation?.inactive || 'Inactive'}
						</span>
					{/if}
					{#if isScheduled}
						<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
							{$t.validation?.scheduled || 'Scheduled'}
						</span>
					{:else}
						<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500">
							{$t.validation?.manual_only || 'Manual only'}
						</span>
					{/if}
				</div>
				<div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-gray-500">
					{#if task?.environment_id}
						<span>
							{$t.validation?.environment || 'Environment'}: {task.environment_id}
						</span>
					{/if}
					{#if task?.provider_id}
						<span>
							{$t.validation?.provider || 'LLM'}: {task.provider_id}
						</span>
					{/if}
					{#if task?.created_at}
						<span>
							{$t.validation?.created_at || 'Created'}: {new Date(task.created_at).toLocaleString()}
						</span>
					{/if}
					{#if task?.updated_at}
						<span>
							{$t.validation?.updated_at || 'Updated'}: {new Date(task.updated_at).toLocaleString()}
						</span>
					{/if}
				</div>
				{#if task?.dashboard_ids?.length}
					<p class="text-sm text-gray-500 mt-1">
						{$t.validation?.dashboard || 'Dashboard'}s: {task.dashboard_ids.length}
					</p>
				{/if}
			</div>
			<div class="flex items-center gap-2 ml-4 flex-shrink-0">
				<button
					onclick={handleRunNow}
					disabled={isRunning}
					class="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors text-sm"
				>
					{#if isRunning}
						<svg class="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
							<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none" />
							<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
						</svg>
						{$t.validation?.running || 'Running...'}
					{:else}
						{$t.validation?.run_now || 'Run Now'}
					{/if}
				</button>
				<button
					onclick={handleEdit}
					class="inline-flex items-center px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm"
				>
					<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
					</svg>
					{$t.validation?.edit_task || 'Edit'}
				</button>
				{#if showDeleteConfirm}
					<div class="flex items-center gap-1">
						<button
							onclick={handleDelete}
							class="px-3 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
						>
							{$t.validation?.confirm_delete || 'Delete'}
						</button>
						<button
							onclick={() => (showDeleteConfirm = false)}
							class="px-3 py-2 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
						>
							{$t.validation?.cancel_delete || 'Cancel'}
						</button>
					</div>
				{:else}
					<button
						onclick={() => (showDeleteConfirm = true)}
						class="inline-flex items-center px-4 py-2 border border-red-300 text-red-600 rounded-lg hover:bg-red-50 transition-colors text-sm"
					>
						<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
						</svg>
						{$t.validation?.delete_task_confirm?.split('"')[0]?.trim() || 'Delete'}
					</button>
				{/if}
			</div>
		</div>
	</div>

	<!-- Run History Section -->
	<div class="flex items-center justify-between mb-4">
		<h2 class="text-lg font-semibold text-gray-900">{$t.validation?.run_history || 'Run History'}</h2>
		{#if uxState === 'populated' || uxState === 'empty'}
			<button
				onclick={loadRunHistory}
				class="inline-flex items-center px-3 py-1.5 text-sm border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
			>
				<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
				</svg>
				{$t.common?.refresh || 'Refresh'}
			</button>
		{/if}
	</div>

	<!-- Loading State -->
	{#if uxState === 'loading'}
		<div class="space-y-3">
			{#each Array(4) as _, i (i)}
				<div class="h-14 bg-gray-100 rounded-lg animate-pulse"></div>
			{/each}
		</div>

	<!-- Error State -->
	{:else if uxState === 'error'}
		<div class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
			<p class="text-red-700 mb-3">{errorMsg}</p>
			<button
				onclick={loadRunHistory}
				class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
			>
				{$t.validation?.retry || 'Retry'}
			</button>
		</div>

	<!-- Empty State -->
	{:else if uxState === 'empty'}
		<div class="bg-gray-50 border border-dashed border-gray-300 rounded-lg p-12 text-center">
			<svg class="w-16 h-16 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
			</svg>
			<p class="text-gray-500 mb-2">{$t.validation?.run_history_empty || 'No runs for this task yet.'}</p>
			<p class="text-sm text-gray-400">{$t.validation?.run_history_empty_hint || 'Click "Run Now" above to start a validation run.'}</p>
		</div>

	<!-- Populated State -->
	{:else if uxState === 'populated'}
		<div class="bg-white border border-gray-200 rounded-lg overflow-hidden">
			<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?.timestamp || 'Date/Time'}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.trigger_manual?.split(' ')[0] || 'Trigger'}</th>
						<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?.summary || 'Aggregate'}</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-right text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.validation?.actions || 'Actions'}</th>
					</tr>
				</thead>
				<tbody class="bg-white divide-y divide-gray-200">
					{#each runs as run (run.id)}
						<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
						<tr
							onclick={() => handleViewRun(run.id)}
							onkeydown={(e) => { if (e.key === 'Enter') handleViewRun(run.id); }}
							role="button"
							tabindex="0"
							class="hover:bg-gray-50 cursor-pointer transition-colors"
						>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
								{run.timestamp || run.started_at || run.created_at
									? new Date(run.timestamp || run.started_at || run.created_at).toLocaleString()
									: '-'}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
								{getTriggerLabel(run.trigger)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap">
								<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {getRunStatusBadgeClass(run.status)}">
									{run.status || 'UNKNOWN'}
								</span>
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
								{getAggregateSummary(run)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
								{formatDuration(run.duration_ms)}
							</td>
							<td class="px-4 py-3 whitespace-nowrap text-right">
								<button
									onclick={(e) => { e.stopPropagation(); handleViewRun(run.id); }}
									class="text-blue-600 hover:text-blue-700 text-sm font-medium"
								>
									{$t.validation?.view_report || 'View Report'}
								</button>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>

		<!-- Pagination -->
		{#if total > pageSize}
			<div class="flex items-center justify-between mt-4">
				<p class="text-sm text-gray-500">
					{($t.validation?.showing || 'Showing {count} of {total}')
						.replace('{count}', String(runs.length))
						.replace('{total}', String(total))}
				</p>
				<div class="flex gap-2">
					<button
						onclick={() => handlePageChange(currentPage - 1)}
						disabled={currentPage <= 1}
						class="px-3 py-1.5 text-sm border border-gray-200 rounded-lg disabled:opacity-50 hover:bg-gray-50"
					>
						{$t.validation?.previous || 'Previous'}
					</button>
					<button
						onclick={() => handlePageChange(currentPage + 1)}
						disabled={currentPage * pageSize >= total}
						class="px-3 py-1.5 text-sm border border-gray-200 rounded-lg disabled:opacity-50 hover:bg-gray-50"
					>
						{$t.validation?.next || 'Next'}
					</button>
				</div>
			</div>
		{/if}
	{/if}
</div>
<!-- #endregion ValidationTaskDetailPage -->
