<!-- #region LLMReportPage [C:3] [TYPE Page] [SEMANTICS sveltekit, llm, report, validation, screenshot] -->
<!-- @ingroup Routes -->
<!-- @BRIEF LLM validation report page — renders LLMReportModel state, delegates all logic to the model. -->
<!-- @LAYER Page -->
<!-- @RELATION BINDS_TO -> [LLMReportModel] -->
<!-- @UX_STATE loading -> Skeleton placeholders visible. -->
<!-- @UX_STATE loaded  -> Full report with durations, screenshots, sent logs and task logs. -->
<!-- @UX_STATE error   -> Alert with retry action. -->
<!-- @UX_FEEDBACK Refresh button reloads report payload. -->
<!-- @UX_RECOVERY Retry via refresh button after API error. -->
<script lang="ts">
  import { onDestroy, onMount, untrack } from 'svelte';
  import { page } from '$app/state';
  import { goto } from '$app/navigation';
  import { ROUTES } from '$lib/routes';
  import { t } from '$lib/i18n/index.svelte.js';
  import { openDrawerForTask } from '$lib/stores/taskDrawer.svelte.js';
  import Icon from '$lib/ui/Icon.svelte';
  import { LLMReportModel } from '$lib/models/LLMReportModel.svelte';

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

  const model = new LLMReportModel();

  $effect(() => {
    model.taskId = taskId;
  });

  function backToReports() {
    goto(ROUTES.reports.list());
  }

  function openTaskDetails() {
    if (!taskId) return;
    openDrawerForTask(taskId);
  }

  const { formatDate, formatMs, getCheckResultClasses } = LLMReportModel;

  onMount(async () => {
    await model.loadReport();
  });

  onDestroy(() => {
    model.cleanupBlobs();
  });

  $effect(() => {
    const paths = model.screenshotPaths;
    untrack(() => {
      void model.loadScreenshotBlobs(paths);
    });
  });
</script>

