<script>
  // 자료실 경로 편집기 — user_tags에서 @library/ 접두사 관리
  import { onMount } from 'svelte';
  import { X, Plus, FolderPlus } from 'lucide-svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';

  let { doc } = $props();

  const PREFIX = '@library/';

  let libraryPaths = $derived(
    (doc.user_tags || [])
      .filter((t) => t.startsWith(PREFIX))
      .map((t) => t.slice(PREFIX.length))
  );

  let newPath = $state('');
  let editing = $state(false);
  let existingPaths = $state([]);
  let showSuggestions = $state(false);
  let showCategoryPicker = $state(false);
  let categoryFilter = $state('');

  let suggestions = $derived(
    newPath.length >= 1
      ? existingPaths
          .filter(
            (p) => p.toLowerCase().includes(newPath.toLowerCase()) && !libraryPaths.includes(p)
          )
          .slice(0, 5)
      : []
  );

  let filteredCategories = $derived(
    categoryFilter
      ? existingPaths.filter(
          (p) => p.toLowerCase().includes(categoryFilter.toLowerCase()) && !libraryPaths.includes(p)
        )
      : existingPaths.filter((p) => !libraryPaths.includes(p))
  );

  // 입력 정규화 미리보기
  let normalizedPreview = $derived(() => {
    try {
      return normalizePath(newPath);
    } catch {
      return null;
    }
  });

  $effect(() => {
    if (doc) {
      newPath = '';
      editing = false;
    }
  });

  onMount(async () => {
    try {
      const categories = await api('/library/categories');
      existingPaths = categories.map((c) => c.path);
    } catch {
      /* 자동완성 실패해도 입력은 가능 */
    }
  });

  function normalizePath(raw) {
    const stripped = raw.trim().replace(/^\/+|\/+$/g, '');
    if (!stripped) throw new Error('빈 경로');
    const segments = stripped.split('/');
    const normalized = [];
    for (const s of segments) {
      const trimmed = s.trim();
      if (!trimmed) throw new Error('빈 세그먼트');
      if (trimmed.length > 30) throw new Error('세그먼트 30자 초과');
      normalized.push(trimmed);
    }
    if (normalized.length > 5) throw new Error('최대 5단계');
    return normalized.join('/');
  }

  async function addPath(rawPath) {
    let path;
    try {
      path = normalizePath(rawPath);
    } catch (e) {
      addToast('error', e.message);
      return;
    }
    const tag = `${PREFIX}${path}`;
    if ((doc.user_tags || []).includes(tag)) {
      addToast('warning', '이미 등록된 경로');
      return;
    }
    const updated = [...(doc.user_tags || []), tag];
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ user_tags: updated }),
      });
      doc.user_tags = updated;
      newPath = '';
      addToast('success', '자료실 경로 추가됨');
    } catch {
      addToast('error', '경로 추가 실패');
    }
  }

  async function removePath(pathToRemove) {
    const tag = `${PREFIX}${pathToRemove}`;
    const updated = (doc.user_tags || []).filter((t) => t !== tag);
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ user_tags: updated }),
      });
      doc.user_tags = updated;
      addToast('success', '경로 삭제됨');
    } catch {
      addToast('error', '경로 삭제 실패');
    }
  }

  function selectSuggestion(path) {
    addPath(path);
    showSuggestions = false;
  }
</script>

<div>
  <h4 class="text-xs font-semibold text-dim uppercase mb-1.5 flex items-center gap-1">
    <FolderPlus size={12} />
    자료실 경로
  </h4>

  <!-- 현재 경로 목록 -->
  {#if libraryPaths.length > 0}
    <div class="flex flex-col gap-1 mb-2">
      {#each libraryPaths as path}
        <div
          class="flex items-center justify-between gap-1 px-2 py-1 bg-bg border border-default rounded text-xs"
        >
          <span class="text-text truncate" title={path}>{path}</span>
          <button
            type="button"
            onclick={() => removePath(path)}
            class="text-dim hover:text-error shrink-0"
            aria-label="{path} 삭제"
            title="삭제"
          >
            <X size={10} />
          </button>
        </div>
      {/each}
    </div>
  {/if}

  <!-- 입력 영역 -->
  {#if editing}
    <div class="relative">
      <form
        onsubmit={(e) => {
          e.preventDefault();
          addPath(newPath);
        }}
        class="flex gap-1"
      >
        <input
          bind:value={newPath}
          onfocus={() => (showSuggestions = true)}
          onblur={() => setTimeout(() => (showSuggestions = false), 200)}
          aria-label="자료실 경로"
          placeholder="회사A/양식/안전"
          class="flex-1 px-2 py-1 bg-bg border border-default rounded text-xs text-text outline-none focus:border-accent"
        />
        <button
          type="submit"
          class="px-2 py-1 text-xs bg-accent text-white rounded hover:bg-accent-hover"
        >
          추가
        </button>
      </form>

      <!-- 자동완성 드롭다운 -->
      {#if showSuggestions && suggestions.length > 0}
        <div
          class="absolute top-full left-0 right-0 mt-1 bg-surface border border-default rounded shadow-lg z-dropdown"
        >
          {#each suggestions as suggestion}
            <button
              type="button"
              onmousedown={() => selectSuggestion(suggestion)}
              class="w-full text-left px-2 py-1.5 text-xs text-dim hover:bg-surface-hover hover:text-text"
            >
              {suggestion}
            </button>
          {/each}
        </div>
      {/if}

      <!-- 정규화 미리보기 -->
      {#if newPath.trim() && normalizedPreview() && normalizedPreview() !== newPath.trim()}
        <p class="text-[10px] text-dim mt-0.5">→ {normalizedPreview()}</p>
      {/if}
    </div>
  {:else}
    <div class="flex items-center gap-2">
      <button
        type="button"
        onclick={() => (showCategoryPicker = !showCategoryPicker)}
        class="flex items-center gap-1 text-xs text-dim hover:text-accent"
      >
        <Plus size={12} /> 분류 선택
      </button>
      <button
        type="button"
        onclick={() => (editing = true)}
        class="text-[10px] text-faint hover:text-dim"
      >
        직접 입력
      </button>
    </div>
  {/if}

  <!-- 카테고리 선택기 -->
  {#if showCategoryPicker}
    <div class="mt-1.5 border border-default rounded bg-surface max-h-48 overflow-y-auto">
      <input
        bind:value={categoryFilter}
        placeholder="분류 검색..."
        class="w-full px-2 py-1.5 bg-bg border-b border-default text-xs text-text outline-none focus:border-accent sticky top-0"
      />
      {#if filteredCategories.length === 0}
        <p class="px-2 py-2 text-[10px] text-faint">일치하는 분류 없음</p>
      {:else}
        {#each filteredCategories as path}
          <button
            type="button"
            onclick={() => { addPath(path); showCategoryPicker = false; categoryFilter = ''; }}
            class="w-full text-left px-2 py-1.5 text-xs text-dim hover:bg-surface-hover hover:text-text"
          >
            {path}
          </button>
        {/each}
      {/if}
    </div>
  {/if}
</div>
