<script>
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { ChevronRight, ChevronDown, FolderOpen, FolderTree, Inbox, Clock, Mail, Scale, StickyNote, GraduationCap, CalendarCheck, MessageCircle } from 'lucide-svelte';

  let tree = $state([]);
  let loading = $state(true);
  let expanded = $state({});

  let activeDomain = $derived($page.url.searchParams.get('domain'));

  const DOMAIN_COLORS = {
    'Philosophy': 'var(--domain-philosophy)',
    'Language': 'var(--domain-language)',
    'Engineering': 'var(--domain-engineering)',
    'Industrial_Safety': 'var(--domain-safety)',
    'Programming': 'var(--domain-programming)',
    'General': 'var(--domain-general)',
    'Reference': 'var(--domain-reference)',
  };

  async function loadTree() {
    loading = true;
    try {
      tree = await api('/documents/tree');
    } catch (err) {
      console.error('트리 로딩 실패:', err);
    } finally {
      loading = false;
    }
  }

  function toggleExpand(path) {
    expanded[path] = !expanded[path];
  }

  function navigate(path) {
    const params = new URLSearchParams($page.url.searchParams);
    params.delete('page');
    if (path) {
      params.set('domain', path);
    } else {
      params.delete('domain');
    }
    params.delete('sub_group');
    for (const [key, val] of [...params.entries()]) {
      if (!val) params.delete(key);
    }
    const qs = params.toString();
    goto(`/documents${qs ? '?' + qs : ''}`, { noScroll: true });
  }

  $effect(() => { loadTree(); });

  $effect(() => {
    if (activeDomain) {
      // 선택된 경로의 부모들 자동 펼치기
      const parts = activeDomain.split('/');
      let path = '';
      for (const part of parts) {
        path = path ? `${path}/${part}` : part;
        expanded[path] = true;
      }
    }
  });

  let totalCount = $derived(tree.reduce((sum, n) => sum + n.count, 0));

  // ArrowUp/Down 키보드 nav — 현재 펼쳐진 tree-row만 traverse
  function handleTreeKeydown(e) {
    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
    const root = e.currentTarget;
    const rows = Array.from(root.querySelectorAll('[data-tree-row]'));
    if (rows.length === 0) return;
    const active = document.activeElement;
    const idx = active ? rows.indexOf(active) : -1;
    let next;
    if (e.key === 'ArrowDown') {
      next = idx < 0 ? 0 : Math.min(idx + 1, rows.length - 1);
    } else {
      next = idx <= 0 ? 0 : idx - 1;
    }
    e.preventDefault();
    rows[next].focus();
  }
</script>

