<script>
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { Menu, EllipsisVertical, ChevronDown, FileText, Newspaper, HelpCircle, StickyNote, Inbox, PanelLeft, MessageCircle } 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 { queueOverview } from '$lib/stores/queueOverview';
  import { MACHINE_STATE_LABEL, machineChipClass } from '$lib/utils/queueDisplay';
  import Sidebar from '$lib/components/Sidebar.svelte';
  import SystemStatusDot from '$lib/components/SystemStatusDot.svelte';
  import QueueDrawer from '$lib/components/QueueDrawer.svelte';
  import QuickMemoButton from '$lib/components/QuickMemoButton.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'];
  // /news = 풀스크린 브리핑 → 데스크탑 상시 사이드바 없음
  const NO_SIDEBAR_PATHS = ['/news'];

  // 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);   // ⋮ 설정 메뉴
  let navMenu = $state('');        // '' | 'docs' | 'news' — 상단 드롭다운

  // 데스크탑 분류(소스트리) 사이드바 접기/펴기 — localStorage 기억. 접으면 콘텐츠가 넓어짐.
  let sidebarCollapsed = $state(
    typeof localStorage !== 'undefined' ? localStorage.getItem('sidebarCollapsed') === 'true' : false
  );
  function toggleSidebarCollapse() {
    sidebarCollapsed = !sidebarCollapsed;
    if (typeof localStorage !== 'undefined') localStorage.setItem('sidebarCollapsed', String(sidebarCollapsed));
  }

  function isActive(path) {
    return $page.url.pathname.startsWith(path);
  }
  // 그룹 active
  let docsActive = $derived(['/documents', '/library', '/audio', '/video'].some(isActive));
  let newsActive = $derived(['/news', '/digest'].some(isActive));

  onMount(async () => {
    if (!$isAuthenticated) {
      await tryRefresh();
    }
    authChecked = true;
    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)));
  let showSidebar = $derived(showChrome && !NO_SIDEBAR_PATHS.some(p => $page.url.pathname.startsWith(p)));

  // 처리 현황 스트립 (안6 라이트) — 60s 폴링 store 공유. fetch 실패/401 시
  // store 가 null → 스트립 자체를 숨김 (silent 비차단, 로그인 페이지 동일).
  let queue = $derived($queueOverview);
  let queueMacbook = $derived(queue?.machines?.find((m) => m.key === 'macbook') ?? null);
  function toggleQueueDrawer() {
    if (ui.isDrawerOpen('queue')) ui.closeDrawer();
    else ui.openDrawer('queue');
  }

  function handleKeydown(e) {
    if (e.key === '/' && !['INPUT', 'TEXTAREA'].includes(document.activeElement?.tagName)) {
      e.preventDefault();
      document.querySelector('[data-search-input]')?.focus();
    }
    if (e.key === 'Escape') {
      ui.handleEscape();
      navMenu = '';
      menuOpen = false;
    }
  }
  function nav(path) { navMenu = ''; goto(path); }
