<!-- [DEF:DashboardDetail:Page] -->
<script>
  /**
   * @TIER: CRITICAL
   * @PURPOSE: Dashboard Detail View - Overview of charts and datasets linked to a dashboard
   * @LAYER: UI
   * @RELATION: BINDS_TO -> dashboard detail API
   * @INVARIANT: Shows dashboard metadata, charts, and datasets for selected environment
   * @TEST_DATA: dashboard_detail_ready -> {"dashboard":{"id":11,"title":"Ops","chart_count":3,"dataset_count":2},"taskHistory":[{"id":"t-1","plugin_id":"llm_dashboard_validation","status":"SUCCESS"}],"llmStatus":{"configured":true,"reason":"ok"}}
   * @TEST_DATA: llm_unconfigured -> {"llmStatus":{"configured":false,"reason":"invalid_api_key"}}
   *
   * @TEST_CONTRACT Page_DashboardDetail ->
   * {
   *   required_props: {},
   *   optional_props: {},
   *   invariants: [
   *       "Loads specific dashboard details directly via the API leveraging the id parameter",
   *       "Triggers LLM validation gracefully respecting llmReady status"
   *   ]
   * }
   * @TEST_FIXTURE init_state -> {"id": "1", "env_id": "env1"}
   * @TEST_INVARIANT dashboard_fetching -> verifies: [init_state]
   */

  import { onMount, onDestroy } from "svelte";
  import { goto } from "$app/navigation";
  import { page } from "$app/stores";
  import { t } from "$lib/i18n";
  import { api } from "$lib/api.js";
  import { openDrawerForTask } from "$lib/stores/taskDrawer.js";
  import { addToast } from "$lib/toasts.js";
  import Icon from "$lib/ui/Icon.svelte";

  $: dashboardId = $page.params.id;
  $: envId = $page.url.searchParams.get("env_id") || "";

  let dashboard = null;
  let isLoading = true;
  let error = null;
  let taskHistory = [];
  let isTaskHistoryLoading = false;
  let taskHistoryError = null;
  let isStartingBackup = false;
  let isStartingValidation = false;
  let thumbnailUrl = "";
  let isThumbnailLoading = false;
  let thumbnailError = null;
  let llmReady = true;
  let llmStatusReason = "";

  onMount(async () => {
    await loadDashboardPage();
  });

  onDestroy(() => {
    releaseThumbnailUrl();
  });

  async function loadDashboardPage() {
    await Promise.all([
      loadDashboardDetail(),
      loadTaskHistory(),
      loadThumbnail(false),
      loadLlmStatus(),
    ]);
  }

  async function loadDashboardDetail() {
    if (!dashboardId || !envId) {
      error = $t.dashboard?.missing_context;
      isLoading = false;
      return;
    }

    isLoading = true;
    error = null;
    try {
      dashboard = await api.getDashboardDetail(envId, dashboardId);
    } catch (err) {
      error = err.message || $t.dashboard?.load_detail_failed;
      console.error("[DashboardDetail][Coherence:Failed]", err);
    } finally {
      isLoading = false;
    }
  }

  async function loadTaskHistory() {
    if (!dashboardId || !envId) return;
    isTaskHistoryLoading = true;
    taskHistoryError = null;
    try {
      const response = await api.getDashboardTaskHistory(envId, dashboardId, {
        limit: 30,
      });
      taskHistory = response?.items || [];
    } catch (err) {
      taskHistoryError = err.message || "Failed to load task history";
      taskHistory = [];
    } finally {
      isTaskHistoryLoading = false;
    }
  }

  function releaseThumbnailUrl() {
    if (thumbnailUrl) {
      URL.revokeObjectURL(thumbnailUrl);
      thumbnailUrl = "";
    }
  }

  async function loadThumbnail(force = false) {
    if (!dashboardId || !envId) return;
    isThumbnailLoading = true;
    thumbnailError = null;
    try {
      const blob = await api.getDashboardThumbnail(envId, dashboardId, {
        force,
      });
      releaseThumbnailUrl();
      thumbnailUrl = URL.createObjectURL(blob);
    } catch (err) {
      if (err?.status === 202) {
        thumbnailError =
          $t.dashboard?.thumbnail_generating || "Thumbnail is being generated";
      } else {
        thumbnailError =
          err.message ||
          $t.dashboard?.thumbnail_failed ||
          "Failed to load thumbnail";
      }
    } finally {
      isThumbnailLoading = false;
    }
  }

  async function runBackupTask() {
    if (isStartingBackup || !envId || !dashboardId) return;
    isStartingBackup = true;
    try {
      const response = await api.postApi("/dashboards/backup", {
        env_id: envId,
        dashboard_ids: [Number(dashboardId)],
      });
      const taskId = response?.task_id;
      if (taskId) {
        openDrawerForTask(taskId);
        addToast(
          $t.dashboard?.backup_started || "Backup task started",
          "success",
        );
      }
      await loadTaskHistory();
    } catch (err) {
      addToast(
        err.message ||
          $t.dashboard?.backup_task_failed ||
          "Failed to start backup",
        "error",
      );
    } finally {
      isStartingBackup = false;
    }
  }

  async function runLlmValidationTask() {
    if (!llmReady) {
      addToast(
        $t.dashboard?.llm_not_configured || "LLM is not configured",
        "error",
      );
      return;
    }
    if (isStartingValidation || !envId || !dashboardId) return;
    isStartingValidation = true;
    try {
      const response = await api.postApi("/tasks", {
        plugin_id: "llm_dashboard_validation",
        params: {
          dashboard_id: String(dashboardId),
          environment_id: envId,
        },
      });
      const taskId = response?.task_id || response?.id;
      if (taskId) {
        openDrawerForTask(taskId);
        addToast(
          $t.dashboard?.validation_started || "LLM validation started",
          "success",
        );
      }
      await Promise.all([loadTaskHistory(), loadThumbnail(true)]);
    } catch (err) {
      addToast(
        err.message ||
          $t.dashboard?.validation_start_failed ||
          "Failed to start LLM validation",
        "error",
      );
    } finally {
      isStartingValidation = false;
    }
  }

  function openLlmReport(taskId) {
    if (!taskId) return;
    window.open(
      `/reports/llm/${encodeURIComponent(String(taskId))}`,
      "_blank",
      "noopener,noreferrer",
    );
  }

  function toTaskTypeLabel(pluginId) {
    if (pluginId === "superset-backup") return $t.dashboard?.backup || "Backup";
    if (pluginId === "llm_dashboard_validation")
      return $t.dashboard?.llm_check || "LLM Check";
    return pluginId || "-";
  }

  function getTaskStatusClasses(status) {
    const normalized = (status || "").toLowerCase();
    if (normalized === "running" || normalized === "pending")
      return "bg-blue-100 text-blue-700";
    if (normalized === "success") return "bg-emerald-100 text-emerald-700";
    if (normalized === "failed" || normalized === "error")
      return "bg-rose-100 text-rose-700";
    if (normalized === "awaiting_input" || normalized === "waiting_input")
      return "bg-amber-100 text-amber-700";
    return "bg-slate-100 text-slate-700";
  }

  function getValidationStatus(task) {
    if (task?.plugin_id !== "llm_dashboard_validation") {
      return { label: "-", level: "na", icon: "" };
    }
    const rawStatus = String(task?.validation_status || "").toUpperCase();
    if (rawStatus === "FAIL") {
      return { label: "FAIL", level: "fail", icon: "!" };
    }
    if (rawStatus === "WARN") {
      return { label: "WARN", level: "warn", icon: "!" };
    }
    if (rawStatus === "PASS") {
      return { label: "PASS", level: "pass", icon: "OK" };
    }
    return { label: "UNKNOWN", level: "unknown", icon: "?" };
  }

  function getValidationStatusClasses(level) {
    if (level === "fail") return "bg-rose-100 text-rose-700 border-rose-200";
    if (level === "warn") return "bg-amber-100 text-amber-700 border-amber-200";
    if (level === "pass")
      return "bg-emerald-100 text-emerald-700 border-emerald-200";
    if (level === "unknown")
      return "bg-slate-100 text-slate-700 border-slate-200";
    return "bg-slate-50 text-slate-400 border-slate-200";
  }

  function goBack() {
    goto(`/dashboards?env_id=${encodeURIComponent(envId)}`);
  }

  function openDataset(datasetId) {
    goto(`/datasets/${datasetId}?env_id=${encodeURIComponent(envId)}`);
  }

  function formatDate(value) {
    if (!value) return "-";
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return "-";
    return `${parsed.toLocaleDateString()} ${parsed.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
  }

  async function loadLlmStatus() {
    try {
      const status = await api.getLlmStatus();
      llmReady = Boolean(status?.configured);
      llmStatusReason = status?.reason || "";
    } catch (_err) {
      llmReady = false;
      llmStatusReason = "status_unavailable";
    }
  }
</script>

<div class="mx-auto w-full max-w-7xl space-y-6">
  <div class="flex items-center justify-between">
    <div>
      <button
        class="inline-flex items-center gap-2 rounded-lg px-2 py-1 text-sm text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900"
        on:click={goBack}
      >
        <Icon name="chevronLeft" size={16} />
        {$t.common?.back}
      </button>
      <h1 class="mt-2 text-2xl font-bold text-slate-900">
        {dashboard?.title || $t.dashboard?.overview}
      </h1>
      <p class="mt-1 text-sm text-slate-500">
        {$t.common?.id}: {dashboardId}{#if dashboard?.slug}
          • {dashboard.slug}{/if}
      </p>
    </div>
    <div class="flex flex-wrap items-center gap-2">
      <button
        class="inline-flex items-center justify-center rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50"
        on:click={runBackupTask}
        disabled={isStartingBackup}
      >
        {isStartingBackup
          ? $t.common?.loading || "Loading..."
          : $t.dashboard?.run_backup || "Run backup"}
      </button>
      <button
        class="inline-flex items-center justify-center rounded-lg border px-4 py-2 text-sm font-medium transition-colors {llmReady
          ? 'border-indigo-300 bg-indigo-50 text-indigo-700 hover:bg-indigo-100'
          : 'border-rose-300 bg-rose-50 text-rose-700 opacity-70 cursor-not-allowed'}"
        on:click={runLlmValidationTask}
        disabled={isStartingValidation || !llmReady}
        title={!llmReady
          ? $t.dashboard?.llm_not_configured || "LLM is not configured"
          : ""}
      >
        {isStartingValidation
          ? $t.common?.loading || "Loading..."
          : $t.dashboard?.run_llm_check || "Run LLM check"}
      </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"
        on:click={loadDashboardPage}
      >
        {$t.common?.refresh}
      </button>
    </div>
  </div>

  {#if !llmReady}
    <div
      class="rounded-lg border border-rose-300 bg-rose-50 px-4 py-3 text-sm text-rose-800"
    >
      <div class="font-semibold">
        {$t.dashboard?.llm_not_configured || "LLM is not configured"}
      </div>
      <div class="mt-1 text-rose-700">
        {#if llmStatusReason === "no_active_provider"}
          {$t.dashboard?.llm_configure_provider ||
            "No active LLM provider. Configure it in Admin -> LLM Settings."}
        {:else if llmStatusReason === "invalid_api_key"}
          {$t.dashboard?.llm_configure_key ||
            "Invalid LLM API key. Update and save a real key in Admin -> LLM Settings."}
        {:else}
          {$t.dashboard?.llm_status_unavailable ||
            "LLM status is unavailable. Check settings and backend logs."}
        {/if}
      </div>
    </div>
  {/if}

  {#if error}
    <div
      class="flex items-center justify-between rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-red-700"
    >
      <span>{error}</span>
      <button
        class="rounded bg-red-600 px-3 py-1.5 text-white hover:bg-red-700"
        on:click={loadDashboardDetail}
      >
        {$t.common?.retry}
      </button>
    </div>
  {/if}

  {#if isLoading}
    <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
      {#each Array(3) as _}
        <div
          class="h-24 animate-pulse rounded-xl border border-slate-200 bg-white"
        ></div>
      {/each}
    </div>
    <div
      class="h-64 animate-pulse rounded-xl border border-slate-200 bg-white"
    ></div>
  {:else if dashboard}
    <div class="grid grid-cols-1 gap-6 xl:grid-cols-5">
      <div
        class="rounded-xl border border-slate-200 bg-white p-4 xl:col-span-2"
      >
        <div class="mb-3 flex items-center justify-between">
          <h2
            class="text-sm font-semibold uppercase tracking-wide text-slate-500"
          >
            {$t.dashboard?.api_thumbnail || "Dashboard thumbnail"}
          </h2>
          <button
            class="rounded-md border border-slate-300 px-2 py-1 text-xs text-slate-700 hover:bg-slate-50"
            on:click={() => loadThumbnail(true)}
            disabled={isThumbnailLoading}
          >
            {$t.common?.refresh || "Refresh"}
          </button>
        </div>
        {#if isThumbnailLoading}
          <div class="h-56 animate-pulse rounded-lg bg-slate-100"></div>
        {:else if thumbnailUrl}
          <img
            src={thumbnailUrl}
            alt="Dashboard thumbnail"
            class="h-56 w-full rounded-lg border border-slate-200 object-cover"
          />
        {:else}
          <div
            class="flex h-56 items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 text-sm text-slate-500"
          >
            {thumbnailError ||
              $t.dashboard?.thumbnail_unavailable ||
              "Thumbnail is unavailable"}
          </div>
        {/if}
      </div>
      <div
        class="rounded-xl border border-slate-200 bg-white p-4 xl:col-span-3"
      >
        <div class="mb-3 flex items-center justify-between">
          <h2
            class="text-sm font-semibold uppercase tracking-wide text-slate-500"
          >
            {$t.tasks?.recent || "Recent tasks"}
          </h2>
          <button
            class="rounded-md border border-slate-300 px-2 py-1 text-xs text-slate-700 hover:bg-slate-50"
            on:click={loadTaskHistory}
            disabled={isTaskHistoryLoading}
          >
            {$t.common?.refresh || "Refresh"}
          </button>
        </div>
        {#if isTaskHistoryLoading}
          <div class="space-y-2">
            {#each Array(4) as _}
              <div class="h-10 animate-pulse rounded bg-slate-100"></div>
            {/each}
          </div>
        {:else if taskHistoryError}
          <div
            class="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700"
          >
            {taskHistoryError}
          </div>
        {:else if taskHistory.length === 0}
          <div
            class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-6 text-center text-sm text-slate-500"
          >
            {$t.tasks?.select_task || "No backup/LLM tasks yet"}
          </div>
        {:else}
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-slate-200 text-sm">
              <thead class="bg-slate-50">
                <tr>
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.common?.type || "Type"}</th
                  >
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.common?.status || "Status"}</th
                  >
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.tasks?.result || "Check"}</th
                  >
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.common?.started || "Started"}</th
                  >
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.common?.finished || "Finished"}</th
                  >
                  <th class="px-3 py-2 text-left font-semibold text-slate-600"
                    >{$t.common?.actions || "Actions"}</th
                  >
                </tr>
              </thead>
              <tbody class="divide-y divide-slate-100">
                {#each taskHistory as task}
                  {@const validation = getValidationStatus(task)}
                  <tr>
                    <td class="px-3 py-2 text-slate-800"
                      >{toTaskTypeLabel(task.plugin_id)}</td
                    >
                    <td class="px-3 py-2">
                      <span
                        class={`rounded-full px-2 py-1 text-xs font-semibold uppercase ${getTaskStatusClasses(task.status)}`}
                      >
                        {task.status}
                      </span>
                    </td>
                    <td class="px-3 py-2">
                      <span
                        class={`inline-flex items-center gap-1 rounded-full border px-2 py-1 text-xs font-semibold uppercase ${getValidationStatusClasses(validation.level)}`}
                      >
                        {#if validation.icon}
                          <span
                            class="inline-flex min-w-[18px] items-center justify-center rounded-full bg-white/70 px-1 text-[10px] font-bold"
                          >
                            {validation.icon}
                          </span>
                        {/if}
                        {validation.label}
                      </span>
                    </td>
                    <td class="px-3 py-2 text-slate-700"
                      >{formatDate(task.started_at)}</td
                    >
                    <td class="px-3 py-2 text-slate-700"
                      >{formatDate(task.finished_at)}</td
                    >
                    <td class="px-3 py-2">
                      <div class="flex flex-wrap items-center gap-1">
                        {#if task.plugin_id === "llm_dashboard_validation"}
                          <button
                            class="inline-flex items-center gap-1 rounded-md border border-indigo-300 bg-indigo-50 px-2 py-1 text-xs text-indigo-700 hover:bg-indigo-100"
                            on:click={() => openLlmReport(task.id)}
                          >
                            {$t.tasks?.open_llm_report || "LLM report"}
                          </button>
                        {/if}
                      </div>
                    </td>
                  </tr>
                {/each}
              </tbody>
            </table>
          </div>
        {/if}
      </div>
    </div>

    <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
      <div class="rounded-xl border border-slate-200 bg-white p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">
          {$t.dashboard?.last_modified}
        </p>
        <p class="mt-2 text-lg font-semibold text-slate-900">
          {formatDate(dashboard.last_modified)}
        </p>
      </div>
      <div class="rounded-xl border border-slate-200 bg-white p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">
          {$t.dashboard?.charts}
        </p>
        <p class="mt-2 text-lg font-semibold text-slate-900">
          {dashboard.chart_count || 0}
        </p>
      </div>
      <div class="rounded-xl border border-slate-200 bg-white p-4">
        <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">
          {$t.nav?.datasets}
        </p>
        <p class="mt-2 text-lg font-semibold text-slate-900">
          {dashboard.dataset_count || 0}
        </p>
      </div>
    </div>

    {#if dashboard.description}
      <div class="rounded-xl border border-slate-200 bg-white p-4">
        <h2
          class="text-sm font-semibold uppercase tracking-wide text-slate-500"
        >
          {$t.dashboard?.overview}
        </h2>
        <p class="mt-2 text-sm text-slate-700">{dashboard.description}</p>
      </div>
    {/if}

    <div class="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div class="border-b border-slate-200 px-4 py-3">
        <h2 class="text-lg font-semibold text-slate-900">
          {$t.dashboard?.charts}
        </h2>
      </div>
      {#if dashboard.charts && dashboard.charts.length > 0}
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-slate-200 text-sm">
            <thead class="bg-slate-50">
              <tr>
                <th class="px-4 py-2 text-left font-semibold text-slate-600"
                  >{$t.settings?.type_chart}</th
                >
                <th class="px-4 py-2 text-left font-semibold text-slate-600"
                  >{$t.nav?.datasets}</th
                >
                <th class="px-4 py-2 text-left font-semibold text-slate-600"
                  >{$t.dashboard?.overview}</th
                >
                <th class="px-4 py-2 text-left font-semibold text-slate-600"
                  >{$t.dashboard?.last_modified}</th
                >
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
              {#each dashboard.charts as chart}
                <tr class="hover:bg-slate-50">
                  <td class="px-4 py-3">
                    <div class="font-medium text-slate-900">{chart.title}</div>
                    <div class="text-xs text-slate-500">
                      ID: {chart.id}{#if chart.viz_type}
                        • {chart.viz_type}{/if}
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    {#if chart.dataset_id}
                      <button
                        class="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-blue-700 hover:bg-blue-50 hover:text-blue-800"
                        on:click={() => openDataset(chart.dataset_id)}
                        title={`${$t.datasets?.table_name} ${chart.dataset_id}`}
                      >
                        {$t.nav?.datasets}
                        {chart.dataset_id}
                        <Icon
                          name="chevronRight"
                          size={12}
                          className="text-blue-500"
                        />
                      </button>
                    {:else}
                      <span class="text-xs text-slate-400">-</span>
                    {/if}
                  </td>
                  <td class="px-4 py-3 text-slate-700"
                    >{chart.overview || "-"}</td
                  >
                  <td class="px-4 py-3 text-slate-700"
                    >{formatDate(chart.last_modified)}</td
                  >
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {:else}
        <div class="px-4 py-8 text-sm text-slate-500">
          {$t.dashboard?.no_charts}
        </div>
      {/if}
    </div>

    <div class="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div class="border-b border-slate-200 px-4 py-3">
        <h2 class="text-lg font-semibold text-slate-900">{$t.nav?.datasets}</h2>
      </div>
      {#if dashboard.datasets && dashboard.datasets.length > 0}
        <div class="divide-y divide-slate-100">
          {#each dashboard.datasets as dataset}
            <button
              class="flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-slate-50"
              on:click={() => openDataset(dataset.id)}
            >
              <div class="min-w-0">
                <div class="truncate font-medium text-slate-900">
                  {dataset.table_name}
                </div>
                <div class="truncate text-xs text-slate-500">
                  {dataset.overview ||
                    `${dataset.schema || ""}.${dataset.table_name}`}
                  {#if dataset.database}
                    • {dataset.database}{/if}
                </div>
              </div>
              <div class="flex items-center gap-3">
                <span class="text-xs text-slate-500"
                  >{formatDate(dataset.last_modified)}</span
                >
                <Icon
                  name="chevronRight"
                  size={16}
                  className="text-slate-400"
                />
              </div>
            </button>
          {/each}
        </div>
      {:else}
        <div class="px-4 py-8 text-sm text-slate-500">
          {$t.dashboard?.no_datasets}
        </div>
      {/if}
    </div>
  {/if}
</div>

<!-- [/DEF:DashboardDetail:Page] -->
