<script>
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { Menu, EllipsisVertical } from 'lucide-svelte';
  import { isAuthenticated, user, tryRefresh, logout } from '$lib/stores/auth';
  import { toasts, removeToast } from '$lib/stores/toast';
  import { refresh as refreshPublicConfig } from '$lib/stores/config';
  import { ui } from '$lib/stores/uiState.svelte';
  import Sidebar from '$lib/components/Sidebar.svelte';
  import SystemStatusDot from '$lib/components/SystemStatusDot.svelte';
  import QuickMemoButton from '$lib/components/QuickMemoButton.svelte';
  import Button from '$lib/components/ui/Button.svelte';
  import IconButton from '$lib/components/ui/IconButton.svelte';
  import Drawer from '$lib/components/ui/Drawer.svelte';
  import '../app.css';

  const PUBLIC_PATHS = ['/login', '/setup', '/__styleguide'];
  const NO_CHROME_PATHS = ['/login', '/setup', '/__styleguide'];

  // toast 의미 토큰 매핑 (A-8 B3)
  const TOAST_CLASS = {
    success: 'bg-success/10 text-success border-success/30',
    error:   'bg-error/10 text-error border-error/30',
    warning: 'bg-warning/10 text-warning border-warning/30',
    info:    'bg-accent/10 text-accent border-accent/30',
  };

  let authChecked = $state(false);
  let menuOpen = $state(false);

  function isActive(path) {
    return $page.url.pathname.startsWith(path);
  }

  onMount(async () => {
    if (!$isAuthenticated) {
      await tryRefresh();
    }
    authChecked = true;
    // 공개 설정 prewarm (인증 상태와 독립적). 실패 시 fallback 유지.
    void refreshPublicConfig();
  });

  $effect(() => {
    if (browser && authChecked && !$isAuthenticated && !PUBLIC_PATHS.some(p => $page.url.pathname.startsWith(p))) {
      goto('/login');
    }
  });

  let showChrome = $derived($isAuthenticated && !NO_CHROME_PATHS.some(p => $page.url.pathname.startsWith(p)));

  function handleKeydown(e) {
    if (e.key === '/' && !['INPUT', 'TEXTAREA'].includes(document.activeElement?.tagName)) {
      e.preventDefault();
      document.querySelector('[data-search-input]')?.focus();
    }
    if (e.key === 'Escape') {
      // 5대 원칙 #2 — 글로벌 Esc는 uiState에 위임 (modal stack → drawer 우선순위 자동 처리)
      ui.handleEscape();
    }
  }
</script>

<svelte:window on:keydown={handleKeydown} />

{#if !authChecked}
  <div class="min-h-screen flex items-center justify-center">
    <p class="text-dim">로딩 중...</p>
  </div>
{:else if $isAuthenticated || PUBLIC_PATHS.some(p => $page.url.pathname.startsWith(p))}
  {#if showChrome}
    <div class="h-screen flex flex-col">
      <!-- 상단 nav -->
      <nav class="flex items-center justify-between px-4 py-2 border-b border-default bg-surface shrink-0">
        <div class="flex items-center gap-3">
          {#if !$page.url.pathname.startsWith('/news')}
            <IconButton
              icon={Menu}
              size="sm"
              aria-label="사이드바 토글"
              onclick={() => ui.openDrawer('sidebar')}
            />
          {/if}
          <a href="/" class="text-sm font-semibold hover:text-accent">PKM</a>
          <span class="text-dim text-xs">/</span>
          <a href="/documents" class="text-xs hover:text-accent {isActive('/documents') ? 'text-accent' : ''}">문서</a>
          <span class="text-faint text-xs">·</span>
          <a href="/library" class="text-xs hover:text-accent {isActive('/library') ? 'text-accent' : ''}">자료실</a>
          <span class="text-faint text-xs">·</span>
          <a href="/audio" class="text-xs hover:text-accent {isActive('/audio') ? 'text-accent' : ''}">오디오</a>
          <span class="text-faint text-xs">·</span>
          <a href="/video" class="text-xs hover:text-accent {isActive('/video') ? 'text-accent' : ''}">비디오</a>
          <SystemStatusDot />
        </div>
        <div class="flex items-center gap-1">
          <Button variant="ghost" size="sm" href="/ask" class={isActive('/ask') ? 'text-accent' : ''}>질문</Button>
          <Button variant="ghost" size="sm" href="/memos" class={isActive('/memos') ? 'text-accent' : ''}>메모</Button>
          <Button variant="ghost" size="sm" href="/study" class={isActive('/study') ? 'text-accent' : ''}>공부</Button>
          <Button variant="ghost" size="sm" href="/news" class={isActive('/news') ? 'text-accent' : ''}>아침 브리핑</Button>
          <Button variant="ghost" size="sm" href="/inbox" class={isActive('/inbox') ? 'text-accent' : ''}>Inbox</Button>
          <div class="relative">
            <IconButton
              icon={EllipsisVertical}
              size="sm"
              aria-label="메뉴"
              aria-expanded={menuOpen}
              aria-haspopup="menu"
              onclick={() => (menuOpen = !menuOpen)}
            />
            {#if menuOpen}
              <button
                onclick={() => (menuOpen = false)}
                class="fixed inset-0 z-40"
                aria-label="메뉴 닫기"
              ></button>
              <div class="absolute right-0 top-full z-50 mt-1 min-w-[140px] bg-surface border border-default rounded-lg shadow-lg py-1" role="menu">
                <a
                  href="/settings"
                  onclick={() => (menuOpen = false)}
                  class="block px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors"
                  role="menuitem"
                >설정</a>
                <button
                  onclick={() => { menuOpen = false; logout(); }}
                  class="w-full text-left px-4 py-2 text-sm text-error hover:bg-error/10 transition-colors"
                  role="menuitem"
                >로그아웃</button>
              </div>
            {/if}
          </div>
        </div>
      </nav>

      <!-- 메인 -->
      <div class="flex-1 min-h-0 relative">
        <!-- 사이드바 드로어 (모든 화면에서 동일, uiState 단일 slot 관리) -->
        <Drawer id="sidebar" side="left" width="sidebar" aria-label="사이드바">
          <Sidebar />
        </Drawer>

        <!-- 콘텐츠 -->
        <main class="h-full overflow-auto">
          <slot />
        </main>
      </div>

      <!-- 빠른 메모 FAB (모든 페이지) -->
      <QuickMemoButton />
    </div>
  {:else}
    <slot />
  {/if}
{/if}

<!-- Toast -->
<div class="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm" role="status" aria-live="polite">
  {#each $toasts as toast (toast.id)}
    <button
      class="px-4 py-3 rounded-lg shadow-lg text-sm flex items-center gap-2 cursor-pointer text-left border {TOAST_CLASS[toast.type] || TOAST_CLASS.info}"
      onclick={() => removeToast(toast.id)}
    >
      {toast.message}
    </button>
  {/each}
</div>
