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

  let { children } = $props();
  let user: { username?: string; email?: string; role?: string } | null = $state(null);
  let selectedDomain = $state<string | null>(null);
  let loading = $state(true);
  let showDropdown = $state(false);
  let dropdownRef = $state<HTMLDivElement | null>(null);

  let usersLink = $derived(selectedDomain ? `/domains/${selectedDomain}/users` : '/domains');
  let aliasesLink = $derived(selectedDomain ? `/domains/${selectedDomain}/aliases` : '/domains');
  let isInitialized = $state(false);

  onMount(() => {
    selectedDomain = localStorage.getItem('selectedDomain');
    isInitialized = true;

    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef && !dropdownRef.contains(event.target as Node)) {
        showDropdown = false;
      }
    }

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  });

  $effect(() => {
    if (!isInitialized) return;
    const path = $page.url.pathname;
    const match = path.match(/^\/domains\/([^/]+)/);
    if (match) {
      selectedDomain = match[1];
      localStorage.setItem('selectedDomain', selectedDomain);
    }
  });

  $effect(() => {
    const path = $page.url.pathname;
    if (!path.startsWith('/auth/')) {
      checkAuth();
    } else {
      loading = false;
    }
  });

  async function checkAuth() {
    const token = localStorage.getItem('token');
    if (!token) {
      goto('/auth/login');
      return;
    }

    try {
      const res = await fetch('/api/auth/me', {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      if (!res.ok) {
        goto('/auth/login');
        return;
      }

      const data = await res.json();
      user = data.data;

      if (user?.role !== 'admin') {
        goto('/auth/dashboard');
        return;
      }
    } catch {
      goto('/auth/login');
    } finally {
      loading = false;
    }
  }

  function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('selectedDomain');
    user = null;
    selectedDomain = null;
    showDropdown = false;
    goto('/auth/login');
  }

  function toggleDropdown(event: MouseEvent) {
    event.stopPropagation();
    showDropdown = !showDropdown;
  }
</script>

{#if loading}
  <div class="loading">Loading...</div>
{:else if user?.role === 'admin'}
  <div class="app">
    <header>
      <h1>IMC Vibe</h1>
      <nav>
        <a href="/">Dashboard</a>
        <a href="/domains">Domains</a>
        {#if selectedDomain}
          <a href={usersLink}>Users</a>
          <a href={aliasesLink}>Aliases</a>
        {/if}
        <a href="/queue">Queue</a>
        <a href="/logs">Logs</a>
      </nav>
      <div class="user-menu" bind:this={dropdownRef}>
        <button class="dropdown-trigger" onclick={toggleDropdown}>
          <span class="username">{user.username || user.email}</span>
          <span class="arrow" class:open={showDropdown}>▼</span>
        </button>
        {#if showDropdown}
          <div class="dropdown">
            <a href="/auth/change-password" onclick={() => showDropdown = false}>Change Password</a>
            <button class="logout-btn" onclick={logout}>Logout</button>
          </div>
        {/if}
      </div>
    </header>

    <main>
      {@render children()}
    </main>
  </div>
{:else}
  {@render children()}
{/if}

<style>
  .loading {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    color: #666;
  }

  :global(body) {
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
    background: #f5f5f5;
  }

  .app {
    min-height: 100vh;
  }

  header {
    background: #2c3e50;
    color: white;
    padding: 0.75rem 2rem;
    display: flex;
    align-items: center;
    gap: 2rem;
    flex-wrap: wrap;
  }

  h1 {
    margin: 0;
    font-size: 1.25rem;
  }

  nav {
    display: flex;
    gap: 0.5rem;
    flex: 1;
  }

  nav a {
    color: #ecf0f1;
    text-decoration: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    font-size: 0.9rem;
    transition: background 0.2s;
  }

  nav a:hover {
    background: #34495e;
  }

  main {
    padding: 2rem;
    max-width: 1400px;
    margin: 0 auto;
  }

  .user-menu {
    position: relative;
  }

  .dropdown-trigger {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background: transparent;
    border: 1px solid #7f8c8d;
    color: #ecf0f1;
    padding: 0.375rem 0.75rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
    transition: background 0.2s;
  }

  .dropdown-trigger:hover {
    background: #34495e;
  }

  .username {
    font-weight: 500;
  }

  .arrow {
    font-size: 0.7rem;
    transition: transform 0.2s;
  }

  .arrow.open {
    transform: rotate(180deg);
  }

  .dropdown {
    position: absolute;
    top: 100%;
    right: 0;
    margin-top: 0.5rem;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    min-width: 160px;
    overflow: hidden;
    z-index: 1000;
  }

  .dropdown a {
    display: block;
    padding: 0.75rem 1rem;
    color: #2c3e50;
    text-decoration: none;
    font-size: 0.9rem;
    transition: background 0.2s;
  }

  .dropdown a:hover {
    background: #f5f5f5;
  }

  .dropdown .logout-btn {
    display: block;
    width: 100%;
    padding: 0.75rem 1rem;
    background: transparent;
    border: none;
    color: #e74c3c;
    text-align: left;
    font-size: 0.9rem;
    cursor: pointer;
    transition: background 0.2s;
  }

  .dropdown .logout-btn:hover {
    background: #f5f5f5;
  }
</style>
