<!-- [DEF:HealthCenterPage:Component] -->
<!-- 
  @TIER: STANDARD
  @PURPOSE: Main page for the Dashboard Health Center.
  @LAYER: UI/Page
  @UX_STATE: Idle -> Displays the Health Center with HealthMatrix.
  @UX_STATE: Loading -> Displays a skeleton or spinner.
  @UX_STATE: Error -> Displays an error message.
  @UX_REATIVITY: State: $state, Derived: $derived.
-->
<script>
  import { onMount } from 'svelte';
  import HealthMatrix from '$lib/components/health/HealthMatrix.svelte';
  import { getHealthSummary, getEnvironments } from '$lib/api.js';
  import { t } from '$lib/i18n';
  import { formatDistanceToNow } from 'date-fns';

  let healthData = $state({
    items: [],
    pass_count: 0,
    warn_count: 0,
    fail_count: 0,
    unknown_count: 0
  });
  let environments = $state([]);
  let selectedEnvId = $state('');
  let loading = $state(true);
  let error = $state(null);

  async function loadData() {
    loading = true;
    error = null;
    try {
      const [summary, envs] = await Promise.all([
        getHealthSummary(selectedEnvId),
        getEnvironments()
      ]);
      healthData = summary;
      environments = envs;
      if (!selectedEnvId && envs.length > 0) {
        // selectedEnvId = envs[0].id; // Optional: default to first env
      }
    } catch (e) {
      error = e.message;
    } finally {
      loading = false;
    }
  }

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

  function handleEnvChange(e) {
    selectedEnvId = e.target.value;
    loadData();
  }
</script>

<div class="container mx-auto p-6">
  <div class="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4">
    <div>
      <h1 class="text-3xl font-bold text-gray-900">{$t.health?.title}</h1>
      <p class="text-gray-500 mt-1">{$t.health?.subtitle}</p>
    </div>

    <div class="flex items-center gap-3">
      <label for="env-select" class="text-sm font-medium text-gray-700 whitespace-nowrap">{$t.health?.environment_label}</label>
      <select 
        id="env-select"
        class="block w-full md:w-48 pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
        value={selectedEnvId}
        onchange={handleEnvChange}
      >
        <option value="">{$t.health?.all_environments}</option>
        {#each environments as env}
          <option value={env.id}>{env.name || env.id}</option>
        {/each}
      </select>
      
      <button 
        onclick={loadData}
        disabled={loading}
        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
      >
        {$t.common?.refresh}
      </button>
    </div>
  </div>
  
  <HealthMatrix 
    pass_count={healthData.pass_count}
    warn_count={healthData.warn_count}
    fail_count={healthData.fail_count}
    unknown_count={healthData.unknown_count}
    {loading} 
    {error} 
  />

  <div class="mt-8 bg-white shadow overflow-hidden sm:rounded-lg border border-gray-200">
    <div class="px-4 py-5 sm:px-6 border-b border-gray-200 bg-gray-50">
      <h3 class="text-lg leading-6 font-medium text-gray-900">{$t.health?.validation_details}</h3>
    </div>
    <div class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.health?.table_dashboard}</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.health?.table_environment}</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.health?.table_status}</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.health?.table_last_check}</th>
            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{$t.health?.table_summary}</th>
            <th scope="col" class="relative px-6 py-3">
              <span class="sr-only">{$t.common?.actions}</span>
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          {#if loading}
            {#each Array(3) as _}
              <tr class="animate-pulse">
                <td class="px-6 py-4 whitespace-nowrap"><div class="h-4 bg-gray-200 rounded w-32"></div></td>
                <td class="px-6 py-4 whitespace-nowrap"><div class="h-4 bg-gray-200 rounded w-16"></div></td>
                <td class="px-6 py-4 whitespace-nowrap"><div class="h-6 bg-gray-200 rounded-full w-16"></div></td>
                <td class="px-6 py-4 whitespace-nowrap"><div class="h-4 bg-gray-200 rounded w-24"></div></td>
                <td class="px-6 py-4"><div class="h-4 bg-gray-200 rounded w-full"></div></td>
                <td class="px-6 py-4"></td>
              </tr>
            {/each}
          {:else if healthData.items.length === 0}
            <tr>
              <td colspan="6" class="px-6 py-10 text-center text-sm text-gray-500">
                {$t.health?.no_records}
              </td>
            </tr>
          {:else}
            {#each healthData.items as item}
              <tr class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                  {item.dashboard_title || item.dashboard_id}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  <span class="px-2 py-1 bg-gray-100 rounded text-xs font-mono">{item.environment_id}</span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2.5 py-0.5 rounded-full text-xs font-medium
                    {item.status === 'PASS' ? 'bg-green-100 text-green-800' : 
                     item.status === 'WARN' ? 'bg-yellow-100 text-yellow-800' : 
                     item.status === 'FAIL' ? 'bg-red-100 text-red-800' : 
                     'bg-gray-100 text-gray-800'}">
                    {item.status}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {formatDistanceToNow(new Date(item.last_check), { addSuffix: true })}
                </td>
                <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">
                    {item.summary || '-'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  {#if item.task_id}
                    <a href="/reports/llm/{item.task_id}" class="text-indigo-600 hover:text-indigo-900">{$t.health?.view_report}</a>
                  {/if}
                </td>
              </tr>
            {/each}
          {/if}
        </tbody>
      </table>
    </div>
  </div>
</div>
<!-- [/DEF:HealthCenterPage:Component] -->
