<!-- #region DashboardDetail [C:4] [TYPE Page] [SEMANTICS sveltekit, dashboard, detail, git, llm] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Dashboard detail view — renders DashboardDetailModel state, delegates all logic to the model. -->
<!-- @LAYER Page -->
<!-- @RELATION BINDS_TO -> [DashboardDetailModel] -->
<!-- @RELATION DEPENDS_ON -> [DashboardHeader] -->
<!-- @RELATION DEPENDS_ON -> [DashboardGitManager] -->
<!-- @RELATION DEPENDS_ON -> [DashboardLinkedResources] -->
<!-- @RELATION DEPENDS_ON -> [DashboardTaskHistory] -->
<!-- @RELATION DEPENDS_ON -> [GitManager] -->
<!-- @UX_STATE loading -> Skeleton shown. -->
<!-- @UX_STATE loaded -> Metadata, assets, Git controls, task history rendered. -->
<!-- @UX_STATE error -> Inline error with retry. -->
<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { page } from '$app/state';
  import { t } from '$lib/i18n/index.svelte.js';
  import { openDrawerForTaskIfPreferred } from '$lib/stores/taskDrawer.svelte.js';
  import { DashboardDetailModel } from '$lib/models/DashboardDetailModel.svelte';
  import { ROUTES } from '$lib/routes.js';
  import { Icon, Skeleton } from '$lib/ui';

  import CommitHistory from '$lib/components/git/CommitHistory.svelte';
  import GitManager from '$lib/components/git/GitManager.svelte';
  import DashboardHeader from './components/DashboardHeader.svelte';
  import DashboardGitManager from './components/DashboardGitManager.svelte';
  import DashboardLinkedResources from './components/DashboardLinkedResources.svelte';

  const m = new DashboardDetailModel();

  $effect(() => { m.dashboardRef = page.params.id; });
  $effect(() => { m.envId = page.url.searchParams.get('env_id') || ''; });

  const { formatDate } = DashboardDetailModel;

  onMount(async () => { await m.loadDashboardPage(); });
  onDestroy(() => { m.cleanup(); });

  $effect(() => { m.trackGitManagerClose(); });
</script>

