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

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

  interface ApiResponse {
    data: Stats;
  }

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

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

<h2>Dashboard</h2>

{#if loading}
  <p>Loading...</p>
{:else}
  <div class="stats-grid">
    <div class="stat-card">
      <h3>{stats.totalDomains}</h3>
      <p>Domains</p>
    </div>
    <div class="stat-card">
      <h3>{stats.totalUsers}</h3>
      <p>Users</p>
    </div>
    <div class="stat-card">
      <h3>{stats.totalAliases}</h3>
      <p>Aliases</p>
    </div>
    <div class="stat-card" class:warning={stats.queueSize > 10}>
      <h3>{stats.queueSize}</h3>
      <p>Queued Emails</p>
    </div>
  </div>
{/if}

<style>
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-top: 2rem;
  }

  .stat-card {
    background: white;
    padding: 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    text-align: center;
  }

  .stat-card.warning {
    border: 2px solid #e74c3c;
  }

  .stat-card h3 {
    font-size: 2.5rem;
    margin: 0;
    color: #2c3e50;
  }

  .stat-card p {
    margin: 0.5rem 0 0;
    color: #7f8c8d;
  }

  .warning h3 {
    color: #e74c3c;
  }
</style>
