<script>
  /**
   * /study/read/[docId] — 개념 학습 리더.
   * 개념노트(가스기사 documents)를 구조(요약/본문/빈출★/관련개념)로 렌더 +
   * '떠올리기' 능동 회상 토글 + 회독 SR(POST read) + 관련개념 백링크 + 이전/다음.
   * 본문 렌더 = MarkdownDoc(KaTeX + docimg 내장). 서버 파싱 = /api/study/concepts/{id}.
   */
  import { page } from '$app/stores';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { renderMathMarkdownInline } from '$lib/utils/mathMarkdown';
  import MarkdownDoc from '$lib/components/MarkdownDoc.svelte';
  import Button from '$lib/components/ui/Button.svelte';
  import EmptyState from '$lib/components/ui/EmptyState.svelte';
  import Skeleton from '$lib/components/ui/Skeleton.svelte';
  import { BookOpen, ArrowLeft, Eye, EyeOff, Check, ChevronLeft, ChevronRight, FileQuestion } from 'lucide-svelte';

  let docId = $derived($page.params.docId);

  let concept = $state(null);
  let relatedQ = $state(null);          // 관련 기출(이론↔문제, 비차단)
  let loading = $state(true);
  let notFound = $state(false);
  let mode = $state('read');            // 'read' | 'recall'(떠올리기)
  let revealed = $state({});            // {sectionIndex: true}
  let marking = $state(false);

  const STAGE_LABEL = { 0: '복습 시작', 1: '복습 1단계', 2: '복습 2단계', 3: '복습 3단계', 4: '학습 완료' };
  const OUTCOME_MARK = { correct: '○', wrong: '✕', unsure: '?' };
  const OUTCOME_CLASS = { correct: 'text-success', wrong: 'text-error', unsure: 'text-warning' };
  const outcomeMark = (o) => OUTCOME_MARK[o] ?? '–';
  const outcomeClass = (o) => OUTCOME_CLASS[o] ?? 'text-faint';

  async function load() {
    const reqId = docId; // in-flight 가드: 백링크 연타 시 stale 응답 무시
    loading = true;
    notFound = false;
    concept = null;
    relatedQ = null;
    revealed = {};
    mode = 'read';
    try {
      const data = await api(`/study/concepts/${reqId}`);
      if (reqId !== docId) return; // 그새 다른 개념으로 이동 → 폐기
      concept = data;
    } catch (e) {
      if (reqId !== docId) return;
      if (e?.status === 404) notFound = true;
      else addToast('error', '개념을 불러오지 못했습니다');
      return; // 본문 실패 → 관련기출 스킵
    } finally {
      if (reqId === docId) loading = false;
    }
    // 관련 기출(비차단 — 실패해도 본문 표시엔 영향 없음)
    try {
      const rq = await api(`/study/concepts/${reqId}/questions?limit=6`);
      if (reqId === docId) relatedQ = rq;
    } catch {}
  }

  // $effect 가 마운트 1회 + docId 변경(백링크/이전·다음) 재로드를 모두 커버 (onMount 불필요)
  $effect(() => {
    void docId;
    load();
  });

  function toggleMode() {
    mode = mode === 'read' ? 'recall' : 'read';
    revealed = {};
  }
  function reveal(i) {
    revealed = { ...revealed, [i]: true };
  }
  function shown(i) {
    return mode === 'read' || revealed[i];
  }

  async function markRead() {
    marking = true;
    try {
      const r = await api(`/study/concepts/${docId}/read`, { method: 'POST' });
      if (concept) {
        concept.is_read = true;
        concept.review_stage = r?.review_stage ?? concept.review_stage;
        concept.due_at = r?.due_at ?? concept.due_at;
      }
      addToast('success', '회독 완료 — 다음 복습에 다시 나옵니다');
    } catch {
      addToast('error', '회독 처리 실패');
    } finally {
      marking = false;
    }
  }
</script>

<svelte:head><title>{concept?.title ?? '개념'} — 공부</title></svelte:head>

