<script lang="ts">
  interface Domain {
    id: number;
    name: string;
    userCount: number;
    aliasCount: number;
  }

  interface UserInfo {
    id: number;
    username: string;
    role: string;
    domains: string[];
  }

  let domains = $state<Domain[]>([]);
  let user = $state<UserInfo | null>(null);
  let loading = $state(true);
  let showModal = $state(false);
  let newDomain = $state({ name: '' });

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

  async function loadData() {
    try {
      const [domainsRes, userRes] = await Promise.all([
        fetchWithAuth('/api/domains'),
        fetchWithAuth('/api/auth/me')
      ]);

      if (domainsRes.data) {
        domains = domainsRes.data || [];
      }
      if (userRes.data) {
        user = userRes.data;
      }
    } catch (e) {
      console.error('Failed to load data:', e);
    } finally {
      loading = false;
    }
  }

  async function createDomain() {
    try {
      const res = await fetch('/api/domains', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}` },
        body: JSON.stringify(newDomain)
      });
      if (res.ok) {
        showModal = false;
        newDomain = { name: '' };
        await loadData();
      }
    } catch (e) {
      console.error('Failed to create domain:', e);
    }
  }

  async function deleteDomain(id: number) {
    if (!confirm('Delete this domain? Users and aliases will be deleted.')) return;
    try {
      await fetch(`/api/domains/${id}`, { 
        method: 'DELETE',
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      await loadData();
    } catch (e) {
      console.error('Failed to delete domain:', e);
    }
  }

  function isAdmin() {
    return user?.role === 'admin';
  }

  $effect(() => { loadData(); });
</script>

<div class="header">
  <h2>Domains</h2>
  {#if isAdmin()}
    <button onclick={() => showModal = true}>Add Domain</button>
  {/if}
</div>

{#if user && !isAdmin() && user.domains.length > 0}
  <h3>Your Domains</h3>
  <div class="domains-grid">
    {#each user.domains as domainName}
      <a href="/domains/{domainName}/users" class="domain-card">
        <span class="domain-name">{domainName}</span>
        <span class="domain-links">Manage →</span>
      </a>
    {/each}
  </div>
{/if}

{#if loading}
  <p>Loading...</p>
{:else if isAdmin() && domains.length === 0}
  <p>No domains configured yet.</p>
{:else if isAdmin()}
  <h3>All Domains</h3>
  <table>
    <thead>
      <tr>
        <th>Domain</th>
        <th>Users</th>
        <th>Aliases</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {#each domains as domain}
        <tr>
          <td><a href="/domains/{domain.name}/users">{domain.name}</a></td>
          <td>{domain.userCount}</td>
          <td>{domain.aliasCount}</td>
          <td>
            <button class="danger" onclick={() => deleteDomain(domain.id)}>Delete</button>
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

{#if showModal}
  <button class="modal-backdrop" onclick={() => showModal = false} aria-label="Close modal"></button>
  <div class="modal">
    <h3>Add Domain</h3>
    <form onsubmit={(e) => { e.preventDefault(); createDomain(); }}>
      <label>
        Domain name:
        <input type="text" bind:value={newDomain.name} placeholder="example.org" required />
      </label>
      <div class="actions">
        <button type="button" onclick={() => showModal = false}>Cancel</button>
        <button type="submit">Create</button>
      </div>
    </form>
  </div>
{/if}

<style>
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
  }

  h3 {
    color: #2c3e50;
    margin-top: 1.5rem;
  }

  .domains-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 1rem;
    margin-top: 1rem;
  }

  .domain-card {
    background: white;
    padding: 1rem 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s, box-shadow 0.2s;
  }

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

  .domain-name {
    font-weight: 600;
    color: #2c3e50;
  }

  .domain-links {
    color: #3498db;
    font-size: 0.9rem;
  }

  table {
    width: 100%;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    margin-top: 1rem;
  }

  th, td {
    padding: 1rem;
    text-align: left;
    border-bottom: 1px solid #eee;
  }

  th {
    background: #f8f9fa;
    font-weight: 600;
  }

  button {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background: #3498db;
    color: white;
  }

  button.danger {
    background: #e74c3c;
  }

  .modal-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    border: none;
    cursor: pointer;
    z-index: 100;
  }

  .modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 2rem;
    border-radius: 8px;
    min-width: 400px;
    z-index: 101;
  }

  .modal h3 {
    margin-top: 0;
  }

  .modal form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .modal label {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .modal input {
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
  }
</style>
