<script>
  // Phase E.1 — 편집 URL(외부 Synology Drive 등) 등록.
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import Button from '$lib/components/ui/Button.svelte';

  let { doc } = $props();

  let urlText = $state('');
  let editing = $state(false);
  let saving = $state(false);

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

  async function save() {
    saving = true;
    try {
      const next = urlText.trim() || null;
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ edit_url: next }),
      });
      doc.edit_url = next;
      editing = false;
      addToast('success', '편집 URL 저장됨');
    } catch (err) {
      addToast('error', '편집 URL 저장 실패');
    } finally {
      saving = false;
    }
  }

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

<div>
  <h4 class="text-xs font-semibold text-dim uppercase mb-1.5">편집 링크</h4>
  {#if editing}
    <div class="flex gap-1">
      <input
        bind:value={urlText}
        aria-label="편집 URL"
        placeholder="Synology Drive URL..."
        class="flex-1 px-2 py-1 bg-bg border border-default rounded text-xs text-text outline-none focus:border-accent"
      />
      <Button variant="primary" size="sm" loading={saving} onclick={save}>저장</Button>
      <Button variant="ghost" size="sm" onclick={cancel}>취소</Button>
    </div>
  {:else if doc.edit_url}
    <div class="flex items-center gap-2">
      <a
        href={doc.edit_url}
        target="_blank"
        rel="noopener"
        class="text-xs text-accent truncate hover:underline flex-1 min-w-0"
      >
        {doc.edit_url}
      </a>
      <button
        type="button"
        onclick={() => (editing = true)}
        class="text-[10px] text-dim hover:text-text shrink-0"
      >
        수정
      </button>
    </div>
  {:else}
    <button
      type="button"
      onclick={() => (editing = true)}
      class="text-xs text-dim hover:text-accent"
    >
      + URL 추가
    </button>
  {/if}
</div>
