<script>
  // Phase E.1 — PreviewPanel 분할. 사용자 메모 편집.
  import { Save } from 'lucide-svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import Button from '$lib/components/ui/Button.svelte';

  let { doc } = $props();

  // 초기값은 빈 문자열, 아래 $effect가 doc 변경 시 동기화.
  let noteText = $state('');
  let editing = $state(false);
  let saving = $state(false);

  $effect(() => {
    if (doc) {
      noteText = doc.user_note || '';
      editing = false;
    }
  });

  async function save() {
    saving = true;
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ user_note: noteText }),
      });
      doc.user_note = noteText;
      editing = false;
      addToast('success', '메모 저장됨');
    } catch (err) {
      addToast('error', '메모 저장 실패');
    } finally {
      saving = false;
    }
  }

  function cancel() {
    editing = false;
    noteText = doc.user_note || '';
  }
</script>

<div>
  <h4 class="text-xs font-semibold text-dim uppercase mb-1.5">메모</h4>
  {#if editing}
    <textarea
      bind:value={noteText}
      aria-label="메모"
      class="w-full h-24 px-3 py-2 bg-bg border border-default rounded-md text-sm text-text resize-none outline-none focus:border-accent"
      placeholder="메모 입력..."
    ></textarea>
    <div class="flex gap-2 mt-1.5">
      <Button variant="primary" size="sm" icon={Save} loading={saving} onclick={save}>
        저장
      </Button>
      <Button variant="ghost" size="sm" onclick={cancel}>취소</Button>
    </div>
  {:else}
    <button
      type="button"
      onclick={() => (editing = true)}
      class="w-full text-left px-3 py-2 bg-bg border border-default rounded-md text-sm min-h-[40px] hover:border-accent transition-colors
        {noteText ? 'text-text' : 'text-dim'}"
    >
      {noteText || '메모 추가...'}
    </button>
  {/if}
</div>
