<script>
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { ChevronRight, ChevronDown, FolderOpen, Inbox, Clock, Mail, Scale } 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));
</script>

<aside class="h-full flex flex-col bg-[var(--sidebar-bg)] border-r border-[var(--border)] overflow-y-auto">
  <div class="px-4 py-3 border-b border-[var(--border)]">
    <h2 class="text-sm font-semibold text-[var(--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-[var(--accent)]/15 text-[var(--accent)]' : 'text-[var(--text)] hover:bg-[var(--surface)]'}"
    >
      <span class="flex items-center gap-2">
        <FolderOpen size={16} />
        전체 문서
      </span>
      {#if totalCount > 0}
        <span class="text-xs text-[var(--text-dim)]">{totalCount}</span>
      {/if}
    </button>
  </div>

  <!-- 트리 -->
  <nav class="flex-1 px-2 py-2">
    {#if loading}
      {#each Array(5) as _}
        <div class="h-8 bg-[var(--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-[var(--surface)] text-[var(--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)}
              class="flex-1 flex items-center justify-between px-2 py-1.5 rounded-md text-sm transition-colors
                {isActive ? 'bg-[var(--accent)]/15 text-[var(--accent)]' : isParent ? 'text-[var(--text)]' : 'text-[var(--text-dim)] hover:bg-[var(--surface)] hover:text-[var(--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-[var(--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-[var(--border)]">
    <h3 class="px-3 py-1 text-[10px] font-semibold text-[var(--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-[var(--text-dim)] hover:bg-[var(--surface)] hover:text-[var(--text)]"
    >
      <Clock size={14} /> 최근 7일
    </button>
    <button
      onclick={() => { const p = new URLSearchParams(); p.set('source', 'law_monitor'); goto(`/documents?${p}`, { noScroll: true }); }}
      class="w-full flex items-center gap-2 px-3 py-1.5 rounded-md text-sm text-[var(--text-dim)] hover:bg-[var(--surface)] hover:text-[var(--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-[var(--text-dim)] hover:bg-[var(--surface)] hover:text-[var(--text)]"
    >
      <Mail size={14} /> 이메일
    </button>
  </div>

  <!-- Inbox -->
  <div class="px-2 py-2 border-t border-[var(--border)]">
    <a
      href="/inbox"
      class="flex items-center justify-between px-3 py-2 rounded-md text-sm text-[var(--text)] hover:bg-[var(--surface)] transition-colors"
    >
      <span class="flex items-center gap-2">
        <Inbox size={16} />
        받은편지함
      </span>
    </a>
  </div>
</aside>
