<!-- #region ValidationRunDetailPage [C:4] [TYPE Page] [SEMANTICS validation,run,detail,dashboard,collapsible] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Validation run detail — renders ValidationRunDetailModel state. -->
<!-- @LAYER Page -->
<!-- @RELATION BINDS_TO -> [ValidationRunDetailModel] -->
<script lang="ts">
  import { goto } from '$app/navigation';
  import { ROUTES } from '$lib/routes';
  import { t, _ } from '$lib/i18n/index.svelte.js';
  import { page } from '$app/state';
  import { EmptyState, Icon } from '$lib/ui';
  import { ValidationRunDetailModel } from '$lib/models/ValidationRunDetailModel.svelte';

  let { data } = $props();

  const m = new ValidationRunDetailModel();
  m.run = data.run;

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

  const { getStatusDotClass, getStatusDot, getSeverityClass, formatDuration, getTriggerLabel, getPathLabel, getPathBadgeClass, getTabIssueSeverity } = ValidationRunDetailModel;

  function handleBack() { goto(ROUTES.validationTasks.detail(policyId)); }

  $effect(() => {
    const expanded = Array.from(m.expandedDashboards);
    for (const dId of expanded) {
      const db = m.dashboards.find((d: Record<string,unknown>) => d.id === dId || d.dashboard_id === dId) as Record<string,unknown>;
      if (!db) continue;
      const selectedTabIdx = parseInt(m.selectedScreenshotTab[dId] || '0', 10);
      const screenshots = (db.screenshots || db.path || []) as unknown[];
      if (screenshots.length > 0) {
        const screenEntry = screenshots[selectedTabIdx] as Record<string,unknown> | undefined;
        if (screenEntry) {
          const path = screenEntry.path || String(screenEntry || screenshots[selectedTabIdx]);
          const tabKey = `${dId}_${selectedTabIdx}`;
          if (!m.screenshotUrls[tabKey]) m.loadScreenshot(String(path), tabKey);
        }
      }
    }
  });
</script>

