<!-- #region TranslationMetricsDashboard [C:3] [TYPE Component] [SEMANTICS translate, metrics, dashboard, stats, cost] -->
<!-- @BRIEF Component component: lib/components/translate/TranslationMetricsDashboard.svelte -->
<!-- @RELATION DEPENDS_ON -> [TranslateApi] -->
<!-- @UX_STATE loading -> Initial load -->
<!-- @UX_STATE loaded -> Metrics data displayed -->
<!-- @UX_STATE error -> Failed to load metrics -->
<!-- @UX_STATE empty -> No metrics data available -->
<!-- @UX_FEEDBACK Spinner during load; card grid for totals; table for per-job breakdown -->
<!-- @UX_RECOVERY Retry button on error -->
<script lang="ts">
  import { t } from '$lib/i18n/index.svelte.js';
  import { addToast } from '$lib/toasts.svelte.js';
  import { fetchAllMetrics } from '$lib/api/translate.js';

  /** @type {'loading'|'loaded'|'error'|'empty'} */
  let uxState = $state('loading');
  let metrics = $state([]);
  let errorMessage = $state('');

  // Aggregated
  let totalRuns = $derived(metrics.reduce((sum, m) => sum + (m.total_runs || 0), 0));
  let successfulRuns = $derived(metrics.reduce((sum, m) => sum + (m.successful_runs || 0), 0));
  let failedRuns = $derived(metrics.reduce((sum, m) => sum + (m.failed_runs || 0), 0));
  let totalRecords = $derived(metrics.reduce((sum, m) => sum + (m.total_records || 0), 0));
  let totalTokens = $derived(metrics.reduce((sum, m) => sum + (m.total_tokens || 0), 0));
  let totalCost = $derived(metrics.reduce((sum, m) => sum + (m.total_cost || 0), 0));
  let successRate = $derived(
    totalRuns > 0 ? Math.round((successfulRuns / totalRuns) * 100) : 0
  );

  let avgLatency = $derived.by(() => {
    const withLatency = metrics.filter(m => m.avg_latency_seconds);
    if (withLatency.length === 0) return null;
    const sum = withLatency.reduce((s, m) => s + (m.avg_latency_seconds || 0), 0);
    return (sum / withLatency.length).toFixed(1);
  });

  $effect(() => {
    loadMetrics();
  });

  async function loadMetrics() {
    uxState = 'loading';
    errorMessage = '';
    try {
      const data = await fetchAllMetrics();
      const items = Array.isArray(data) ? data : (data?.items || []);
      if (items.length === 0) {
        uxState = 'empty';
      } else {
        metrics = items;
        uxState = 'loaded';
      }
    } catch (err) {
      errorMessage = err?.message || $t.translate?.metrics?.load_failed;
      uxState = 'error';
    }
  }

  async function handleRefresh() {
    await loadMetrics();
  }
</script>

<div class="translation-metrics-dashboard space-y-6">
  <!-- Header -->
  <div class="flex items-center justify-between">
    <div>
      <h2 class="text-xl font-bold text-gray-900">{$t.translate?.metrics?.title}</h2>
      <p class="text-sm text-gray-500 mt-1">{$t.translate?.metrics?.subtitle}</p>
    </div>
    <button
      onclick={handleRefresh}
      class="px-3 py-1.5 text-sm border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-1.5"
    >
      <svg class="w-4 h-4" 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.translate?.metrics?.refresh}
    </button>
  </div>

  <!-- Loading -->
  {#if uxState === 'loading'}
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      {#each Array(3) as _}
        <div class="h-24 bg-gray-100 rounded-lg animate-pulse" />
      {/each}
    </div>

  <!-- Error -->
  {:else if uxState === 'error'}
    <div class="bg-destructive-light border-destructive-light rounded-lg p-6 text-center">
      <p class="text-red-700 mb-3">{errorMessage}</p>
      <button
        onclick={handleRefresh}
        class="px-4 py-2 bg-destructive text-white rounded-lg hover:bg-destructive-hover transition-colors text-sm"
      >
        {$t.translate?.common?.retry}
      </button>
    </div>

  <!-- Empty -->
  {:else if uxState === 'empty'}
    <div class="bg-gray-50 border border-gray-200 rounded-lg p-8 text-center">
      <svg class="w-16 h-16 text-gray-300 mx-auto mb-4" 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-gray-500">{$t.translate?.metrics?.no_data}</p>
    </div>

  <!-- Loaded -->
  {:else if uxState === 'loaded'}
    <!-- Summary Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.total_runs}</p>
        <p class="text-2xl font-bold text-gray-900 mt-1">{totalRuns}</p>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.success_rate}</p>
        <p class="text-2xl font-bold text-green-600 mt-1">{successRate}%</p>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.failed_runs}</p>
        <p class="text-2xl font-bold text-red-600 mt-1">{failedRuns}</p>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.total_records}</p>
        <p class="text-2xl font-bold text-gray-900 mt-1">{totalRecords.toLocaleString()}</p>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.total_tokens}</p>
        <p class="text-2xl font-bold text-gray-900 mt-1">{totalTokens.toLocaleString()}</p>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.total_cost}</p>
        <p class="text-2xl font-bold text-gray-900 mt-1">${totalCost.toFixed(2)}</p>
      </div>
    </div>

    <!-- Per-Job Breakdown Table -->
    <div class="bg-white border border-gray-200 rounded-lg overflow-hidden">
      <div class="px-4 py-3 border-b border-gray-200">
        <h3 class="text-sm font-semibold text-gray-900">{$t.translate?.metrics?.runs_per_job}</h3>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.job}</th>
              <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.runs}</th>
              <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.successful}</th>
              <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.failed}</th>
              <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.tokens}</th>
              <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">{$t.translate?.metrics?.cost}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            {#each metrics as m}
              <tr class="hover:bg-gray-50">
                <td class="px-4 py-2 font-medium text-gray-900">{m.job_name || m.job_id}</td>
                <td class="px-4 py-2 text-center text-gray-700">{m.total_runs || 0}</td>
                <td class="px-4 py-2 text-center text-green-600">{m.successful_runs || 0}</td>
                <td class="px-4 py-2 text-center text-red-600">{m.failed_runs || 0}</td>
                <td class="px-4 py-2 text-right text-gray-700">{(m.total_tokens || 0).toLocaleString()}</td>
                <td class="px-4 py-2 text-right text-gray-700">${(m.total_cost || 0).toFixed(2)}</td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    </div>

    <!-- Additional stats row -->
    {#if avgLatency !== null}
      <div class="bg-white border border-gray-200 rounded-lg p-4">
        <p class="text-xs text-gray-500 uppercase">{$t.translate?.metrics?.avg_latency}</p>
        <p class="text-lg font-semibold text-gray-900 mt-1">{avgLatency}s</p>
      </div>
    {/if}
  {/if}
</div>
<!-- #endregion TranslationMetricsDashboard -->
