<script lang="ts">
  import { page } from '$app/state';
  import { goto } from '$app/navigation';
  import { ChevronDown } from 'lucide-svelte';
  import { user, logout } from '$lib/auth/store.svelte';
  import { player } from '$lib/player/store.svelte';
  import { appName } from '$lib/branding';
  import PlayerBar from './PlayerBar.svelte';
  import SearchInput from './SearchInput.svelte';

  let { children } = $props<{ children: import('svelte').Snippet }>();

  let menuOpen = $state(false);
  let menuRef: HTMLElement | undefined = $state();
  let menuButtonRef: HTMLElement | undefined = $state();

  // Close the dropdown when the click was outside both the button and the menu.
  // The previous implementation used onclick={(e) => e.stopPropagation()} on the
  // menu container, which kept the window-level close-on-outside-click handler
  // from firing — but it also blocked SvelteKit's document-level link-click
  // interceptor, so clicking Admin/Settings inside the dropdown fell through
  // to the browser's native navigation (a full-page reload). On a hard reload,
  // /admin/+layout.ts's load function ran before bootstrap() settled the user
  // store, so the admin guard saw user.value === null and redirected to /.
  function handleWindowClick(e: MouseEvent) {
    if (!menuOpen) return;
    const target = e.target as Node | null;
    if (!target) return;
    if (menuRef?.contains(target) || menuButtonRef?.contains(target)) return;
    menuOpen = false;
  }

  async function handleLogout() {
    menuOpen = false;
    await logout();
    goto('/login', { replaceState: true });
  }

  function isActive(href: string): boolean {
    if (href === '/') return page.url.pathname === '/';
    return page.url.pathname.startsWith(href);
  }

  // Search reaches /search via the global SearchInput in the header (not the
  // nav). Requests is a tab inside Discover. Settings + Admin live in the
  // username dropdown — they're per-operator chrome, not primary surfaces.
  const navItems = [
    { href: '/',                label: 'Home' },
    { href: '/library/artists', label: 'Artists' },
    { href: '/library/albums',  label: 'Albums' },
    { href: '/library/liked',   label: 'Liked' },
    { href: '/discover',        label: 'Discover' },
    { href: '/playlists',       label: 'Playlists' }
  ];
</script>

<svelte:window onclick={handleWindowClick} onkeydown={(e) => e.key === 'Escape' && (menuOpen = false)} />

<div class="grid h-screen grid-cols-[auto_1fr] grid-rows-[auto_1fr_auto] bg-background text-text-primary">
  <header class="col-span-2 flex items-center gap-4 border-b border-border bg-surface px-4 py-3">
    <div class="font-semibold">{appName()}</div>
    <div class="flex-1">
      <SearchInput />
    </div>
    <div class="relative">
      <button
        bind:this={menuButtonRef}
        type="button"
        class="flex items-center gap-1.5 rounded px-3 py-1 hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
        aria-haspopup="menu"
        aria-expanded={menuOpen}
        onclick={() => (menuOpen = !menuOpen)}
      >
        <span>{user.value?.username ?? ''}</span>
        <ChevronDown
          size={16}
          strokeWidth={1}
          class="transition-transform {menuOpen ? 'rotate-180' : ''}"
          aria-hidden="true"
        />
      </button>
      {#if menuOpen}
        <div
          bind:this={menuRef}
          class="absolute right-0 z-50 mt-1 w-40 rounded border border-border bg-surface shadow"
          role="menu"
          tabindex="-1"
        >
          <a
            href="/settings"
            role="menuitem"
            class="block px-3 py-2 text-sm hover:bg-surface-hover"
            onclick={() => (menuOpen = false)}
          >
            Settings
          </a>
          {#if user.value?.is_admin}
            <a
              href="/admin"
              role="menuitem"
              class="block px-3 py-2 text-sm hover:bg-surface-hover"
              onclick={() => (menuOpen = false)}
            >
              Admin
            </a>
          {/if}
          <button
            type="button"
            role="menuitem"
            class="block w-full border-t border-border px-3 py-2 text-left text-sm hover:bg-surface-hover"
            onclick={handleLogout}
          >
            Log out
          </button>
        </div>
      {/if}
    </div>
  </header>

  <nav class="hidden w-48 border-r border-border bg-surface md:block">
    <ul class="p-2">
      {#each navItems as item}
        <li>
          <a
            href={item.href}
            class="block rounded px-3 py-2 hover:bg-surface-hover"
            aria-current={isActive(item.href) ? 'page' : undefined}
          >
            {item.label}
          </a>
        </li>
      {/each}
    </ul>
  </nav>

  <main class="overflow-y-auto p-4 md:col-start-2">
    {@render children?.()}
  </main>

  {#if player.current}
    <div class="col-span-2">
      <PlayerBar />
    </div>
  {/if}
</div>
