<script>
  // 파일 메타 정보 + facet 편집
  import { onMount } from 'svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';

  let { doc } = $props();

  // facet 옵션 (세션 내 1회 로드)
  let facetOptions = $state({ company: [], topic: [], doctype: [], year: [] });

  function formatDate(dateStr) {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  }

  function formatSize(bytes) {
    if (!bytes) return '-';
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)}KB`;
    return `${(bytes / 1048576).toFixed(1)}MB`;
  }

  onMount(async () => {
    try {
      facetOptions = await api('/library/facets');
    } catch { /* 옵션 로딩 실패해도 수동 입력 가능 */ }
  });

  async function updatePurpose(e) {
    const val = e.target.value || null;
    const prev = doc.doc_purpose;
    doc.doc_purpose = val;
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ doc_purpose: val }),
      });
      addToast('success', '용도 변경됨');
    } catch {
      doc.doc_purpose = prev;
      addToast('error', '용도 변경 실패');
    }
  }

  async function updateFacet(field, value) {
    const prev = doc[field];
    doc[field] = value;
    try {
      await api(`/documents/${doc.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ [field]: value }),
      });
      addToast('success', '변경됨');
    } catch {
      doc[field] = prev;
      addToast('error', '변경 실패');
    }
  }
</script>

<div>
  <h4 class="text-xs font-semibold text-dim uppercase mb-1.5">정보</h4>
  <dl class="space-y-1.5 text-xs">
    <div class="flex justify-between">
      <dt class="text-dim">포맷</dt>
      <dd class="text-text uppercase">
        {doc.file_format}{doc.original_format ? ` (원본: ${doc.original_format})` : ''}
      </dd>
    </div>
    <div class="flex justify-between">
      <dt class="text-dim">크기</dt>
      <dd class="text-text">{formatSize(doc.file_size)}</dd>
    </div>
    {#if doc.source_channel}
      <div class="flex justify-between">
        <dt class="text-dim">출처</dt>
        <dd class="text-text">{doc.source_channel}</dd>
      </div>
    {/if}
    {#if doc.data_origin}
      <div class="flex justify-between">
        <dt class="text-dim">구분</dt>
        <dd class="text-text">{doc.data_origin}</dd>
      </div>
    {/if}
    <div class="flex justify-between items-center">
      <dt class="text-dim">용도</dt>
      <dd>
        <select
          value={doc.doc_purpose || ''}
          onchange={updatePurpose}
          class="bg-bg border border-default rounded px-1 py-0.5 text-xs text-text outline-none focus:border-accent"
        >
          <option value="">미분류</option>
          <option value="business">업무용</option>
          <option value="knowledge">참조용</option>
        </select>
      </dd>
    </div>
    <div class="flex justify-between">
      <dt class="text-dim">등록일</dt>
      <dd class="text-text">{formatDate(doc.created_at)}</dd>
    </div>
  </dl>

  <!-- Facet 메타데이터 -->
  <h4 class="text-xs font-semibold text-dim uppercase mt-3 mb-1.5">탐색 축</h4>
  <dl class="space-y-1.5 text-xs">
    <div class="flex justify-between items-center">
      <dt class="text-dim">회사</dt>
      <dd>
        <select
          value={doc.facet_company || ''}
          onchange={(e) => updateFacet('facet_company', e.target.value || null)}
          class="bg-bg border border-default rounded px-1 py-0.5 text-xs text-text outline-none focus:border-accent"
        >
          <option value="">-</option>
          {#each facetOptions.company || [] as v}
            <option value={v}>{v}</option>
          {/each}
        </select>
      </dd>
    </div>
    <div class="flex justify-between items-center">
      <dt class="text-dim">주제</dt>
      <dd>
        <select
          value={doc.facet_topic || ''}
          onchange={(e) => updateFacet('facet_topic', e.target.value || null)}
          class="bg-bg border border-default rounded px-1 py-0.5 text-xs text-text outline-none focus:border-accent"
        >
          <option value="">-</option>
          {#each facetOptions.topic || [] as v}
            <option value={v}>{v}</option>
          {/each}
        </select>
      </dd>
    </div>
    <div class="flex justify-between items-center">
      <dt class="text-dim">연도</dt>
      <dd>
        <select
          value={doc.facet_year ?? ''}
          onchange={(e) => updateFacet('facet_year', e.target.value ? Number(e.target.value) : null)}
          class="bg-bg border border-default rounded px-1 py-0.5 text-xs text-text outline-none focus:border-accent"
        >
          <option value="">-</option>
          {#each facetOptions.year || [] as v}
            <option value={v}>{v}</option>
          {/each}
        </select>
      </dd>
    </div>
    <div class="flex justify-between items-center">
      <dt class="text-dim">문서유형</dt>
      <dd>
        <select
          value={doc.facet_doctype || ''}
          onchange={(e) => updateFacet('facet_doctype', e.target.value || null)}
          class="bg-bg border border-default rounded px-1 py-0.5 text-xs text-text outline-none focus:border-accent"
        >
          <option value="">-</option>
          {#each facetOptions.doctype || [] as v}
            <option value={v}>{v}</option>
          {/each}
        </select>
      </dd>
    </div>
  </dl>
</div>
