<script>
  // 오디오 플레이어 + 전사 세그먼트 sticky 패널.
  // 줄 클릭 시 audio.currentTime = seg.start 로 점프.
  // 재생 중인 세그먼트는 하이라이트.

  import { api, getAccessToken } from '$lib/api';

  let { docId } = $props();

  let audioEl = $state(null);
  let segments = $state([]);
  let currentTime = $state(0);
  let loading = $state(true);
  let error = $state(null);

  let token = $derived(getAccessToken());
  let fileSrc = $derived(`/api/documents/${docId}/file?token=${token}`);

  $effect(() => {
    if (docId != null) loadSegments(docId);
  });

  async function loadSegments(id) {
    loading = true;
    error = null;
    try {
      const resp = await api(`/audio/${id}/segments`);
      segments = resp?.segments ?? [];
    } catch (err) {
      segments = [];
      error = '전사 세그먼트를 불러오지 못했습니다';
    } finally {
      loading = false;
    }
  }

  function seekTo(start) {
    if (!audioEl) return;
    audioEl.currentTime = Math.max(0, start);
    audioEl.play().catch(() => {});
  }

  function handleTimeUpdate() {
    if (audioEl) currentTime = audioEl.currentTime;
  }

  function formatTime(sec) {
    if (sec == null || isNaN(sec)) return '00:00';
    const m = Math.floor(sec / 60);
    const s = Math.floor(sec % 60);
    return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
  }

  let activeIdx = $derived(
    segments.findIndex((s) => currentTime >= s.start && currentTime < s.end)
  );
</script>

<div class="flex flex-col h-full">
  <div class="sticky top-0 z-10 bg-surface border-b border-default p-3">
    <audio
      bind:this={audioEl}
      src={fileSrc}
      controls
      preload="metadata"
      class="w-full"
      ontimeupdate={handleTimeUpdate}
    >
      <track kind="captions" />
    </audio>
  </div>

  <div class="flex-1 overflow-y-auto p-4 space-y-1">
    {#if loading}
      <p class="text-muted text-sm">전사 불러오는 중…</p>
    {:else if error}
      <p class="text-error text-sm">{error}</p>
    {:else if segments.length === 0}
      <p class="text-muted text-sm">전사 결과가 아직 없습니다 (STT 처리 대기 중일 수 있음).</p>
    {:else}
      {#each segments as seg, i (seg.start)}
        <button
          type="button"
          class="w-full text-left flex gap-3 px-2 py-1 rounded transition-colors {i === activeIdx ? 'bg-accent-muted' : 'hover:bg-surface-hover'}"
          onclick={() => seekTo(seg.start)}
        >
          <span class="text-xs tabular-nums text-muted min-w-[3.5rem] mt-0.5">
            {formatTime(seg.start)}
          </span>
          <span class="text-sm leading-relaxed">{seg.text}</span>
        </button>
      {/each}
    {/if}
  </div>
</div>
