<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>

<div class="space-y-6">
  <div class="flex items-center gap-4">
    <a href="/domains" class="btn btn-ghost btn-sm">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
      </svg>
      Back to Domains
    </a>
    {#if domain}
      <h2 class="text-2xl font-bold">{domain.name}</h2>
    {/if}
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  {:else if error}
    <div class="alert alert-error">
      <span>{error}</span>
    </div>
  {:else if domain}
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl">
      <a href="/domains/{domain.name}/users" 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">{domain.userCount}</h2>
          <p class="text-base-content/60">Users</p>
        </div>
      </a>
      
      <a href="/domains/{domain.name}/aliases" 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">{domain.aliasCount}</h2>
          <p class="text-base-content/60">Aliases</p>
        </div>
      </a>
    </div>
  {:else}
    <div class="alert">
      <span>Domain not found</span>
    </div>
  {/if}
</div>
