<!-- [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
   */

  import { onMount } from "svelte";
  import { goto } from "$app/navigation";
  import { page } from "$app/stores";
  import { t } from "$lib/i18n";
  import { api } from "$lib/api.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;

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

  async function loadDashboardDetail() {
    if (!dashboardId || !envId) {
      error = "Missing dashboard ID or environment ID";
      isLoading = false;
      return;
    }

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

  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" })}`;
  }
</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 || "Back to Dashboards"}
      </button>
      <h1 class="mt-2 text-2xl font-bold text-slate-900">
        {dashboard?.title || "Dashboard Overview"}
      </h1>
      <p class="mt-1 text-sm text-slate-500">
        ID: {dashboardId}{#if dashboard?.slug} • {dashboard.slug}{/if}
      </p>
    </div>
    <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={loadDashboardDetail}
    >
      {$t.common?.refresh || "Refresh"}
    </button>
  </div>

  {#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 || "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-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">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">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">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">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">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">Chart</th>
                <th class="px-4 py-2 text-left font-semibold text-slate-600">Dataset</th>
                <th class="px-4 py-2 text-left font-semibold text-slate-600">Overview</th>
                <th class="px-4 py-2 text-left font-semibold text-slate-600">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={`Open dataset ${chart.dataset_id}`}
                      >
                        Dataset {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">No charts found for this dashboard.</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">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">No datasets found for this dashboard.</div>
      {/if}
    </div>
  {/if}
</div>

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