<div class="mx-auto w-full max-w-7xl space-y-6">
  <DashboardHeader
    dashboard={m.dashboard}
    resolvedDashboardId={m.resolvedDashboardId}
    dashboardRef={m.dashboardRef}
    envId={m.envId}
    gitDashboardRef={m.gitDashboardRef}
    hasGitRepo={m.gitModel.hasGitRepo}
    bind:currentBranch={m.gitModel.currentBranch}
    gitMeta={m.gitModel.meta}
    gitStatus={m.gitModel.gitStatus}
    isStartingBackup={m.isStartingBackup}
    bind:showGitManager={m.showGitManager}
    goBack={() => m.goBack()}
    handleBranchChange={(e) => m.gitModel.handleBranchChange(e)}
    runBackupTask={() => m.runBackupTask()}
    loadDashboardPage={() => m.loadDashboardPage()}
  />

  {#if m.error}
    <div class="flex items-center justify-between rounded-lg border border-destructive-ring bg-destructive-light px-4 py-3 text-destructive">
      <span>{m.error}</span>
      <button class="rounded bg-destructive px-3 py-1.5 text-white hover:bg-destructive-hover" onclick={() => m.loadDashboardDetail()}>{$t.common?.retry}</button>
    </div>
  {/if}

  {#if m.isLoading}
    <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
      {#each Array(3) as _}
        <Skeleton variant="card" height="h-24" class="rounded-xl border border-border bg-surface-card" />
      {/each}
    </div>
    <Skeleton variant="card" height="h-64" class="rounded-xl border border-border bg-surface-card" />
  {:else if m.dashboard}
    <div class="grid grid-cols-1 gap-6 xl:grid-cols-5">
      <!-- Thumbnail -->
      <div class="rounded-xl border border-border bg-surface-card 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-text-muted">{$t.dashboard?.api_thumbnail || "Dashboard thumbnail"}</h2>
          <button class="rounded-md border border-border-strong px-2 py-1 text-xs text-text hover:bg-surface-page" onclick={() => m.loadThumbnail(true)} disabled={m.isThumbnailLoading}>{$t.common?.refresh}</button>
        </div>
        {#if m.isThumbnailLoading}
          <Skeleton variant="card" height="h-56" />
        {:else if m.thumbnailUrl}
          <img src={m.thumbnailUrl} alt="Dashboard thumbnail" class="h-56 w-full rounded-lg border border-border object-cover" />
        {:else}
          <div class="flex h-56 items-center justify-center rounded-lg border border-dashed border-border-strong bg-surface-page text-sm text-text-muted">{m.thumbnailError || $t.dashboard?.thumbnail_unavailable || "Thumbnail is unavailable"}</div>
        {/if}
      </div>

      <!-- Git Manager -->
      <DashboardGitManager
        isGitStatusLoading={m.gitModel.statusLoading}
        gitStatusError={m.gitModel.statusError}
        hasGitRepo={m.gitModel.hasGitRepo}
        gitSyncState={m.gitModel.syncState}
        gitStatus={m.gitModel.gitStatus}
        changedChartsCount={m.gitModel.changedChartsCount}
        changedDatasetsCount={m.gitModel.changedDatasetsCount}
        allChangedFiles={m.gitModel.allChangedFilesList}
        runGitSyncAndOpenCommit={() => m.handleSyncAndOpenCommit()}
        isSyncingGit={m.gitModel.syncing}
        hasChangesToCommit={m.gitModel.hasChangesToCommit}
        loadGitDiffPreview={() => m.gitModel.loadDiffPreview()}
        isGitDiffLoading={m.gitModel.diffLoading}
        runGitPull={() => m.gitModel.pullRepository()}
        isPullingGit={m.gitModel.pulling}
        runGitPush={() => m.gitModel.pushRepository()}
        isPushingGit={m.gitModel.pushing}
        gitDiffPreview={m.gitModel.diffPreview}
        loadGitStatus={() => m.gitModel.loadStatus()}
        bind:showGitManager={m.showGitManager}
      />
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
      <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.dashboard?.last_modified}</p>
        <p class="mt-2 text-lg font-semibold text-text">{formatDate(m.dashboard.last_modified)}</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.dashboard?.charts}</p>
        <p class="mt-2 text-lg font-semibold text-text">{m.dashboard.chart_count || 0}</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.nav?.datasets}</p>
        <p class="mt-2 text-lg font-semibold text-text">{m.dashboard.dataset_count || 0}</p>
      </div>
    </div>

    <!-- Validation History -->
    <div class="rounded-xl border border-border bg-surface-card p-4">
      <div class="mb-3 flex items-center justify-between">
        <h2 class="text-sm font-semibold uppercase tracking-wide text-text-muted">{$t.dashboard?.validation_history || "Validation History"}</h2>
        <button class="rounded-md border border-border-strong px-2 py-1 text-xs text-text hover:bg-surface-page" onclick={() => m.loadValidationHistory(m.dashboard?.id ?? m.dashboardRef)} disabled={m.isValidationHistoryLoading}>{$t.common?.refresh}</button>
      </div>
      {#if m.isValidationHistoryLoading}
        <div class="space-y-2">{#each Array(3) as _}<Skeleton variant="line" height="h-10" />{/each}</div>
      {:else if m.validationHistoryError}
        <div class="rounded-lg border border-destructive-ring bg-destructive-light px-3 py-2 text-sm text-destructive">{m.validationHistoryError}</div>
      {:else if m.validationHistory.length === 0}
        <div class="rounded-lg border border-border bg-surface-page px-3 py-6 text-center text-sm text-text-muted">{$t.dashboard?.no_validation_runs || "No validation runs yet"}</div>
      {:else}
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-border text-sm">
            <thead class="bg-surface-page"><tr>
              <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.common?.date}</th>
              <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.tasks?.name || "Task Name"}</th>
              <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.common?.status}</th>
              <th class="px-3 py-2 text-left font-semibold text-text-muted">{$t.common?.actions}</th>
            </tr></thead>
            <tbody class="divide-y divide-border">
              {#each m.validationHistory as run}
                {@const runStatus = String(run.status || "").toUpperCase()}
                <tr>
                  <td class="px-3 py-2 text-text">{formatDate(run.timestamp || (run as Record<string,unknown>).created_at || run.started_at)}</td>
                  <td class="px-3 py-2 text-text">{run.summary ? run.summary.slice(0, 80) + (run.summary.length > 80 ? '\u2026' : '') : '-'}</td>
                  <td class="px-3 py-2">
                    <span class="rounded-full px-2 py-1 text-xs font-semibold uppercase {runStatus === 'SUCCESS' || runStatus === 'PASS' ? 'bg-success-light text-success' : runStatus === 'FAIL' || runStatus === 'FAILED' || runStatus === 'ERROR' ? 'bg-destructive-light text-destructive' : runStatus === 'WARN' ? 'bg-warning-light text-warning' : runStatus === 'RUNNING' || runStatus === 'PENDING' ? 'bg-primary-light text-primary' : 'bg-surface-muted text-text'}">{runStatus || 'UNKNOWN'}</span>
                  </td>
                  <td class="px-3 py-2">
                    {#if run.policy_id || (run as Record<string,unknown>).policyId}
                      <a href={ROUTES.validationTasks.runReport(run.policy_id || (run as Record<string,unknown>).policyId as string, run.id || (run as Record<string,unknown>).run_id as string)} class="inline-flex items-center gap-1 rounded-md border border-primary-ring bg-primary-light px-2 py-1 text-xs text-primary hover:bg-primary-light">{$t.common?.view_report || "Report"}</a>
                    {:else if run.id}
                      <button class="inline-flex items-center gap-1 rounded-md border border-border-strong px-2 py-1 text-xs text-text-muted hover:bg-surface-page" onclick={() => openDrawerForTaskIfPreferred(run.id)}>{$t.tasks?.open_task_drawer || "View task"}</button>
                    {/if}
                  </td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
        <div class="border-t border-border px-3 py-2 text-right">
          <a href={ROUTES.dashboards.validation(m.resolvedDashboardId ?? m.dashboardRef, m.envId || '')} class="inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary transition-colors">
            {$t.dashboard?.view_all_validation || 'View all validation runs'}
            <Icon name="chevronRight" size={14} strokeWidth={2} />
          </a>
        </div>
      {/if}
    </div>

    <!-- Tabs: Linked Resources / Git History -->
    <div class="rounded-xl border border-border bg-surface-card">
      <div class="flex flex-wrap items-center gap-2 border-b border-border px-4 py-3">
        <button class="rounded-md px-3 py-1.5 text-sm font-medium transition-colors {m.activeTab === 'resources' ? 'bg-terminal-bg text-white' : 'bg-surface-muted text-text hover:bg-surface-muted'}" onclick={() => (m.activeTab = 'resources')}>{$t.dashboard?.linked_resources || 'Linked resources'}</button>
        <button class="rounded-md px-3 py-1.5 text-sm font-medium transition-colors {m.activeTab === 'git-history' ? 'bg-terminal-bg text-white' : 'bg-surface-muted text-text hover:bg-surface-muted'}" onclick={() => (m.activeTab = 'git-history')}>{$t.dashboard?.git_history || 'Git history'}</button>
      </div>

      <div class="space-y-4 p-4">
        {#if m.activeTab === 'resources'}
          <DashboardLinkedResources dashboard={m.dashboard} openDataset={(id: string) => m.openDataset(id)} {formatDate} />
        {:else if m.activeTab === 'git-history'}
          {#if m.gitModel.hasGitRepo && m.gitDashboardRef}
            <CommitHistory dashboardId={m.gitDashboardRef} envId={m.envId || null} />
          {:else}
            <div class="rounded-lg border border-border bg-surface-page px-4 py-6 text-sm text-text-muted">{$t.git?.not_linked || "This dashboard is not yet linked to a Git repository."}</div>
          {/if}
        {/if}
      </div>
    </div>
  {/if}
</div>

{#if m.showGitManager && m.gitDashboardRef}
  <GitManager dashboardId={m.gitDashboardRef} envId={m.envId || null} dashboardTitle={m.dashboard?.title || ''} bind:show={m.showGitManager} />
{/if}
<!-- #endregion DashboardDetail -->
