<script>
  // /audio — 오디오 문서 목록. §3
  // `GET /api/documents?category=audio` 로 조회 후 카드 그리드로 렌더.

  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { Mic, FileAudio } from 'lucide-svelte';

  let docs = $state([]);
  let total = $state(0);
  let loading = $state(true);
  let currentPage = $state(1);
  const PAGE_SIZE = 30;

  onMount(load);

  async function load() {
    loading = true;
    try {
      const params = new URLSearchParams({
        category: 'audio',
        page: String(currentPage),
        page_size: String(PAGE_SIZE),
        sort: 'updated_desc',
      });
      const data = await api(`/documents?${params}`);
      docs = data.items ?? [];
      total = data.total ?? 0;
    } catch (err) {
      addToast('error', '오디오 목록 불러오기 실패');
      docs = [];
    } finally {
      loading = false;
    }
  }

  function pickOpen(id) {
    goto(`/audio/${id}`);
  }

  function fmtSize(bytes) {
    if (!bytes) return '-';
    const mb = bytes / (1024 * 1024);
    return mb < 1 ? `${(bytes / 1024).toFixed(0)} KB` : `${mb.toFixed(1)} MB`;
  }

  function fmtDate(s) {
    if (!s) return '';
    const d = new Date(s);
    return d.toLocaleDateString();
  }
</script>

<div class="p-6 max-w-[1680px] mx-auto">
  <header class="flex items-center gap-2 mb-4">
    <Mic size={20} />
    <h1 class="text-xl font-semibold">Audio</h1>
    <span class="text-sm text-muted ml-2">{total}건</span>
  </header>

  {#if loading}
    <p class="text-muted">불러오는 중…</p>
  {:else if docs.length === 0}
    <p class="text-muted">오디오 문서가 없습니다. NAS <code>PKM/Recordings/</code> 에 드롭하거나 업로드하세요.</p>
  {:else}
    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
      {#each docs as d (d.id)}
        <button
          type="button"
          class="text-left p-4 rounded-lg border border-default bg-surface hover:bg-surface-hover transition-colors"
          onclick={() => pickOpen(d.id)}
        >
          <div class="flex items-start gap-2">
            <FileAudio size={18} class="text-muted mt-0.5 shrink-0" />
            <div class="flex-1 min-w-0">
              <p class="font-medium truncate">{d.title || '(제목 없음)'}</p>
              <p class="text-xs text-muted mt-1">.{d.file_format} · {fmtSize(d.file_size)}</p>
              <p class="text-xs text-dim mt-0.5">{fmtDate(d.updated_at)}</p>
            </div>
          </div>
        </button>
      {/each}
    </div>

    {#if total > PAGE_SIZE}
      <div class="flex justify-center gap-2 mt-6">
        <button
          type="button"
          class="px-3 py-1 rounded border border-default disabled:opacity-50"
          disabled={currentPage === 1}
          onclick={() => { currentPage -= 1; load(); }}
        >이전</button>
        <span class="px-3 py-1 text-sm text-muted">{currentPage} / {Math.ceil(total / PAGE_SIZE)}</span>
        <button
          type="button"
          class="px-3 py-1 rounded border border-default disabled:opacity-50"
          disabled={currentPage * PAGE_SIZE >= total}
          onclick={() => { currentPage += 1; load(); }}
        >다음</button>
      </div>
    {/if}
  {/if}
</div>