<aside class="h-full flex flex-col bg-sidebar border-r border-default overflow-y-auto">
  <div class="px-4 py-3 border-b border-default">
    <h2 class="text-sm font-semibold text-dim uppercase tracking-wider">분류</h2>
  </div>

  <!-- 전체 문서 -->
  <div class="px-2 pt-2">
    <button
      onclick={() => navigate(null)}
      class="w-full flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors
        {!activeDomain ? 'bg-accent/15 text-accent' : 'text-text hover:bg-surface'}"
    >
      <span class="flex items-center gap-2">
        <FolderOpen size={16} />
        전체 문서
      </span>
      {#if totalCount > 0}
        <span class="text-xs text-dim">{totalCount}</span>
      {/if}
    </button>
  </div>

  <!-- 트리 -->
  <nav class="flex-1 px-2 py-2" onkeydown={handleTreeKeydown}>
    {#if loading}
      {#each Array(5) as _}
        <div class="h-8 bg-surface rounded-md animate-pulse mx-1 mb-1"></div>
      {/each}
    {:else}
      {#each tree as node}
        {@const color = DOMAIN_COLORS[node.name] || 'var(--text-dim)'}
        {#snippet treeNode(n, depth)}
          {@const isActive = activeDomain === n.path}
          {@const isParent = activeDomain?.startsWith(n.path + '/')}
          {@const hasChildren = n.children.length > 0}
          {@const isExpanded = expanded[n.path]}

          <div class="flex items-center" style="padding-left: {depth * 16}px">
            {#if hasChildren}
              <button
                onclick={() => toggleExpand(n.path)}
                class="p-0.5 rounded hover:bg-surface text-dim"
              >
                {#if isExpanded}
                  <ChevronDown size={14} />
                {:else}
                  <ChevronRight size={14} />
                {/if}
              </button>
            {:else}
              <span class="w-5"></span>
            {/if}

            <button
              onclick={() => navigate(n.path)}
              data-tree-row
              aria-current={isActive ? 'page' : undefined}
              class="flex-1 flex items-center justify-between px-2 py-1.5 rounded-md text-sm transition-colors
                {isActive ? 'bg-accent/15 text-accent' : isParent ? 'text-text' : 'text-dim hover:bg-surface hover:text-text'}"
            >
              <span class="flex items-center gap-2">
                {#if depth === 0}
                  <span class="w-2 h-2 rounded-full shrink-0" style="background: {color}"></span>
                {/if}
                <span class="truncate">{n.name}</span>
              </span>
              <span class="text-xs text-dim shrink-0 ml-2">{n.count}</span>
            </button>
          </div>

          {#if hasChildren && isExpanded}
            {#each n.children as child}
              {@render treeNode(child, depth + 1)}
            {/each}
          {/if}
        {/snippet}
        {@render treeNode(node, 0)}
      {/each}
    {/if}
  </nav>

  <!-- 스마트 그룹 -->
  <div class="px-2 py-2 border-t border-default">
    <h3 class="px-3 py-1 text-[10px] font-semibold text-dim uppercase tracking-wider">스마트 그룹</h3>
    <button
      onclick={() => goto('/documents', { noScroll: true })}
      class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm text-dim hover:bg-surface hover:text-text"
    >
      <Clock size={14} /> 최근 7일
    </button>
    <button
      onclick={() => { const p = new URLSearchParams(); p.set('category', 'law'); goto(`/documents?${p}`, { noScroll: true }); }}
      class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm text-dim hover:bg-surface hover:text-text"
    >
      <Scale size={14} /> 법령 알림
    </button>
    <button
      onclick={() => { const p = new URLSearchParams(); p.set('source', 'email'); goto(`/documents?${p}`, { noScroll: true }); }}
      class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm text-dim hover:bg-surface hover:text-text"
    >
      <Mail size={14} /> 이메일
    </button>
    <a
      href="/library"
      class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm transition-colors
        {$page.url.pathname === '/library' ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface hover:text-text'}"
    >
      <FolderTree size={14} /> 자료실
    </a>
  </div>

  <!-- 메모 & Inbox -->
  <div class="px-2 py-2 border-t border-default">
    <a
      href="/memos"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors
        {$page.url.pathname === '/memos' ? 'bg-accent/15 text-accent' : 'text-text hover:bg-surface'}"
    >
      <span class="flex items-center gap-2">
        <StickyNote size={16} />
        메모
      </span>
    </a>
    <a
      href="/events"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors
        {$page.url.pathname.startsWith('/events') ? 'bg-accent/15 text-accent' : 'text-text hover:bg-surface'}"
    >
      <span class="flex items-center gap-2">
        <CalendarCheck size={16} />
        events
      </span>
    </a>
    <a
      href="/study"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors
        {$page.url.pathname.startsWith('/study') ? 'bg-accent/15 text-accent' : 'text-text hover:bg-surface'}"
    >
      <span class="flex items-center gap-2">
        <GraduationCap size={16} />
        공부
      </span>
    </a>
    <a
      href="/chat"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors
        {$page.url.pathname.startsWith('/chat') ? 'bg-accent/15 text-accent' : 'text-text hover:bg-surface'}"
    >
      <span class="flex items-center gap-2">
        <MessageCircle size={16} />
        이드
      </span>
    </a>
    <a
      href="/inbox"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm text-text hover:bg-surface transition-colors"
    >
      <span class="flex items-center gap-2">
        <Inbox size={16} />
        받은편지함
      </span>
    </a>
  </div>
</aside>
