<script lang="ts">
  import { page } from '$app/stores';

  interface DomainDetail {
    id: number;
    name: string;
    userCount: number;
    aliasCount: number;
  }

  let domain = $state<DomainDetail | null>(null);
  let loading = $state(true);
  let error = $state('');

  async function loadDomain(name: string) {
    try {
      const res = await fetch(`/api/domains/${encodeURIComponent(name)}`);
      if (res.ok) {
        const data = await res.json();
        domain = data.data;
        if (domain) {
          localStorage.setItem('selectedDomain', domain.name);
        }
      } else {
        error = 'Domain not found';
      }
    } catch (e) {
      error = 'Failed to load domain';
    } finally {
      loading = false;
    }
  }

  $effect(() => {
    const name = $page.params.name;
    if (name) loadDomain(name);
  });
</script>

{#if loading}
  <p>Loading...</p>
{:else if error}
  <p class="error">{error}</p>
{:else if domain}
  <div class="header">
    <a href="/domains" class="back">← Back to Domains</a>
    <h2>{domain.name}</h2>
  </div>

  <div class="cards-grid">
    <a href="/domains/{domain.name}/users" class="card">
      <h3>{domain.userCount}</h3>
      <p>Users</p>
    </a>
    <a href="/domains/{domain.name}/aliases" class="card">
      <h3>{domain.aliasCount}</h3>
      <p>Aliases</p>
    </a>
  </div>
{:else}
  <p>Domain not found</p>
{/if}

<style>
  .header {
    margin-bottom: 2rem;
  }

  .back {
    display: inline-block;
    margin-bottom: 1rem;
    color: #3498db;
    text-decoration: none;
  }

  .back:hover {
    text-decoration: underline;
  }

  .error {
    color: #e74c3c;
  }

  .cards-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
  }

  .card {
    background: white;
    padding: 2rem;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    text-align: center;
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s, box-shadow 0.2s;
  }

  .card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
  }

  .card h3 {
    font-size: 3rem;
    margin: 0;
    color: #3498db;
  }

  .card p {
    margin: 0.5rem 0 0;
    color: #7f8c8d;
    font-size: 1.1rem;
  }
</style>
