<script lang="ts">
  import { page } from '$app/state'
  import { goto } from '$app/navigation'

  let { children, data } = $props()

  const publicNav = [
    { href: '/', label: '시세' },
    { href: '/theme', label: '테마' },
    { href: '/kospi200', label: '코스피200' },
  ]

  const protectedNav = [
    { href: '/asset', label: '자산' },
    { href: '/autotrade', label: '자동매매' },
  ]

  let loggedIn = $derived(data.loggedIn)

  async function logout() {
    await fetch('/logout', { method: 'POST', credentials: 'include' })
    goto('/login')
  }

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

<div class="min-h-screen flex flex-col bg-gray-900">
  <!-- 헤더 네비게이션 -->
  <header class="bg-gray-800 border-b border-gray-700 sticky top-0 z-30">
    <div class="max-w-screen-2xl mx-auto px-4">
      <div class="flex items-center h-14 gap-6">
        <!-- 로고 -->
        <a href="/" class="text-white font-bold text-lg shrink-0">📈 StockSearch</a>

        <!-- 네비 링크 -->
        <nav class="flex items-center gap-1 flex-1">
          {#each publicNav as item}
            <a
              href={item.href}
              class="px-3 py-1.5 rounded-md text-sm font-medium transition-colors
                {isActive(item.href)
                  ? 'bg-blue-600 text-white'
                  : 'text-gray-300 hover:text-white hover:bg-gray-700'}"
            >
              {item.label}
            </a>
          {/each}
          {#if loggedIn}
            {#each protectedNav as item}
              <a
                href={item.href}
                class="px-3 py-1.5 rounded-md text-sm font-medium transition-colors
                  {isActive(item.href)
                    ? 'bg-blue-600 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'}"
              >
                {item.label}
              </a>
            {/each}
          {/if}
        </nav>

        <!-- 로그인/로그아웃 -->
        {#if loggedIn}
          <button
            onclick={logout}
            class="text-xs text-gray-400 hover:text-white transition-colors shrink-0"
          >
            로그아웃
          </button>
        {:else}
          <a
            href="/login"
            class="text-xs text-gray-400 hover:text-white transition-colors shrink-0"
          >
            로그인
          </a>
        {/if}
      </div>
    </div>
  </header>

  <!-- 메인 콘텐츠 -->
  <main class="flex-1 max-w-screen-2xl mx-auto w-full px-4 py-6">
    {@render children()}
  </main>
</div>
