<script>
  import { goto } from '$app/navigation';
  import { page } from '$app/stores';

  let { tag = '', clickable = true } = $props();

  // 계층별 색상 (의미 토큰)
  function getColor(t) {
    if (t.startsWith('@상태/') || t.startsWith('@')) return { bg: 'bg-warning/30', text: 'text-warning' };
    if (t.startsWith('#주제/') || t.startsWith('#')) return { bg: 'bg-accent/30', text: 'text-accent' };
    if (t.startsWith('$유형/') || t.startsWith('$')) return { bg: 'bg-success/30', text: 'text-success' };
    if (t.startsWith('!우선순위/') || t.startsWith('!')) return { bg: 'bg-error/30', text: 'text-error' };
    return { bg: 'bg-default', text: 'text-dim' };
  }

  function handleClick(e) {
    if (!clickable) return;
    e.preventDefault();
    e.stopPropagation();
    const params = new URLSearchParams($page.url.searchParams);
    params.set('tag', tag);
    params.delete('page');
    goto(`/documents?${params}`, { noScroll: true });
  }

  let color = $derived(getColor(tag));
</script>

{#if clickable}
  <button
    onclick={handleClick}
    class="inline-flex text-[10px] px-1.5 py-0.5 rounded {color.bg} {color.text} hover:opacity-80 transition-opacity"
  >
    {tag}
  </button>
{:else}
  <span class="inline-flex text-[10px] px-1.5 py-0.5 rounded {color.bg} {color.text}">
    {tag}
  </span>
{/if}
