<script>
  // /study — 학습 hub + 데일리 랜딩('오늘의 공부' 대시보드).
  // 상단 = 이론 홈(진도·오늘의 개념·복습 due, 재노출 트리거). 하단 = 기존 모드 진입.
  import { onMount } from 'svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { BookOpen, PenLine, GraduationCap, FolderKanban, Layers, Repeat, Flag, Inbox, Activity, CalendarCheck, Target } from 'lucide-svelte';

  let cardReviewCount = $state(0);
  let questionFlagCount = $state(0);

  // 오늘의 공부 (이론 홈)
  let curriculum = $state(null);
  let todayConcepts = $state([]);
  let weakConcepts = $state([]);        // 약점 개념(관련 기출 정답률 낮음)
  let dashLoading = $state(true);

  let readPct = $derived(
    curriculum && curriculum.total ? Math.round((curriculum.read / curriculum.total) * 100) : 0
  );

  async function loadDashboard() {
    dashLoading = true;
    try {
      const [cur, today] = await Promise.all([
        api('/study/curriculum'),
        api('/study/today-concepts?limit=6'),
      ]);
      curriculum = cur;
      todayConcepts = today?.concepts ?? [];
    } catch {
      // 코어 대시보드 실패해도 허브 나머지는 동작 (조용히)
    } finally {
      dashLoading = false;
    }
    // 약점 개념 = 비차단(신규 엔드포인트 실패해도 코어 대시보드 블랙아웃 방지)
    try {
      const weak = await api('/study/concepts/weakness-map?limit=5');
      weakConcepts = weak?.weak ?? [];
    } catch {}
  }

  async function markRead(doc) {
    try {
      await api(`/study/concepts/${doc.doc_id}/read`, { method: 'POST' });
      todayConcepts = todayConcepts.filter((c) => c.doc_id !== doc.doc_id);
      addToast('success', `회독: ${doc.title}`);
      loadDashboard(); // 진도 갱신
    } catch {
      addToast('error', '회독 처리 실패');
    }
  }

  onMount(async () => {
    loadDashboard();
    try {
      const r = await api('/study-cards/needs-review/count');
      cardReviewCount = r?.count ?? 0;
    } catch {}
    try {
      const r2 = await api('/study-questions/needs-review/count');
      questionFlagCount = r2?.count ?? 0;
    } catch {}
  });
</script>

