<!-- #region UnifiedReportsPage [C:3] [TYPE Page] [SEMANTICS sveltekit, report, filter, task, detail] -->
<!-- @BRIEF Unified reports page with task-type and status filtering, list selection, detail panel, and resilient UX states for mixed task types. -->
<!-- @LAYER Page -->
<!-- @RELATION DEPENDS_ON -> [ReportsApi] -->
<!-- @RELATION DEPENDS_ON -> [EXT:frontend:ReportsList] -->
<!-- @RELATION DEPENDS_ON -> [EXT:frontend:ReportDetailPanel] -->
<!-- @RELATION DEPENDS_ON -> [PageHeader] -->
<!-- @UX_STATE Loading -> Skeleton block visible; filters remain interactive. -->
<!-- @UX_STATE Ready -> Reports list rendered with selected report detail. -->
<!-- @UX_STATE NoData -> Friendly empty state for total=0 without filters. -->
<!-- @UX_STATE FilteredEmpty -> Filtered empty state with one-click clear. -->
<!-- @UX_STATE Error -> Inline error with retry preserving filter selections. -->
<!-- @UX_FEEDBACK Filter change immediately reloads the list. -->
<!-- @UX_FEEDBACK Selecting a report loads its detail in the right panel. -->
<!-- @UX_RECOVERY Retry and clear-filters actions available. -->
<script lang="ts">
  import { onMount } from "svelte";
  import { t } from "$lib/i18n/index.svelte.js";
  import { PageHeader } from "$lib/ui";
  import { getReports, getReportDetail } from "$lib/api/reports.js";
  import ReportsList from "$lib/components/reports/ReportsList.svelte";
  import ReportDetailPanel from "$lib/components/reports/ReportDetailPanel.svelte";

  let loading = true;
  let error = "";
  let collection = null;
  let selectedReport = null;
  let selectedReportDetail = null;

  let taskType = "all";
  let status = "all";
  let page = 1;
  const pageSize = 20;

  const TASK_TYPE_OPTIONS = [
    { value: "all", label: $t.reports?.all_types },
    { value: "llm_verification", label: "LLM" },
    { value: "backup", label: $t.nav?.backups },
    { value: "migration", label: $t.nav?.migration },
    { value: "documentation", label: "Documentation" },
  ];

  const STATUS_OPTIONS = [
    { value: "all", label: $t.reports?.all_statuses },
    { value: "success", label: "Success" },
    { value: "failed", label: "Failed" },
    { value: "in_progress", label: "In progress" },
    { value: "partial", label: "Partial" },
  ];

  function buildQuery() {
    return {
      page,
      page_size: pageSize,
      task_types: taskType === "all" ? [] : [taskType],
      statuses: status === "all" ? [] : [status],
      sort_by: "updated_at",
      sort_order: "desc",
    };
  }

  async function loadReports({ silent = false } = {}) {
    try {
      if (!silent) loading = true;
      error = "";
      collection = await getReports(buildQuery());
      if (!selectedReport && collection?.items?.length) {
        selectedReport = collection.items[0];
        selectedReportDetail = await getReportDetail(selectedReport.report_id);
      }
    } catch (e) {
      error = e?.message || "Failed to load reports";
      collection = null;
    } finally {
      if (!silent) loading = false;
    }
  }

  function hasActiveFilters() {
    return taskType !== "all" || status !== "all";
  }

  function clearFilters() {
    taskType = "all";
    status = "all";
    page = 1;
    selectedReport = null;
    selectedReportDetail = null;
    loadReports();
  }

  function onFilterChange() {
    page = 1;
    selectedReport = null;
    selectedReportDetail = null;
    loadReports();
  }

  async function onSelectReport(event) {
    const payload = event?.report ?? event?.detail?.report;
    if (!payload) return;
    selectedReport = payload;
    selectedReportDetail = await getReportDetail(selectedReport.report_id);
  }

  onMount(() => {
    loadReports();
  });
</script>

<div class="mx-auto w-full max-w-7xl space-y-4">
  <PageHeader
    title={$t.reports?.title}
    subtitle={() => null}
    actions={() => null}
  />

  <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
    <div class="grid grid-cols-1 gap-2 md:grid-cols-4">
      <select
        bind:value={taskType}
        onchange={onFilterChange}
        class="rounded-md border border-slate-300 px-2 py-1.5 text-sm"
      >
        {#each TASK_TYPE_OPTIONS as option}
          <option value={option.value}>{option.label}</option>
        {/each}
      </select>

      <select
        bind:value={status}
        onchange={onFilterChange}
        class="rounded-md border border-slate-300 px-2 py-1.5 text-sm"
      >
        {#each STATUS_OPTIONS as option}
          <option value={option.value}>{option.label}</option>
        {/each}
      </select>

      <button
        class="inline-flex items-center justify-center rounded-lg border border-slate-300 px-3 py-1.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50"
        onclick={() => loadReports()}
      >
        {$t.common?.refresh}
      </button>

      <button
        class="inline-flex items-center justify-center rounded-lg border border-slate-300 px-3 py-1.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50"
        onclick={clearFilters}
      >
        {$t.reports?.clear_filters}
      </button>
    </div>
  </div>

  {#if loading}
    <div
      class="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm"
    >
      {$t.reports?.loading}
    </div>
  {:else if error}
    <div
      class="rounded-xl border border-destructive-light bg-destructive-light p-4 text-red-700 shadow-sm"
    >
      <p>{error}</p>
      <button
        class="mt-2 inline-flex items-center justify-center rounded-lg border border-red-300 px-3 py-1 text-sm font-medium text-red-700 transition-colors hover:bg-red-100"
        onclick={() => loadReports()}
      >
        {$t.reports?.retry_load || $t.common?.retry}
      </button>
    </div>
  {:else if !collection || collection.total === 0}
    <div
      class="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm"
    >
      {$t.reports?.empty}
    </div>
  {:else if collection.items.length === 0 && hasActiveFilters()}
    <div
      class="rounded-xl border border-slate-200 bg-white p-6 text-sm text-slate-500 shadow-sm"
    >
      <p>{$t.reports?.filtered_empty}</p>
      <button
        class="mt-2 inline-flex items-center justify-center rounded-lg border border-slate-300 px-3 py-1 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50"
        onclick={clearFilters}
      >
        {$t.reports?.clear_filters}
      </button>
    </div>
  {:else}
    <div class="grid grid-cols-1 gap-4 lg:grid-cols-3">
      <div class="lg:col-span-2">
        <ReportsList
          reports={collection?.items || []}
          selectedReportId={selectedReport?.report_id}
          onselect={onSelectReport}
        />
      </div>
      <ReportDetailPanel detail={selectedReportDetail} />
    </div>
  {/if}
</div>

<!-- #endregion UnifiedReportsPage -->