<div class="p-4 md:p-6 max-w-3xl mx-auto">
  <!-- 상단 네비 -->
  <div class="flex items-center gap-2 text-xs md:text-sm mb-4 min-w-0">
    <a href="/study" class="text-dim hover:text-text flex items-center gap-1 shrink-0">
      <ArrowLeft size={14} /> 공부
    </a>
    {#if concept?.subject}
      <span class="text-faint shrink-0">/</span>
      <span class="text-dim truncate">{concept.subject}</span>
    {/if}
  </div>

  {#if loading}
    <Skeleton h="h-10" rounded="card" />
    <div class="mt-3 space-y-2">
      {#each Array(4) as _}<Skeleton h="h-24" rounded="card" />{/each}
    </div>
  {:else if notFound}
    <EmptyState icon={BookOpen} title="개념을 찾을 수 없습니다" description="삭제되었거나 잘못된 주소입니다." />
  {:else if concept}
    <!-- 제목 + 빈출 tier -->
    <header class="mb-3">
      <div class="flex items-start gap-2">
        <h1 class="text-xl md:text-2xl font-semibold text-text flex-1">{concept.title}</h1>
        <span class="text-accent text-sm shrink-0 mt-1" title="빈출도">
          {#each Array(concept.freq) as _}★{/each}
        </span>
      </div>
      {#if concept.is_read || (concept.review_stage !== null && concept.review_stage !== undefined)}
        <div class="mt-1 text-xs text-dim">
          {#if concept.review_stage !== null && concept.review_stage !== undefined}
            {STAGE_LABEL[concept.review_stage] ?? '복습 중'}
          {:else}회독함{/if}
        </div>
      {/if}
    </header>

    <!-- 한 줄 요약 (고정 표시) -->
    {#if concept.summary}
      <div class="mb-4 rounded-lg border-l-4 border-accent bg-accent/10 px-4 py-3 markdown-body text-sm text-text">
        {@html renderMathMarkdownInline(concept.summary)}
      </div>
    {/if}

    <!-- 모드 토글 -->
    <div class="flex items-center gap-2 mb-4">
      <Button variant={mode === 'recall' ? 'primary' : 'secondary'} size="sm" icon={mode === 'recall' ? EyeOff : Eye} onclick={toggleMode}>
        {mode === 'recall' ? '떠올리기 모드' : '읽기 모드'}
      </Button>
      {#if mode === 'recall'}
        <span class="text-xs text-dim">각 섹션을 떠올린 뒤 확인하세요</span>
      {/if}
    </div>

    <!-- 본문 섹션 -->
    {#if concept.body.length > 0}
      <div class="space-y-3 mb-5">
        {#each concept.body as sec, i (i)}
          <section class="rounded-lg border border-default bg-surface overflow-hidden">
            <div class="flex items-center gap-2 px-4 py-2.5 border-b border-default bg-surface-hover">
              <h2 class="text-sm font-semibold text-text flex-1">{sec.label}</h2>
              {#if sec.stars > 0}
                <span class="text-accent text-xs shrink-0">{#each Array(sec.stars) as _}★{/each}</span>
              {/if}
            </div>
            {#if shown(i)}
              <div class="px-4 py-3">
                <MarkdownDoc documentId={concept.doc_id} mdContent={sec.md} mdStatus={null}
                  class="markdown-body max-w-none text-text" />
              </div>
            {:else}
              <button type="button" onclick={() => reveal(i)}
                class="w-full px-4 py-6 text-center text-sm text-dim hover:text-accent hover:bg-accent/5 transition-colors">
                <Eye size={16} class="inline mr-1" /> 떠올린 뒤 확인
              </button>
            {/if}
          </section>
        {/each}
      </div>
    {/if}

    <!-- 빈출 포인트 -->
    {#if concept.bincheol.length > 0}
      <section class="mb-5 rounded-lg border border-default bg-surface p-4">
        <h2 class="text-sm font-semibold text-text mb-2 flex items-center gap-1.5">
          <span class="text-accent">★</span> 빈출 포인트
        </h2>
        <ul class="space-y-1.5">
          {#each concept.bincheol as item}
            <li class="flex gap-2 text-sm text-text">
              <span class="text-accent shrink-0 text-xs mt-0.5">{#each Array(item.tier || 1) as _}★{/each}</span>
              <span class="markdown-body flex-1">{@html renderMathMarkdownInline(item.text)}</span>
            </li>
          {/each}
        </ul>
      </section>
    {/if}

    <!-- 관련 개념 (백링크) -->
    {#if concept.related.length > 0}
      <section class="mb-5">
        <h2 class="text-xs text-dim mb-2">관련 개념</h2>
        <div class="flex flex-wrap gap-2">
          {#each concept.related as rel}
            {#if rel.doc_id}
              <a href="/study/read/{rel.doc_id}"
                class="text-xs rounded-full border border-accent/40 bg-accent/10 text-accent px-3 py-1 hover:bg-accent/20 transition-colors">
                {rel.phrase}
              </a>
            {:else}
              <span class="text-xs rounded-full border border-default bg-surface text-faint px-3 py-1" title="아직 없는 개념">
                {rel.phrase}
              </span>
            {/if}
          {/each}
        </div>
      </section>
    {/if}

    <!-- 관련 기출 (이론↔문제 브리지) -->
    {#if relatedQ && relatedQ.linked > 0}
      <section class="mb-5 rounded-lg border border-default bg-surface p-4">
        <h2 class="text-sm font-semibold text-text mb-2 flex items-center gap-1.5">
          <FileQuestion size={15} class="text-accent" /> 관련 기출
          <span class="ml-1 text-xs font-normal text-dim">
            {relatedQ.linked}문항{#if relatedQ.accuracy !== null} · 정답률 <span class="{relatedQ.accuracy < 60 ? 'text-error' : 'text-text'} font-medium">{relatedQ.accuracy}%</span>{:else} · 아직 안 풂{/if}
          </span>
        </h2>
        <ul class="space-y-0.5">
          {#each relatedQ.questions as q (q.id)}
            <li>
              <a href="/study/topics/4/questions/{q.id}"
                class="flex items-center gap-2 text-xs py-1 text-dim hover:text-accent transition-colors">
                <span class="{outcomeClass(q.last_outcome)} shrink-0 w-4 text-center font-bold">{outcomeMark(q.last_outcome)}</span>
                <span class="truncate">{q.subject ?? '기출'}{#if q.exam_round} · {q.exam_round}{/if}</span>
              </a>
            </li>
          {/each}
        </ul>
      </section>
    {/if}

    <!-- 액션바 -->
    <div class="flex items-center gap-2 border-t border-default pt-4 mt-2">
      {#if concept.prev_id}
        <Button variant="ghost" size="sm" icon={ChevronLeft} href="/study/read/{concept.prev_id}">이전</Button>
      {/if}
      <div class="flex-1"></div>
      <Button variant="primary" size="sm" icon={Check} onclick={markRead} loading={marking}>
        {concept.is_read ? '다시 회독' : '회독 완료'}
      </Button>
      {#if concept.next_id}
        <Button variant="secondary" size="sm" icon={ChevronRight} href="/study/read/{concept.next_id}">다음 개념</Button>
      {/if}
    </div>
  {/if}
</div>
