<script lang="ts">
  /**
   * AssetList — 학습 세션에 연결된 documents (assets) 목록.
   *
   * Phase 1 표시:
   *   - handwriting_png: PNG snapshot 이력
   *   - audio: 재생 버튼 (브라우저 native <audio> 활용)
   *   - video: thumbnail 또는 재생 링크
   *   - source_scan / transcript / reference: 텍스트 링크
   *
   * "기존 문서 연결" 버튼은 Phase 1 에선 document_id 직접 입력 prompt() 로 단순화.
   * Phase 2 에서 search 모달로 교체.
   */
  import { Trash2, Headphones, Image as ImageIcon, Film, FileText, Plus } from 'lucide-svelte';
  import IconButton from '$lib/components/ui/IconButton.svelte';

  export interface AssetItem {
    id: number;
    document_id: number;
    asset_type: 'source_scan' | 'handwriting_png' | 'audio' | 'video' | 'transcript' | 'reference';
    role: string | null;
    sort_order: number;
    created_at: string;
  }

  interface Props {
    assets: AssetItem[];
    onLink?: (input: { document_id: number; asset_type: string; role: string | null }) => void;
    onUnlink?: (assetId: number) => void;
  }
  let { assets, onLink, onUnlink }: Props = $props();

  function iconFor(type: AssetItem['asset_type']) {
    switch (type) {
      case 'audio': return Headphones;
      case 'video': return Film;
      case 'handwriting_png':
      case 'source_scan': return ImageIcon;
      default: return FileText;
    }
  }

  function labelFor(type: AssetItem['asset_type']) {
    switch (type) {
      case 'audio': return '오디오';
      case 'video': return '영상';
      case 'handwriting_png': return '필기';
      case 'source_scan': return '스캔';
      case 'transcript': return '자막';
      case 'reference': return '참고';
    }
  }

  function promptLink() {
    const idStr = prompt('연결할 document_id 입력:');
    if (!idStr) return;
    const id = parseInt(idStr, 10);
    if (Number.isNaN(id)) return;
    const type = prompt('asset_type (source_scan / handwriting_png / audio / video / transcript / reference):', 'audio');
    if (!type) return;
    const role = prompt('role (선택, 비워도 됨 — pronunciation/lecture/listening_source 등):', '') || null;
    onLink?.({ document_id: id, asset_type: type, role });
  }
</script>

<div class="flex flex-col gap-1 p-3">
  <div class="flex items-center justify-between mb-1">
    <span class="text-xs text-dim">연결된 자료 ({assets.length})</span>
    <button
      type="button"
      onclick={promptLink}
      class="flex items-center gap-1 px-2 py-1 rounded text-xs text-accent hover:bg-accent/10"
    >
      <Plus size={12} /> 문서 연결
    </button>
  </div>
  {#if assets.length === 0}
    <div class="text-xs text-dim py-2">연결된 자료 없음. 오디오/영상/스캔 교재를 연결하세요.</div>
  {:else}
    {#each assets as a (a.id)}
      {@const Icon = iconFor(a.asset_type)}
      <div class="flex items-center gap-2 px-2 py-1.5 rounded border border-default bg-surface">
        <Icon size={14} class="text-dim shrink-0" />
        <span class="text-xs text-text shrink-0">{labelFor(a.asset_type)}</span>
        {#if a.role}
          <span class="text-[10px] text-dim shrink-0">· {a.role}</span>
        {/if}
        {#if a.asset_type === 'audio'}
          <audio controls preload="none" src={`/api/documents/${a.document_id}/file?disposition=inline`} class="flex-1 min-w-0 h-6">
            <track kind="captions" />
          </audio>
        {:else if a.asset_type === 'video'}
          <a
            href={`/video/${a.document_id}`}
            class="text-xs text-accent hover:underline flex-1 truncate"
          >video #{a.document_id} 보기</a>
        {:else}
          <a
            href={`/documents/${a.document_id}`}
            class="text-xs text-accent hover:underline flex-1 truncate"
          >document #{a.document_id}</a>
        {/if}
        <IconButton
          icon={Trash2}
          size="sm"
          aria-label="연결 해제"
          onclick={() => onUnlink?.(a.id)}
        />
      </div>
    {/each}
  {/if}
</div>
