<!-- #region HealthCenterPage [C:5] [TYPE Page] [SEMANTICS sveltekit, health, matrix, dashboard-cards, validation, environment] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Dashboard Health Center — thin page shell delegating state logic to HealthCenterModel.
     Cards replace the old table; matrix clicks filter the list. -->
<!-- @LAYER Page -->
<!-- @RELATION DEPENDS_ON -> [HealthMatrix] -->
<!-- @RELATION DEPENDS_ON -> [ScheduleAtAGlance] -->
<!-- @RELATION BINDS_TO -> [HealthCenterModel] -->
<!-- @UX_STATE Loading -> Skeleton loaders, matrix dimmed. -->
<!-- @UX_STATE Loaded -> Health matrix + card-based dashboard list. -->
<!-- @UX_STATE Error -> Error message with retry button. -->
<!-- @UX_FEEDBACK Toast on delete success/failure. -->
<!-- @UX_RECOVERY Refresh button reloads data; Clear filter resets matrix filter. -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { ROUTES } from '$lib/routes.js';
  import HealthMatrix from '$lib/components/health/HealthMatrix.svelte';
  import ScheduleAtAGlance from '$lib/components/health/ScheduleAtAGlance.svelte';
  import { t } from '$lib/i18n/index.svelte.js';
  import { formatDistanceToNow } from 'date-fns';
  import { HealthCenterModel } from '$lib/models/HealthCenterModel.svelte.ts';

  const m = new HealthCenterModel();

  onMount(() => { m.loadData(); });

  function formatRelativeDate(ts: string): string {
    return formatDistanceToNow(new Date(ts), { addSuffix: true });
  }

  function getStatusBadge(status: string): string {
    switch (status) {
      case 'PASS': return 'bg-success-light text-success ring-1 ring-success-ring';
      case 'WARN': return 'bg-warning-light text-warning ring-1 ring-warning-ring';
      case 'FAIL': return 'bg-destructive-light text-destructive ring-1 ring-destructive-ring';
      default: return 'bg-surface-muted text-text-muted ring-1 ring-secondary-ring';
    }
  }
</script>