<div class="mx-auto w-full max-w-7xl space-y-6">
  <div class="flex items-start justify-between">
    <div>
      <button
        class="inline-flex items-center gap-2 rounded-lg px-2 py-1 text-sm text-text-muted transition-colors hover:bg-surface-muted hover:text-text"
        onclick={backToReports}
      >
        <Icon name="chevronLeft" size={16} />
        {$t.nav?.reports || "Reports"}
      </button>
      <h1 class="mt-2 text-2xl font-bold text-text">
        {$t.tasks?.result_llm_validation || "LLM Validation Report"}
      </h1>
      <p class="mt-1 text-sm text-text-muted">{$t.reports?.llm_task_id?.replace("{taskId}", taskId) || `Task: ${taskId}`}</p>
    </div>
    <div class="flex items-center gap-2">
      <button
        class="inline-flex items-center justify-center rounded-lg border border-border-strong bg-surface-card px-4 py-2 text-sm font-medium text-text transition-colors hover:bg-surface-page"
        onclick={openTaskDetails}
      >
        {$t.tasks?.details_logs || "Task details and logs"}
      </button>
      <button
        class="inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-hover"
        onclick={() => model.refresh()}
      >
        {$t.common?.refresh || "Refresh"}
      </button>
    </div>
  </div>

  {#if model.error}
    <div class="rounded-lg border border-destructive-ring bg-destructive-light px-4 py-3 text-destructive">
      <div>{model.error}</div>
    </div>
  {/if}

  {#if model.screenState === 'loading'}
    <div class="space-y-3">
      <div class="h-24 animate-pulse rounded-xl border border-border bg-surface-card"></div>
      <div class="h-64 animate-pulse rounded-xl border border-border bg-surface-card"></div>
      <div class="h-64 animate-pulse rounded-xl border border-border bg-surface-card"></div>
    </div>
  {:else if model.task}
    <!-- Stats row -->
    <div class="grid grid-cols-1 gap-4 md:grid-cols-5">
      <div class="rounded-xl border border-border bg-surface-card p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_status || "Status"}</p>
        <p class="mt-2 text-lg font-semibold text-text">{model.task?.status || "-"}</p>
      </div>
      <div class="rounded-xl border border-border bg-surface-card p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_dashboard_check || "Dashboard check"}</p>
        <span class={`mt-2 inline-flex items-center gap-1 rounded-full border px-2 py-1 text-sm font-semibold uppercase ${getCheckResultClasses(model.checkResult.level)}`}>
          <span class="inline-flex min-w-[18px] items-center justify-center rounded-full bg-surface-card/70 px-1 text-[10px] font-bold">{model.checkResult.icon}</span>
          {model.checkResult.label}
        </span>
      </div>
      <div class="rounded-xl border border-border bg-surface-card p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-text-muted">{$t.common?.started || "Started"}</p>
        <p class="mt-2 text-sm font-semibold text-text">{formatDate(model.task?.started_at)}</p>
      </div>
      <div class="rounded-xl border border-border bg-surface-card p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-text-muted">{$t.common?.finished || "Finished"}</p>
        <p class="mt-2 text-sm font-semibold text-text">{formatDate(model.task?.finished_at)}</p>
      </div>
      <div class="rounded-xl border border-border bg-surface-card p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-text-muted">{$t.common?.duration || "Duration"}</p>
        <p class="mt-2 text-lg font-semibold text-text">{formatMs(model.timings?.validation_duration_ms)}</p>
      </div>
    </div>

    <!-- Text report -->
    <div class="rounded-xl border border-border bg-surface-card p-4">
      <h2 class="text-sm font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_text_report || "Text Report"}</h2>
      <p class="mt-2 text-sm text-text">{model.result?.summary || "-"}</p>
      {#if Array.isArray(model.result?.issues) && model.result.issues.length > 0}
        <div class="mt-4 space-y-2">
          {#each model.result.issues as issue}
            <div class="rounded-lg border border-border bg-surface-page p-3 text-sm">
              <div class="font-semibold text-text">{issue?.severity || "INFO"}</div>
              <div class="text-text">{issue?.message || "-"}</div>
              {#if issue?.location}
                <div class="text-xs text-text-muted">{$t.reports?.llm_location?.replace("{location}", issue.location) || `Location: ${issue.location}`}</div>
              {/if}
            </div>
          {/each}
        </div>
      {/if}
    </div>

    <!-- Screenshots -->
    <div class="rounded-xl border border-border bg-surface-card p-4">
      <h2 class="text-sm font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_screenshots || "Screenshots"}</h2>
      {#if model.screenshotPaths.length === 0}
        <p class="mt-2 text-sm text-text-muted">{$t.reports?.llm_no_screenshots || "No screenshots saved."}</p>
      {:else}
        <div class="mt-3 grid grid-cols-1 gap-4 lg:grid-cols-2">
          {#each model.screenshotPaths as path}
            <button
              type="button"
              class="block w-full text-left"
              onclick={() => model.openScreenshot(path)}
              disabled={!model.screenshotBlobUrls[path]}
            >
              {#if model.screenshotBlobUrls[path]}
                <img
                  src={model.screenshotBlobUrls[path]}
                  alt={$t.reports?.llm_screenshots || "Validation screenshot"}
                  class="h-64 w-full rounded-lg border border-border object-cover"
                />
              {:else}
                <div class="flex h-64 w-full items-center justify-center rounded-lg border border-destructive-ring bg-destructive-light px-4 text-sm text-destructive">
                  {model.screenshotLoadErrors[path] || $t.reports?.llm_failed_screenshot || "Failed to load screenshot"}
                </div>
              {/if}
              <p class="mt-1 truncate text-xs text-text-muted">{path}</p>
            </button>
          {/each}
        </div>
      {/if}
    </div>

    <!-- Logs sent to LLM -->
    <div class="rounded-xl border border-border bg-surface-card p-4">
      <h2 class="text-sm font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_logs_sent?.replace("{count}", model.sentLogs.length) || `Logs sent to LLM (${model.sentLogs.length})`}</h2>
      {#if model.sentLogs.length === 0}
        <p class="mt-2 text-sm text-text-muted">{$t.reports?.llm_no_source_logs || "No source logs were attached."}</p>
      {:else}
        <pre class="mt-3 max-h-80 overflow-auto rounded-lg bg-terminal-bg p-3 text-xs text-text-subtle">{model.sentLogs.join("\n")}</pre>
      {/if}
    </div>

    <!-- Task execution logs -->
    <div class="rounded-xl border border-border bg-surface-card p-4">
      <h2 class="text-sm font-semibold uppercase tracking-wide text-text-muted">{$t.reports?.llm_task_logs?.replace("{count}", model.logs.length) || `Task execution logs (${model.logs.length})`}</h2>
      {#if model.logs.length === 0}
        <p class="mt-2 text-sm text-text-muted">{$t.reports?.llm_no_task_logs || "No task logs available."}</p>
      {:else}
        <div class="mt-3 max-h-96 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.reports?.llm_time || "Time"}</th>
                <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.reports?.llm_level || "Level"}</th>
                <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.reports?.llm_source || "Source"}</th>
                <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.reports?.llm_message || "Message"}</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-border">
              {#each model.logs as logEntry}
                <tr>
                  <td class="px-3 py-2 align-top text-text-muted">{formatDate(logEntry?.timestamp)}</td>
                  <td class="px-3 py-2 align-top text-text">{logEntry?.level || "-"}</td>
                  <td class="px-3 py-2 align-top text-text">{logEntry?.source || "-"}</td>
                  <td class="px-3 py-2 align-top text-text whitespace-pre-wrap">{logEntry?.message || "-"}</td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {/if}
    </div>
  {/if}
</div>
<!-- #endregion LLMReportPage -->
