<script>
  // /video — 비디오 문서 목록. §3
  // needs_conversion=true 는 재생 불가 배지 표시, 썸네일은 /api/video/{id}/thumbnail?token=.

  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { api, getAccessToken } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { Film, AlertTriangle } 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: 'video',
        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;
    }
  }

  let token = $derived(getAccessToken());

  function thumbSrc(id) {
    return `/api/video/${id}/thumbnail?token=${token}`;
  }

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

<div class="p-6 max-w-[1680px] mx-auto">
  <header class="flex items-center gap-2 mb-4">
    <Film size={20} />
    <h1 class="text-xl font-semibold">Video</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/Videos/</code> 에 드롭하거나 업로드하세요.</p>
  {:else}
    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
      {#each docs as d (d.id)}
        <button
          type="button"
          class="text-left rounded-lg overflow-hidden border border-default bg-surface hover:bg-surface-hover transition-colors"
          onclick={() => goto(`/video/${d.id}`)}
        >
          <div class="aspect-video bg-black relative flex items-center justify-center">
            {#if d.thumbnail_path}
              <img src={thumbSrc(d.id)} alt="" class="w-full h-full object-cover" loading="lazy" />
            {:else}
              <Film size={32} class="text-dim" />
            {/if}
            {#if d.needs_conversion}
              <span class="absolute top-1 left-1 px-1.5 py-0.5 rounded bg-warning text-xs flex items-center gap-1">
                <AlertTriangle size={12} /> 변환 필요
              </span>
            {/if}
          </div>
          <div class="p-2">
            <p class="text-sm font-medium truncate">{d.title || '(제목 없음)'}</p>
            <p class="text-xs text-muted mt-0.5">.{d.file_format} · {fmtSize(d.file_size)}</p>
          </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>