<div class="max-w-7xl mx-auto px-4 py-6">
  <!-- Header -->
  <div class="flex flex-col sm:flex-row sm:items-center justify-between mb-6 gap-4">
    <div>
      <h1 class="text-2xl font-bold text-text">{$t.health?.title || 'Dashboard Health Center'}</h1>
      <p class="text-sm text-text-muted mt-1">{$t.health?.subtitle || 'Monitor the latest validation status across your environments.'}</p>
    </div>
    <div class="flex items-center gap-3">
      <select
        value={m.selectedEnvId}
        onchange={(e) => m.handleEnvChange((e.target as HTMLSelectElement).value)}
        class="w-44 px-3 py-2 text-sm border-border-strong rounded-lg bg-surface-card shadow-sm focus:ring-primary-ring focus:border-primary-ring"
      >
        <option value="">{$t.health?.all_environments || 'All'}</option>
        {#each m.environments as env (env.id)}
          <option value={env.id}>{env.name || env.id}</option>
        {/each}
      </select>
      <button
        onclick={() => m.loadData()}
        disabled={m.screenState === 'loading'}
        class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg text-white bg-primary hover:bg-primary-hover disabled:opacity-50 transition-colors"
      >
        <svg class="w-4 h-4" class:animate-spin={m.screenState === 'loading'} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
        {$t.common?.refresh || 'Refresh'}
      </button>
    </div>
  </div>

  <!-- Clickable Health Matrix -->
  <HealthMatrix
    pass_count={m.healthData.pass_count}
    warn_count={m.healthData.warn_count}
    fail_count={m.healthData.fail_count}
    unknown_count={m.healthData.unknown_count}
    selectedFilter={m.activeStatusFilter}
    onSelect={(s) => m.handleMatrixSelect(s)}
    loading={m.screenState === 'loading'}
    error={m.error}
  />

  <!-- Schedule (compact) -->
  <div class="mt-5">
    <ScheduleAtAGlance
      healthItems={m.healthData.items}
      selectedEnvId={m.selectedEnvId}
      appTimezone={m.appTimezone}
    />
  </div>

  <!-- Dashboard Cards -->
  <div class="mt-5">
    <div class="flex items-center justify-between mb-3">
      <h2 class="text-sm font-semibold text-text-muted uppercase tracking-wider">
        {$t.health?.validation_details || 'Dashboards'}
        {#if m.activeStatusFilter}
          <span class="font-normal normal-case text-text-subtle"> · filtered by {m.activeStatusFilter}</span>
        {/if}
      </h2>
      <span class="text-xs text-text-subtle">{m.filteredItems.length} {m.filteredItems.length === 1 ? 'dashboard' : 'dashboards'}</span>
    </div>

    {#if m.screenState === 'loading'}
      <div class="space-y-3">
        {#each Array(4) as _, i (i)}
          <div class="animate-pulse bg-surface-card border border-border rounded-xl p-5">
            <div class="flex items-center justify-between mb-3">
              <div class="h-5 bg-surface-muted rounded w-48"></div>
              <div class="h-6 bg-surface-muted rounded-full w-16"></div>
            </div>
            <div class="h-4 bg-surface-muted rounded w-full mb-2"></div>
            <div class="h-4 bg-surface-muted rounded w-3/4"></div>
          </div>
        {/each}
      </div>
    {:else if m.filteredItems.length === 0}
      <div class="bg-surface-card border-2 border-dashed border-border rounded-xl p-12 text-center">
        <svg class="w-12 h-12 mx-auto mb-3 text-text-subtle" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
        <p class="text-sm text-text-subtle">{$t.health?.no_records || 'No validation records found'}</p>
        {#if m.activeStatusFilter}
          <button onclick={() => m.clearFilter()} class="mt-3 text-xs text-primary hover:text-primary underline">
            {$t.validation?.clear_filters || 'Clear filter'}
          </button>
        {/if}
      </div>
    {:else}
      <div class="space-y-3">
        {#each m.filteredItems as item (item.record_id || item.dashboard_id)}
          <div class="bg-surface-card border border-border rounded-xl p-5 hover:border-border-strong hover:shadow-sm transition-all">
            <!-- Card top: name + status + last check -->
            <div class="flex items-start justify-between mb-3">
              <div class="min-w-0 flex-1">
                <div class="flex items-center gap-2 flex-wrap">
                  <a
                    href={ROUTES.dashboards.detail(item.dashboard_slug || item.dashboard_id, item.environment_id)}
                    class="text-base font-semibold text-text hover:text-primary hover:underline truncate"
                  >
                    {item.dashboard_name || item.dashboard_title || item.dashboard_slug || item.dashboard_id}
                  </a>
                  <a
                    href={ROUTES.dashboards.validation(item.dashboard_id, item.environment_id)}
                    class="inline-flex items-center gap-0.5 text-[11px] text-text-subtle hover:text-primary transition-colors flex-shrink-0"
                    title="View full validation history"
                  >
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    {$t.health?.view_history || 'History'}
                  </a>
                  <span class="text-[10px] text-text-subtle font-mono">{item.environment_id}</span>
                </div>
              </div>
              <div class="flex items-center gap-2 flex-shrink-0 ml-3">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold {getStatusBadge(item.status)}">{item.status}</span>
              </div>
            </div>

            <!-- Card meta: path, issues, chunks, time -->
            <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-text-muted mb-2">
              {#if item.execution_path === 'screenshot'}
                <span class="inline-flex items-center gap-1"><span class="text-text-subtle">📷</span> Screenshot</span>
              {:else if item.execution_path === 'text_only'}
                <span class="inline-flex items-center gap-1"><span class="text-text-subtle">📝</span> Text</span>
              {:else}
                <span>—</span>
              {/if}
              <span>·</span>
              {#if item.issues_count != null}
                <span class="font-medium" class:text-destructive={item.status === 'FAIL'} class:text-warning={item.status === 'WARN'}>
                  {item.issues_count} issue{item.issues_count !== 1 ? 's' : ''}
                </span>
              {:else}
                <span>—</span>
              {/if}
              {#if item.chunk_count != null}
                <span>·</span>
                <span>{item.chunk_count} chunk{item.chunk_count > 1 ? 's' : ''}</span>
              {/if}
              <span>·</span>
              <span class="text-text-subtle">{formatRelativeDate(item.last_check)}</span>
            </div>

            <!-- Summary -->
            {#if item.summary}
              <p class="text-sm text-text-muted line-clamp-2 mb-3 leading-relaxed">{item.summary}</p>
            {/if}

            <!-- Card actions -->
            <div class="flex items-center gap-3 pt-1">
              {#if item.policy_id && item.run_id}
                <a
                  href={ROUTES.validationTasks.runReport(item.policy_id, item.run_id)}
                  class="inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary transition-colors"
                >
                  <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                  {$t.health?.view_report || 'Open Report'}
                </a>
              {:else if item.task_id}
                <a
                  href={ROUTES.reports.llmReport(item.task_id)}
                  class="inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary transition-colors"
                >
                  {$t.health?.view_report || 'Open Report'}
                </a>
              {/if}
              <button
                type="button"
                class="inline-flex items-center gap-1 text-xs text-text-subtle hover:text-destructive transition-colors ml-auto"
                onclick={() => m.handleDeleteReport(item)}
                disabled={m.deletingReportIds.has(item.record_id!)}
              >
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                {m.deletingReportIds.has(item.record_id!) ? '...' : $t.common?.delete || 'Delete'}
              </button>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </div>
</div>
<!-- #endregion HealthCenterPage -->
