<script>
  /**
   * /study/topics/[id]/exam-rounds — 회차 목록 + 진행률 (PR-6).
   *
   * 토픽의 exam_round_size 가 있으면 진행 바 + "N번부터 이어서" 동선.
   * 새 회차 시작 모달 → /questions/new?exam_round=...&start_qnum=1 로 이동.
   */
  import { onMount } from 'svelte';
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { ArrowLeft, Plus, ArrowRight, CheckCircle2, ListChecks } from 'lucide-svelte';
  import Button from '$lib/components/ui/Button.svelte';
  import Card from '$lib/components/ui/Card.svelte';
  import EmptyState from '$lib/components/ui/EmptyState.svelte';
  import Skeleton from '$lib/components/ui/Skeleton.svelte';

  let topicId = $derived(Number($page.params.id));
  let topicName = $state('');
  let examRoundSize = $state(null);
  let items = $state([]);
  let loading = $state(true);

  // 새 회차 시작 모달
  let newRoundModal = $state(false);
  let newRoundName = $state('');

  async function load() {
    loading = true;
    try {
      const [t, r] = await Promise.all([
        api(`/study-topics/${topicId}`),
        api(`/study-topics/${topicId}/exam-rounds`),
      ]);
      topicName = t?.topic?.name ?? '';
      examRoundSize = r.exam_round_size;
      items = r.items;
    } catch (err) {
      addToast('error', err.detail || '회차 목록 로딩 실패');
    } finally {
      loading = false;
    }
  }

  onMount(load);

  function startNewRound() {
    if (!newRoundName.trim()) {
      addToast('error', '회차명을 입력하세요');
      return;
    }
    const r = newRoundName.trim();
    newRoundModal = false;
    newRoundName = '';
    const q = new URLSearchParams({ exam_round: r, start_qnum: '1' });
    goto(`/study/topics/${topicId}/questions/new?${q}`);
  }

  function resumeRound(it) {
    const q = new URLSearchParams({
      exam_round: it.exam_round,
      start_qnum: String(it.next_question_number ?? it.max_question_number + 1),
    });
    goto(`/study/topics/${topicId}/questions/new?${q}`);
  }

  function progressPercent(it) {
    if (!examRoundSize) return 0;
    return Math.min(100, Math.round((it.question_count / examRoundSize) * 100));
  }
</script>

<svelte:head><title>회차 — {topicName || '주제'}</title></svelte:head>

<div class="p-4 md:p-6 max-w-4xl mx-auto">
  <div class="flex items-center gap-2 text-xs md:text-sm mb-3">
    <a href="/study" class="text-dim hover:text-text">공부</a>
    <span class="text-faint">/</span>
    <a href="/study/topics" class="text-dim hover:text-text">주제</a>
    <span class="text-faint">/</span>
    <a href={`/study/topics/${topicId}`} class="text-dim hover:text-text truncate">{topicName || '...'}</a>
    <span class="text-faint">/</span>
    <span class="text-text font-medium flex items-center gap-1.5"><ListChecks size={14} class="text-accent" /> 회차</span>
  </div>

  <header class="flex items-center justify-between mb-4 flex-wrap gap-2">
    <div>
      <h1 class="text-lg font-semibold text-text">{topicName} — 회차</h1>
      <p class="text-xs text-dim mt-1">
        {#if examRoundSize}회차당 <span class="text-text">{examRoundSize}</span>문항 기준{:else}회차당 문항 수 미설정 (주제 편집에서 설정){/if}
      </p>
    </div>
    <Button onclick={() => (newRoundModal = true)} icon={Plus}>새 회차 시작</Button>
  </header>

  {#if loading}
    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
      {#each Array(3) as _}<Skeleton h="h-24" rounded="lg" />{/each}
    </div>
  {:else if items.length === 0}
    <EmptyState
      icon={ListChecks}
      title="회차가 없습니다"
      description="첫 회차(예: '2019년 1회')를 시작하면 여기에 진행률이 누적됩니다."
    />
  {:else}
    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
      {#each items as it (it.exam_round)}
        <div class="p-4 rounded-lg border border-default bg-surface flex flex-col gap-2">
          <div class="flex items-center gap-2">
            <span class="text-sm font-semibold text-text truncate">{it.exam_round}</span>
            {#if it.is_complete}
              <span class="text-[10px] text-success border border-success/40 rounded px-1.5 py-0.5 flex items-center gap-1">
                <CheckCircle2 size={10} /> 완료
              </span>
            {/if}
            <span class="ml-auto text-xs text-dim">
              <span class="text-text">{it.question_count}</span>{#if examRoundSize}<span class="text-faint">/{examRoundSize}</span>{/if}
            </span>
          </div>

          {#if examRoundSize}
            <div class="h-1.5 bg-bg rounded-full overflow-hidden">
              <div class="h-full bg-accent transition-all" style="width: {progressPercent(it)}%"></div>
            </div>
          {/if}

          <div class="flex items-center justify-between mt-1">
            <span class="text-[11px] text-dim">
              {#if it.is_complete}모든 문항 입력 완료{:else}다음: <span class="text-text">{it.next_question_number}번</span>{/if}
            </span>
            {#if !it.is_complete}
              <Button size="sm" onclick={() => resumeRound(it)} icon={ArrowRight} iconPosition="right">
                {it.next_question_number}번부터 이어서
              </Button>
            {/if}
          </div>
        </div>
      {/each}
    </div>
  {/if}
</div>

<!-- 새 회차 모달 -->
{#if newRoundModal}
  <button type="button" aria-label="모달 닫기" onclick={() => (newRoundModal = false)}
    class="fixed inset-0 z-40 bg-black/40"></button>
  <div class="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none">
    <div class="w-full max-w-sm bg-surface rounded-lg border border-default shadow-xl p-4 pointer-events-auto">
      <div class="text-sm font-semibold text-text mb-3">새 회차 시작</div>
      <label class="flex flex-col gap-1.5">
        <span class="text-xs text-dim">회차명</span>
        <input type="text" bind:value={newRoundName}
          placeholder="예: 2019년 1회"
          onkeydown={(e) => { if (e.key === 'Enter') startNewRound(); }}
          class="px-3 py-2 bg-surface border border-default rounded text-sm text-text outline-none focus:border-accent" />
      </label>
      <p class="text-[11px] text-dim mt-2">
        같은 토픽 안에서 회차명은 자유 텍스트입니다. "2019년 1회" 같은 형태로 입력하면 진행률 추적이 가능합니다.
      </p>
      <div class="flex gap-2 justify-end mt-4">
        <Button variant="ghost" onclick={() => (newRoundModal = false)}>취소</Button>
        <Button onclick={startNewRound}>시작</Button>
      </div>
    </div>
  </div>
{/if}