</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 gap-3 px-4 h-14 border-b border-default bg-sidebar shrink-0">
        {#if showSidebar}
          <div class="lg:hidden">
            <IconButton icon={Menu} size="sm" aria-label="사이드바" onclick={() => ui.openDrawer('sidebar')} />
          </div>
          <div class="hidden lg:block">
            <IconButton icon={PanelLeft} size="sm" aria-label={sidebarCollapsed ? '사이드바 펴기' : '사이드바 접기'}
              aria-pressed={!sidebarCollapsed} title={sidebarCollapsed ? '사이드바 펴기' : '사이드바 접기'}
              onclick={toggleSidebarCollapse} />
          </div>
        {/if}
        <a href="/" class="flex items-center gap-2 shrink-0">
          <span class="w-7 h-7 rounded-md bg-accent text-white grid place-items-center text-[10px] font-extrabold tracking-wide">DS</span>
          <span class="font-extrabold text-[15px] tracking-tight hidden sm:inline">Document Server</span>
        </a>

        <!-- 데스크탑 4그룹 -->
        <div class="hidden lg:flex items-center gap-1 ml-2">
          <a href="/" class="px-3 py-1.5 rounded-md text-sm font-semibold transition-colors {$page.url.pathname === '/' ? 'text-accent bg-accent/12' : 'text-dim hover:text-text hover:bg-surface'}">홈</a>

          <div class="relative">
            <button onclick={() => (navMenu = navMenu === 'docs' ? '' : 'docs')} aria-haspopup="menu" aria-expanded={navMenu === 'docs'}
              class="px-3 py-1.5 rounded-md text-sm font-semibold flex items-center gap-1 transition-colors {docsActive ? 'text-accent bg-accent/12' : 'text-dim hover:text-text hover:bg-surface'}">
              문서 <ChevronDown size={13} />
            </button>
            {#if navMenu === 'docs'}
              <button onclick={() => (navMenu = '')} class="fixed inset-0 z-40" aria-label="닫기"></button>
              <div class="absolute left-0 top-full z-50 mt-1 min-w-[160px] bg-surface border border-default rounded-lg shadow-lg py-1" role="menu">
                <button onclick={() => nav('/documents')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">전체 문서</button>
                <button onclick={() => nav('/library')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">자료실</button>
                <button onclick={() => nav('/audio')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">오디오</button>
                <button onclick={() => nav('/video')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">비디오</button>
              </div>
            {/if}
          </div>

          <div class="relative">
            <button onclick={() => (navMenu = navMenu === 'news' ? '' : 'news')} aria-haspopup="menu" aria-expanded={navMenu === 'news'}
              class="px-3 py-1.5 rounded-md text-sm font-semibold flex items-center gap-1 transition-colors {newsActive ? 'text-accent bg-accent/12' : 'text-dim hover:text-text hover:bg-surface'}">
              뉴스 <ChevronDown size={13} />
            </button>
            {#if navMenu === 'news'}
              <button onclick={() => (navMenu = '')} class="fixed inset-0 z-40" aria-label="닫기"></button>
              <div class="absolute left-0 top-full z-50 mt-1 min-w-[160px] bg-surface border border-default rounded-lg shadow-lg py-1" role="menu">
                <button onclick={() => nav('/news')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">아침 브리핑</button>
                <button onclick={() => nav('/digest')} class="w-full text-left px-4 py-2 text-sm text-text hover:bg-surface-hover transition-colors" role="menuitem">다이제스트</button>
              </div>
            {/if}
          </div>

          <a href="/ask" class="px-3 py-1.5 rounded-md text-sm font-semibold transition-colors {isActive('/ask') ? 'text-accent bg-accent/12' : 'text-dim hover:text-text hover:bg-surface'}">질문</a>
          <a href="/chat" class="px-3 py-1.5 rounded-md text-sm font-semibold transition-colors {isActive('/chat') ? 'text-accent bg-accent/12' : 'text-dim hover:text-text hover:bg-surface'}">이드</a>
          <SystemStatusDot />
        </div>

        <div class="flex-1"></div>

        <a href="/inbox" aria-label="받은편지함"
          class="hidden lg:grid place-items-center w-8 h-8 rounded-md border border-default transition-colors {isActive('/inbox') ? 'text-accent border-accent' : 'text-dim hover:text-accent hover:border-accent'}">
          <Inbox size={15} />
        </a>
        <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>
      </nav>

      <!-- 전 페이지 상태 스트립 (안6 라이트) — 클릭 시 우측 처리 현황 드로어 토글 -->
      {#if queue}
        <button
          type="button"
          onclick={toggleQueueDrawer}
          aria-expanded={ui.isDrawerOpen('queue')}
          aria-label="처리 현황 자세히 보기"
          class="flex items-center gap-3 px-4 py-1.5 border-b border-default bg-surface text-[11px] text-dim shrink-0 text-left hover:bg-surface-hover transition-colors overflow-x-auto"
        >
          <span class="flex items-center gap-1.5 shrink-0">
            <span class="w-2 h-2 rounded-full {queue.totals.processing > 0 ? 'bg-success' : 'bg-faint'}"></span>
            <strong class="text-text font-semibold tabular-nums">처리 중 {queue.totals.processing.toLocaleString()}</strong>
          </span>
          <span class="tabular-nums shrink-0">대기 <strong class="text-text">{queue.totals.pending.toLocaleString()}</strong></span>
          <span class="tabular-nums shrink-0 {queue.totals.failed > 0 ? 'text-error font-semibold' : ''}">실패 <strong class={queue.totals.failed > 0 ? '' : 'text-text'}>{queue.totals.failed.toLocaleString()}</strong></span>
          {#if queueMacbook}
            <span class="text-[10px] font-bold rounded-full px-2 py-0.5 shrink-0 {machineChipClass(queueMacbook.state)}">맥북 {MACHINE_STATE_LABEL[queueMacbook.state]}</span>
          {/if}
          <span class="ml-auto flex items-center gap-0.5 text-faint shrink-0">자세히 <ChevronDown size={11} /></span>
        </button>
      {/if}

      <!-- 메인: 데스크탑 상시 사이드바 + 콘텐츠 -->
      <div class="flex-1 min-h-0 flex">
        {#if showSidebar}
          <aside class="hidden lg:block shrink-0 overflow-hidden transition-[width] duration-200 ease-out {sidebarCollapsed ? 'w-0 border-r-0' : 'w-sidebar border-r border-default'}">
            <Sidebar />
          </aside>
        {/if}
        <main class="flex-1 min-w-0 overflow-auto">
          <slot />
        </main>
      </div>

      <!-- 모바일 하단 탭바 -->
      <nav class="lg:hidden shrink-0 flex border-t border-default bg-sidebar" aria-label="하단 탭">
        <a href="/documents" aria-current={docsActive ? 'page' : undefined} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold transition-colors {docsActive ? 'text-accent' : 'text-dim'}"><FileText size={18} strokeWidth={1.9} /> 문서</a>
        <a href="/news" aria-current={newsActive ? 'page' : undefined} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold transition-colors {newsActive ? 'text-accent' : 'text-dim'}"><Newspaper size={18} strokeWidth={1.9} /> 뉴스</a>
        <a href="/ask" aria-current={isActive('/ask') ? 'page' : undefined} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold transition-colors {isActive('/ask') ? 'text-accent' : 'text-dim'}"><HelpCircle size={18} strokeWidth={1.9} /> 질문</a>
        <a href="/chat" aria-current={isActive('/chat') ? 'page' : undefined} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold transition-colors {isActive('/chat') ? 'text-accent' : 'text-dim'}"><MessageCircle size={18} strokeWidth={1.9} /> 이드</a>
        <a href="/memos" aria-current={isActive('/memos') ? 'page' : undefined} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold transition-colors {isActive('/memos') ? 'text-accent' : 'text-dim'}"><StickyNote size={18} strokeWidth={1.9} /> 메모</a>
        <button onclick={() => ui.openDrawer('sidebar')} class="flex-1 flex flex-col items-center justify-center gap-1 py-2 text-[10px] font-semibold text-dim"><Menu size={18} strokeWidth={1.9} /> 더보기</button>
      </nav>

      <!-- 모바일 사이드바 드로어 (chrome 있는 모든 페이지) -->
      <div class="lg:hidden">
        <Drawer id="sidebar" side="left" width="sidebar" aria-label="사이드바">
          <Sidebar />
        </Drawer>
      </div>

      <!-- 처리 현황 드로어 (안6 라이트, 스트립 클릭 시 우측) -->
      <QueueDrawer />

      <!-- 빠른 메모 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>
