<script>
  // Phase E.1 — 태그 추가/삭제.
  // Phase F의 inbox override TagsEditor도 향후 이 컴포넌트로 통일 가능.
  import { Plus, X } from 'lucide-svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import TagPill from '$lib/components/TagPill.svelte';

  let { doc } = $props();

  let newTag = $state('');
  let editing = $state(false);

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

  async function addTag() {
    const tag = newTag.trim();
    if (!tag) return;
    const updated = [...(doc.ai_tags || []), tag];
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ ai_tags: updated }),
      });
      doc.ai_tags = updated;
      newTag = '';
      addToast('success', '태그 추가됨');
    } catch (err) {
      addToast('error', '태그 추가 실패');
    }
  }

  async function removeTag(tagToRemove) {
    const updated = (doc.ai_tags || []).filter((t) => t !== tagToRemove);
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ ai_tags: updated }),
      });
      doc.ai_tags = updated;
      addToast('success', '태그 삭제됨');
    } catch (err) {
      addToast('error', '태그 삭제 실패');
    }
  }
</script>

<div>
  <h4 class="text-xs font-semibold text-dim uppercase mb-1.5">태그</h4>
  <div class="flex flex-wrap gap-1 mb-2">
    {#each doc.ai_tags || [] as tag}
      <span class="inline-flex items-center gap-0.5">
        <TagPill {tag} clickable={false} />
        <button
          type="button"
          onclick={() => removeTag(tag)}
          class="text-dim hover:text-error"
          aria-label="{tag} 삭제"
          title="삭제"
        >
          <X size={10} />
        </button>
      </span>
    {/each}
  </div>
  {#if editing}
    <form
      onsubmit={(e) => {
        e.preventDefault();
        addTag();
      }}
      class="flex gap-1"
    >
      <input
        bind:value={newTag}
        aria-label="새 태그"
        placeholder="태그 입력..."
        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>
  {:else}
    <button
      type="button"
      onclick={() => (editing = true)}
      class="flex items-center gap-1 text-xs text-dim hover:text-accent"
    >
      <Plus size={12} /> 태그 추가
    </button>
  {/if}
</div>