<div class="max-w-7xl mx-auto px-4 py-6">
  <button onclick={handleBack} class="flex items-center gap-2 text-text-muted hover:text-text transition-colors mb-4">
    <Icon name="back" size={20} strokeWidth={2} />
    {$t.validation?.back_to_policy || 'Back to policy'}
  </button>

  {#if m.uxState === 'not_found'}
    <EmptyState title={$t.validation?.run_not_found || 'Run not found'} />
  {:else if m.uxState === 'error'}
    <div class="bg-destructive-light border border-destructive-ring rounded-lg p-6 text-center">
      <p class="text-destructive mb-3">{m.errorMsg || $t.validation?.load_runs_failed || 'Failed to load run details.'}</p>
      <button onclick={() => window.location.reload()} class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors">{$t.validation?.retry || 'Retry'}</button>
    </div>
  {:else if m.run}
    <!-- Stats bar -->
    <div class="grid grid-cols-2 sm:grid-cols-5 gap-3 mb-6">
      <div class="bg-surface-card border border-border rounded-lg p-3 text-center"><p class="text-2xl font-bold text-success">{m.passCount}</p><p class="text-xs text-text-muted">PASS</p></div>
      <div class="bg-surface-card border border-border rounded-lg p-3 text-center"><p class="text-2xl font-bold text-warning">{m.warnCount}</p><p class="text-xs text-text-muted">WARN</p></div>
      <div class="bg-surface-card border border-border rounded-lg p-3 text-center"><p class="text-2xl font-bold text-destructive">{m.failCount}</p><p class="text-xs text-text-muted">FAIL</p></div>
      <div class="bg-surface-card border border-border rounded-lg p-3 text-center"><p class="text-2xl font-bold text-text-subtle">{m.unknownCount}</p><p class="text-xs text-text-muted">UNKNOWN</p></div>
      <div class="bg-surface-card border border-border rounded-lg p-3 text-center"><p class="text-2xl font-bold text-info">{m.totalIssues}</p><p class="text-xs text-text-muted">{$t.validation?.issues || 'Issues'}</p></div>
    </div>

    <!-- Run header -->
    <div class="bg-surface-card border border-border rounded-lg p-4 mb-4">
      <div class="flex flex-wrap items-center gap-3 text-sm">
        <span class="font-semibold text-text">{m.run.id}</span>
        <span class="inline-flex px-2 py-0.5 text-xs rounded-full {getStatusDotClass(m.run.status)}">{getStatusDot(m.run.status)} {m.run.status}</span>
        {#if m.run.trigger_type}<span class="text-text-muted">{getTriggerLabel(m.run.trigger_type, _)}</span>{/if}
        <span class="text-text-subtle">{m.run.started_at ? new Date(m.run.started_at as string).toLocaleString() : ''}</span>
        {#if m.run.finished_at}<span class="text-text-subtle">→ {new Date(m.run.finished_at as string).toLocaleString()}</span>{/if}
        {#if m.run.started_at && m.run.finished_at}<span class="text-text-muted font-mono text-xs">{formatDuration((new Date(m.run.finished_at as string).getTime() - new Date(m.run.started_at as string).getTime()))}</span>{/if}
      </div>
    </div>

    <!-- Dashboard results -->
    <div class="space-y-4">
      {#each m.dashboards as dashboard (dashboard.id || dashboard.dashboard_id)}
        <div class="bg-surface-card border border-border rounded-lg overflow-hidden">
          <!-- Dashboard header (clickable) -->
          <button class="w-full flex items-center justify-between px-4 py-3 hover:bg-surface-muted transition-colors text-left" onclick={() => m.toggleDashboard(dashboard.id || dashboard.dashboard_id)}>
            <div class="flex items-center gap-3">
              <Icon name="chevronRight" size={20} class={`transition-transform ${m.isDashboardExpanded(dashboard.id || dashboard.dashboard_id) ? 'rotate-90' : ''}`} strokeWidth={2} />
              <span class="font-medium text-text">{dashboard.title || dashboard.slug || dashboard.dashboard_id}</span>
            </div>
            <div class="flex items-center gap-3">
              {#if dashboard.path}
                <span class={`px-2 py-0.5 text-xs rounded-full ${getPathBadgeClass(dashboard.path)}`}>{getPathLabel(dashboard.path, _)}</span>
              {/if}
              <span class={`px-2 py-0.5 text-xs rounded-full font-semibold uppercase ${getStatusDotClass(dashboard.status)}`}>{dashboard.status}</span>
              {#if dashboard.duration_ms}<span class="text-xs text-text-muted font-mono">{formatDuration(dashboard.duration_ms)}</span>{/if}
            </div>
          </button>

          {#if m.isDashboardExpanded(dashboard.id || dashboard.dashboard_id)}
            <div class="border-t border-border px-4 py-3 space-y-4">
              <!-- Tabs + Screenshots -->
              {#if dashboard.tabs?.length}
                {@const selectedIdx = parseInt(m.selectedScreenshotTab[dashboard.id || dashboard.dashboard_id] || '0', 10)}
                <div>
                  <div class="flex gap-1 mb-3 flex-wrap">
                    {#each dashboard.tabs as tab, tabIdx}
                      {@const issueInfo = getTabIssueSeverity(tab.label || '', tabIdx, dashboard.tabs?.length || 0, dashboard.issues || [])}
                      <button
                        onclick={() => { m.selectedScreenshotTab = { ...m.selectedScreenshotTab, [dashboard.id || dashboard.dashboard_id]: String(tabIdx) }; }}
                        class="relative px-3 py-1.5 text-xs rounded-md transition-colors {String(tabIdx) === (m.selectedScreenshotTab[dashboard.id || dashboard.dashboard_id] || '0') ? 'bg-primary-light text-primary border border-primary-ring' : 'bg-surface-muted text-text-muted border border-border hover:bg-surface-page'}"
                      >
                        {tab.label || `Tab ${tabIdx + 1}`}
                        {#if issueInfo}
                          <span class={`ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full text-[9px] font-bold ${issueInfo.severity === 'FAIL' ? 'bg-destructive text-white' : issueInfo.severity === 'WARN' ? 'bg-warning text-white' : 'bg-primary-light text-primary'}`}>{issueInfo.count}</span>
                        {/if}
                      </button>
                    {/each}
                  </div>
                  {#if dashboard.screenshots?.length}
                    {@const screenEntry = dashboard.screenshots[selectedIdx || 0]}
                    {#if screenEntry}
                      <div class="rounded-lg border border-border overflow-hidden">
                        {#if m.screenshotUrls[`${dashboard.id || dashboard.dashboard_id}_${selectedIdx || 0}`]}
                          <img src={m.screenshotUrls[`${dashboard.id || dashboard.dashboard_id}_${selectedIdx || 0}`]} alt="Screenshot" class="w-full object-cover max-h-96" />
                        {:else}
                          <div class="h-64 flex items-center justify-center bg-surface-muted text-text-subtle text-sm animate-pulse">{$t.validation?.loading_screenshot || 'Loading screenshot...'}</div>
                        {/if}
                      </div>
                    {/if}
                  {/if}
                </div>
              {/if}

              <!-- Issues -->
              {#if dashboard.issues?.length}
                <div>
                  <h4 class="text-sm font-semibold text-text mb-2">{$t.validation?.issues || 'Issues'} ({dashboard.issues.length})</h4>
                  <div class="space-y-1.5">
                    {#each dashboard.issues as issue}
                      <div class="flex items-start gap-2 rounded-md px-3 py-2 {getSeverityClass(issue.severity)}">
                        <span class="text-[10px] font-bold uppercase mt-0.5 shrink-0">{issue.severity || 'INFO'}</span>
                        <span class="text-xs">{issue.message || '-'}</span>
                        {#if issue.location}<span class="text-[10px] text-text-subtle ml-auto shrink-0">{issue.location}</span>{/if}
                      </div>
                    {/each}
                  </div>
                </div>
              {/if}

              <!-- Logs sent to LLM -->
              {#if dashboard.logs_sent_to_llm?.length}
                <div>
                  <button class="text-xs font-medium text-primary hover:underline" onclick={() => m.toggleLogsSent(dashboard.id || dashboard.dashboard_id)}>
                    {m.logsSentExpanded.has(dashboard.id || dashboard.dashboard_id) ? '▾' : '▸'} {$t.validation?.logs_sent || 'Logs sent to LLM'} ({dashboard.logs_sent_to_llm.length})
                  </button>
                  {#if m.logsSentExpanded.has(dashboard.id || dashboard.dashboard_id)}
                    <pre class="mt-2 max-h-48 overflow-auto rounded-lg bg-terminal-bg p-3 text-xs text-text-subtle">{dashboard.logs_sent_to_llm.join('\n')}</pre>
                  {/if}
                </div>
              {/if}

              <!-- Task execution logs -->
              <div>
                <button class="text-xs font-medium text-primary hover:underline" onclick={() => m.toggleTaskLogs(`tasklogs_${dashboard.id || dashboard.dashboard_id}`)}>
                  {m.taskLogsExpanded.has(`tasklogs_${dashboard.id || dashboard.dashboard_id}`) ? '▾' : '▸'} {$t.validation?.task_logs || 'Task execution logs'}
                </button>
                {#if m.taskLogsExpanded.has(`tasklogs_${dashboard.id || dashboard.dashboard_id}`) && (dashboard as Record<string,unknown>).task_logs}
                  <div class="mt-2 max-h-64 overflow-auto rounded-lg border border-border">
                    <table class="min-w-full divide-y divide-border text-xs">
                      <thead class="bg-surface-page">
                        <tr>
                          <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.validation?.time || 'Time'}</th>
                          <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.validation?.level || 'Level'}</th>
                          <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.validation?.source || 'Source'}</th>
                          <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.validation?.message || 'Message'}</th>
                        </tr>
                      </thead>
                      <tbody class="divide-y divide-border">
                        {#each (dashboard as Record<string,unknown>).task_logs as logEntry}
                          <tr>
                            <td class="px-3 py-2 align-top text-text-muted">{new Date((logEntry as Record<string,unknown>).timestamp as string).toLocaleString()}</td>
                            <td class="px-3 py-2 align-top text-text">{(logEntry as Record<string,unknown>).level || '-'}</td>
                            <td class="px-3 py-2 align-top text-text">{(logEntry as Record<string,unknown>).source || '-'}</td>
                            <td class="px-3 py-2 align-top text-text whitespace-pre-wrap">{(logEntry as Record<string,unknown>).message || '-'}</td>
                          </tr>
                        {/each}
                      </tbody>
                    </table>
                  </div>
                {:else if m.taskLogsExpanded.has(`tasklogs_${dashboard.id || dashboard.dashboard_id}`)}
                  <div class="mt-2 text-xs text-text-muted animate-pulse">{$t.validation?.loading_logs || 'Loading logs...'}</div>
                {/if}
              </div>
            </div>
          {/if}
        </div>
      {/each}
    </div>
  {/if}
</div>
<!-- #endregion ValidationRunDetailPage -->
