<script>
  // 안전 자료실 공용 목록 — material_type + jurisdiction 필터로 GET /documents/ 조회.
  // C-1 계약: material_type 지정 = 기본 exclude(news·law_monitor·note) 해제 (documents.py list_documents).
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import DocumentCard from '$lib/components/DocumentCard.svelte';

  let { materialType, jurisdiction = '' } = $props();

  const PAGE_SIZE = 20;
  let docs = $state([]);
  let total = $state(0);
  let nextPage = $state(1);
  let loading = $state(false);

  async function load(reset = false) {
    loading = true;
    const pageToLoad = reset ? 1 : nextPage;
    try {
      const params = new URLSearchParams();
      params.set('material_type', materialType);
      if (jurisdiction) params.set('jurisdiction', jurisdiction);
      params.set('page', String(pageToLoad));
      params.set('page_size', String(PAGE_SIZE));
      const result = await api(`/documents/?${params}`);
      docs = reset ? result.items : [...docs, ...result.items];
      total = result.total;
      nextPage = pageToLoad + 1;
    } catch {
      addToast('error', '안전 자료 로딩 실패');
    } finally {
      loading = false;
    }
  }

  $effect(() => {
    // 필터 변경 시 1페이지부터 재조회 (materialType/jurisdiction 읽기 = 반응 트리거)
    void materialType;
    void jurisdiction;
    docs = [];
    load(true);
  });

  let hasMore = $derived(docs.length < total);
</script>

<div class="flex flex-col gap-2">
  {#if !loading || docs.length > 0}
    <p class="text-xs text-dim tabular-nums">총 {total.toLocaleString()}건</p>
  {/if}

  {#if docs.length > 0}
    <div class="flex flex-col gap-2">
      {#each docs as doc (doc.id)}
        <DocumentCard {doc} />
      {/each}
    </div>
  {:else if !loading}
    <div class="py-12 text-center text-sm text-dim">
      해당 조건의 자료가 없습니다.
    </div>
  {/if}

  {#if loading}
    <div class="py-6 text-center text-sm text-dim">불러오는 중…</div>
  {:else if hasMore}
    <button
      type="button"
      onclick={() => load(false)}
      class="self-center px-4 py-1.5 rounded-md text-sm text-dim border border-default hover:bg-surface hover:text-text transition-colors"
    >
      더 보기 ({docs.length}/{total.toLocaleString()})
    </button>
  {/if}
</div>