<div class="p-4 md:p-6 max-w-5xl mx-auto">
  <header class="mb-6">
    <h1 class="text-xl font-semibold text-text flex items-center gap-2">
      <GraduationCap size={22} /> 공부
    </h1>
    <p class="text-sm text-dim mt-1">주제별 퀴즈·복습(SRS)·통계 / 학습 자료 회독 / 손글씨 필사 세션.</p>
  </header>

  <!-- 오늘의 공부 (이론 홈 대시보드 = 데일리 트리거) -->
  <section class="mb-5 rounded-lg border border-default bg-surface p-4 md:p-5">
    <div class="flex items-center gap-2 mb-3">
      <CalendarCheck size={18} class="text-accent" />
      <h2 class="text-base font-semibold text-text">오늘의 공부</h2>
      {#if curriculum}
        <span class="ml-auto text-xs text-dim">이론 회독 <span class="text-text font-medium">{curriculum.read}</span> / {curriculum.total} ({readPct}%)</span>
      {/if}
    </div>

    {#if dashLoading}
      <p class="text-xs text-dim">불러오는 중…</p>
    {:else}
      {#if curriculum}
        <div class="h-2 rounded-full bg-bg overflow-hidden mb-3">
          <div class="h-full bg-accent" style="width: {readPct}%"></div>
        </div>
        <div class="flex flex-wrap gap-x-4 gap-y-1 mb-4 text-xs text-dim">
          {#each curriculum.subjects as s}
            <span>{s.subject} <span class="text-text">{s.read}/{s.total}</span></span>
          {/each}
        </div>

        <div class="flex flex-wrap gap-2 mb-4">
          <a
            href="/study/topics/{curriculum.topic_id}/review-queue"
            class="flex items-center gap-1.5 rounded border border-default px-3 py-1.5 text-xs text-dim hover:border-accent hover:text-text transition-colors"
          >
            <Repeat size={13} /> 문항 복습 <span class="font-semibold text-text">{curriculum.question_due}</span>
          </a>
          <span class="flex items-center gap-1.5 rounded border border-default px-3 py-1.5 text-xs text-dim">
            <BookOpen size={13} /> 개념 재복습 <span class="font-semibold text-text">{curriculum.concept_due}</span>
          </span>
        </div>
      {/if}

      <div class="text-xs text-dim mb-2">오늘의 개념</div>
      {#if todayConcepts.length === 0}
        <p class="text-xs text-dim">오늘 볼 개념이 없습니다. 잘 하고 있어요.</p>
      {:else}
        <ul class="space-y-1.5">
          {#each todayConcepts as c (c.doc_id)}
            <li class="flex items-center gap-2 rounded border border-default px-3 py-2">
              <span class="text-accent shrink-0 text-xs" title="빈출">{#each Array(c.freq) as _}★{/each}</span>
              <a href="/study/read/{c.doc_id}" class="text-sm text-text hover:text-accent truncate flex-1">{c.title}</a>
              <span class="shrink-0 text-[10px] rounded-full px-2 py-0.5 {c.reason === '재복습' ? 'bg-accent/15 text-accent' : 'bg-surface border border-default text-dim'}">{c.reason}</span>
              <button
                type="button"
                onclick={() => markRead(c)}
                class="shrink-0 text-xs rounded border border-default px-2 py-1 text-dim hover:border-accent hover:text-accent transition-colors"
              >읽음</button>
            </li>
          {/each}
        </ul>
      {/if}

      {#if weakConcepts.length > 0}
        <div class="mt-4 pt-3 border-t border-default">
          <div class="text-xs text-dim mb-2 flex items-center gap-1.5">
            <Target size={13} class="text-error" /> 약점 개념 <span class="text-faint">(관련 기출 정답률 낮음)</span>
          </div>
          <div class="flex flex-wrap gap-2">
            {#each weakConcepts as w (w.doc_id)}
              <a href="/study/read/{w.doc_id}"
                class="text-xs rounded-full border border-error/40 bg-error/10 text-error px-3 py-1 hover:bg-error/20 transition-colors">
                {w.title.replace(/^\d+_/, '')} <span class="font-semibold">{w.accuracy}%</span>
              </a>
            {/each}
          </div>
        </div>
      {/if}
    {/if}
  </section>

  <a
    href="/study/topics"
    class="block mb-3 p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
  >
    <div class="flex items-center gap-2 mb-2">
      <FolderKanban size={18} class="text-accent" />
      <h2 class="text-base font-semibold text-text">주제로 보기</h2>
    </div>
    <p class="text-xs text-dim">"가스기사" 같은 학습 주제 아래에 필기 세션과 자료를 함께 묶어 본다. 한 주제 안에서 필기·자료를 한눈에.</p>
  </a>

  <a
    href="/study/diagnosis"
    class="block mb-3 p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
  >
    <div class="flex items-center gap-2 mb-2">
      <Activity size={18} class="text-accent" />
      <h2 class="text-base font-semibold text-text">학습 진단</h2>
    </div>
    <p class="text-xs text-dim">누적 풀이 이력에서 약점 토픽과 학습 태도를 코치(이드)가 진단합니다. 매일 새벽 약점 스냅샷을 만들고, 권장 복습세트 초안까지 제안.</p>
  </a>

  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
    <a
      href="/study/sources"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <BookOpen size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">자료 학습</h2>
      </div>
      <p class="text-xs text-dim">자료실에 올린 학습 자료를 카테고리별로 읽고 회독 카운트를 누적합니다. "안 본 자료만" 필터로 진도 관리.</p>
    </a>

    <a
      href="/study/write"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <PenLine size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">손글씨 필사 세션</h2>
      </div>
      <p class="text-xs text-dim">iPad + Apple Pencil 로 자격증 교재 / 어학 한자·단어를 손으로 필사. 세션 단위 stroke 보존.</p>
    </a>

    <a
      href="/study/cards-review"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <Layers size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">암기카드 검수</h2>
        {#if cardReviewCount > 0}
          <span class="ml-auto rounded-full bg-accent px-2 py-0.5 text-xs font-bold text-white">{cardReviewCount}</span>
        {/if}
      </div>
      <p class="text-xs text-dim">푼 문제에서 AI가 추출한 암기카드(cloze 빈칸 / qa)를 확인하고 승인·수정·폐기. 승인된 카드만 학습에 쓰입니다.</p>
    </a>

    <a
      href="/study/cards-study"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <Repeat size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">암기카드 학습</h2>
      </div>
      <p class="text-xs text-dim">검수한 암기카드를 모바일에서 학습. <b>복습(간격반복 1·3·7·14일)</b>으로 자기평가하거나, <b>그냥 공부</b>로 덜 본 카드를 가볍게 훑어봅니다.</p>
    </a>

    <a
      href="/study/review-box"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <Inbox size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">복습함</h2>
      </div>
      <p class="text-xs text-dim">오늘 복습할 카드와 미확인 카드를 한눈에 보고, <b>골라서</b> 복습합니다.</p>
    </a>

    <a
      href="/study/questions-review"
      class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
    >
      <div class="flex items-center gap-2 mb-2">
        <Flag size={18} class="text-accent" />
        <h2 class="text-base font-semibold text-text">문제 신고함</h2>
        {#if questionFlagCount > 0}
          <span class="ml-auto rounded-full bg-warning px-2 py-0.5 text-xs font-bold text-white">{questionFlagCount}</span>
        {/if}
      </div>
      <p class="text-xs text-dim">퀴즈·문제 화면에서 <b>이상하다고 신고한 문제</b>를 모아 확인하고 수정·검토 완료·폐기합니다.</p>
    </a>
  </div>

  <div class="mt-6 p-4 rounded-lg border border-dashed border-default/60 text-xs text-dim">
    <div class="font-medium text-dim mb-1">예정</div>
    <ul class="list-disc list-inside space-y-0.5">
      <li>개념 학습 리더 (가리고 떠올리기 · 빈출★ · 관련개념 백링크)</li>
      <li>이론↔문제 연결 (개념별 정답률 · 약점 개념 지도)</li>
    </ul>
  </div>
</div>
