<script lang="ts">
  import { onMount } from 'svelte';

  interface Stats {
    totalDomains: number;
    totalUsers: number;
    totalAliases: number;
    queueSize: number;
  }

  let stats = $state<Stats>({
    totalDomains: 0,
    totalUsers: 0,
    totalAliases: 0,
    queueSize: 0
  });
  let loading = $state(true);

  async function fetchWithAuth(url: string) {
    const token = localStorage.getItem('token');
    const res = await fetch(url, {
      headers: { Authorization: `Bearer ${token}` }
    });
    return res.json();
  }

  onMount(async () => {
    try {
      const statsRes = await fetchWithAuth('/api/stats');
      if (statsRes.data) {
        stats = statsRes.data;
      }
    } catch (e) {
      console.error('Failed to fetch stats:', e);
    } finally {
      loading = false;
    }
  });
</script>

<div class="space-y-6">
  <h2 class="text-2xl font-bold">Dashboard</h2>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else}
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
      <a href="/domains" class="card bg-base-100 shadow hover:shadow-md transition-shadow">
        <div class="card-body items-center text-center">
          <h2 class="card-title text-4xl font-bold text-primary">{stats.totalDomains}</h2>
          <p class="text-base-content/60">Domains</p>
        </div>
      </a>
      
      <a href="/domains" class="card bg-base-100 shadow hover:shadow-md transition-shadow">
        <div class="card-body items-center text-center">
          <h2 class="card-title text-4xl font-bold text-secondary">{stats.totalUsers}</h2>
          <p class="text-base-content/60">Users</p>
        </div>
      </a>
      
      <a href="/domains" class="card bg-base-100 shadow hover:shadow-md transition-shadow">
        <div class="card-body items-center text-center">
          <h2 class="card-title text-4xl font-bold text-accent">{stats.totalAliases}</h2>
          <p class="text-base-content/60">Aliases</p>
        </div>
      </a>
      
      <a href="/queue" class="card bg-base-100 shadow hover:shadow-md transition-shadow {stats.queueSize > 10 ? 'ring-2 ring-error' : ''}">
        <div class="card-body items-center text-center">
          <h2 class="card-title text-4xl font-bold {stats.queueSize > 10 ? 'text-error' : 'text-warning'}">{stats.queueSize}</h2>
          <p class="text-base-content/60">Queued Emails</p>
        </div>
      </a>
    </div>
  {/if}
</div>
