<script>
  /**
   * /study/topics — 학습 워크스페이스(주제) 목록.
   *
   * 한 주제(예: 가스기사) 아래에 필기 세션과 자료(library document)를 묶어 본다.
   * 1차 컨테이너로 향후 단어장/오디오/문제세트 같은 학습 자산이 같은 묶음으로 들어올 예정.
   *
   * - 카드 그리드 (세션 수 / 자료 수 표시)
   * - 새 주제 생성 인라인 폼
   * - 주제 클릭 시 /study/topics/[id] 통합 뷰로 이동
   */
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { Plus, ArrowLeft, FolderKanban, Trash2, Pencil } 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';
  import TextInput from '$lib/components/ui/TextInput.svelte';
  import Select from '$lib/components/ui/Select.svelte';
  import Textarea from '$lib/components/ui/Textarea.svelte';
  import StudyDiagnosisPanel from '$lib/components/StudyDiagnosisPanel.svelte';

  const STUDY_TYPE_OPTIONS = [
    { value: '', label: '미지정' },
    { value: 'certification', label: '자격증 (certification)' },
    { value: 'language', label: '어학 (language)' },
    { value: 'school', label: '학교 (school)' },
    { value: 'work', label: '업무 (work)' },
    { value: 'general', label: '일반 (general)' },
  ];

  let topics = $state([]);
  let total = $state(0);
  let loading = $state(true);

  // 생성 폼
  let formOpen = $state(false);
  let f_name = $state('');
  let f_description = $state('');
  let f_color = $state('');
  let f_study_type = $state('');
  // PR-6: 시험 메타
  let f_exam_round_size = $state(''); // 빈 값 = 미설정
  let f_exam_subjects = $state([]); // 문자열 배열
  let f_subject_input = $state('');
  let creating = $state(false);

  function addSubject() {
    const v = f_subject_input.trim();
    if (!v) return;
    if (!f_exam_subjects.includes(v)) f_exam_subjects = [...f_exam_subjects, v];
    f_subject_input = '';
  }
  function removeSubject(s) {
    f_exam_subjects = f_exam_subjects.filter((x) => x !== s);
  }

  // 편집 모달
  let editing = $state(null); // {id, name, description, color, study_type, exam_round_size, exam_subjects}
  let savingEdit = $state(false);
  let edit_subject_input = $state('');

  function addEditSubject() {
    if (!editing) return;
    const v = edit_subject_input.trim();
    if (!v) return;
    if (!editing.exam_subjects.includes(v)) editing.exam_subjects = [...editing.exam_subjects, v];
    edit_subject_input = '';
  }
  function removeEditSubject(s) {
    if (!editing) return;
    editing.exam_subjects = editing.exam_subjects.filter((x) => x !== s);
  }

  async function load() {
    loading = true;
    try {
      const res = await api('/study-topics/?limit=200');
      topics = res.items;
      total = res.total;
    } catch (err) {
      addToast('error', err.detail || '학습 주제 로딩 실패');
    } finally {
      loading = false;
    }
  }

  onMount(load);

  async function createTopic() {
    if (!f_name.trim()) {
      addToast('error', '주제 이름을 입력하세요');
      return;
    }
    creating = true;
    try {
      const body = {
        name: f_name.trim(),
        description: f_description || null,
        color: f_color || null,
        study_type: f_study_type || null,
        exam_round_size: f_exam_round_size ? Number(f_exam_round_size) : null,
        exam_subjects: f_exam_subjects,
      };
      const t = await api('/study-topics/', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      topics = [t, ...topics];
      total += 1;
      addToast('success', '주제 생성됨');
      formOpen = false;
      f_name = '';
      f_description = '';
      f_color = '';
      f_study_type = '';
      f_exam_round_size = '';
      f_exam_subjects = [];
      f_subject_input = '';
    } catch (err) {
      addToast('error', err.detail || '주제 생성 실패');
    } finally {
      creating = false;
    }
  }

  function startEdit(t) {
    editing = {
      id: t.id,
      name: t.name,
      description: t.description ?? '',
      color: t.color ?? '',
      study_type: t.study_type ?? '',
      exam_round_size: t.exam_round_size ?? '',
      exam_subjects: [...(t.exam_subjects ?? [])],
    };
    edit_subject_input = '';
  }

  async function saveEdit() {
    if (!editing) return;
    if (!editing.name.trim()) {
      addToast('error', '주제 이름을 입력하세요');
      return;
    }
    savingEdit = true;
    try {
      const updated = await api(`/study-topics/${editing.id}`, {
        method: 'PATCH',
        body: JSON.stringify({
          name: editing.name.trim(),
          description: editing.description || null,
          color: editing.color || null,
          study_type: editing.study_type || null,
          exam_round_size: editing.exam_round_size === '' || editing.exam_round_size == null
            ? null
            : Number(editing.exam_round_size),
          exam_subjects: editing.exam_subjects ?? [],
        }),
      });
      topics = topics.map((x) => (x.id === updated.id ? updated : x));
      addToast('success', '저장됨');
      editing = null;
    } catch (err) {
      addToast('error', err.detail || '저장 실패');
    } finally {
      savingEdit = false;
    }
  }

  async function removeTopic(t) {
    if (!confirm(`"${t.name}" 주제를 삭제합니다.\n연결된 자료 매핑은 해제되고 세션은 미분류 상태로 남습니다.`)) return;
    try {
      await api(`/study-topics/${t.id}`, { method: 'DELETE' });
      topics = topics.filter((x) => x.id !== t.id);
      total -= 1;
      addToast('success', '삭제됨');
    } catch (err) {
      addToast('error', err.detail || '삭제 실패');
    }
  }

  function fmtDate(s) {
    return new Date(s).toLocaleDateString('ko-KR', { dateStyle: 'medium' });
  }
</script>

<svelte:head><title>주제로 보기 — 공부</title></svelte:head>

<div class="p-4 md:p-6 max-w-5xl 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 flex items-center gap-1">
      <ArrowLeft size={14} /> 공부
    </a>
    <span class="text-faint">/</span>
    <span class="text-text font-medium flex items-center gap-1.5">
      <FolderKanban size={14} class="text-accent" /> 주제로 보기
    </span>
  </div>

  <header class="mb-4">
    <h1 class="text-lg font-semibold text-text">학습 주제</h1>
    <p class="text-xs text-dim mt-1">한 주제 아래에 필기 세션과 자료를 묶어 보고 진도 관리. 향후 단어장·오디오·문제세트도 같은 묶음으로 연결됩니다.</p>
  </header>

  <!-- 이드 학습 진단 (공유 컴포넌트 — /study/diagnosis 와 동일 패널) -->
  <StudyDiagnosisPanel class="mb-4" />

  <!-- 새 주제 -->
  <Card class="mb-4">
    {#snippet children()}
      <div class="p-3">
        {#if !formOpen}
          <Button onclick={() => (formOpen = true)} icon={Plus} size="sm">새 주제</Button>
        {:else}
          <div class="flex flex-col gap-3">
            <div class="text-sm font-semibold text-text">새 학습 주제</div>
            <TextInput label="주제 이름" bind:value={f_name} placeholder="예: 가스기사" />
            <Textarea label="설명 (선택)" bind:value={f_description} rows={2} placeholder="이 주제의 학습 목표, 시험 일정 등" />
            <Select label="분류 (선택)" bind:value={f_study_type} options={STUDY_TYPE_OPTIONS} />
            <TextInput label="색상 (선택, hex)" bind:value={f_color} placeholder="#3B82F6" />

            <!-- PR-6: 시험 정보 -->
            <div class="border-t border-default pt-3 mt-1">
              <div class="text-xs font-semibold text-dim mb-2">시험 정보 (선택)</div>
              <div class="flex flex-col gap-2">
                <label class="flex flex-col gap-1.5">
                  <span class="text-xs text-dim">회차당 문항 수 (1~300)</span>
                  <input type="number" min="1" max="300" bind:value={f_exam_round_size}
                    placeholder="예: 100"
                    class="px-3 py-2 bg-surface border border-default rounded text-sm text-text outline-none focus:border-accent" />
                </label>
                <div class="flex flex-col gap-1.5">
                  <span class="text-xs text-dim">과목 리스트 (입력 시 드롭다운 옵션)</span>
                  <div class="flex gap-2">
                    <input type="text" bind:value={f_subject_input}
                      placeholder="예: 가스유체역학"
                      onkeydown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addSubject(); } }}
                      class="flex-1 px-3 py-1.5 bg-surface border border-default rounded text-sm text-text outline-none focus:border-accent" />
                    <Button size="sm" variant="ghost" onclick={addSubject} icon={Plus}>추가</Button>
                  </div>
                  {#if f_exam_subjects.length > 0}
                    <div class="flex flex-wrap gap-1.5 mt-1">
                      {#each f_exam_subjects as s}
                        <span class="inline-flex items-center gap-1 px-2 py-1 rounded bg-accent/10 border border-accent/30 text-xs text-text">
                          {s}
                          <button type="button" onclick={() => removeSubject(s)} class="text-dim hover:text-error" aria-label="제거">×</button>
                        </span>
                      {/each}
                    </div>
                  {/if}
                </div>
              </div>
            </div>

            <div class="flex gap-2 justify-end">
              <Button variant="ghost" onclick={() => (formOpen = false)} disabled={creating}>취소</Button>
              <Button onclick={createTopic} loading={creating}>생성</Button>
            </div>
          </div>
        {/if}
      </div>
    {/snippet}
  </Card>

  <!-- 목록 -->
  {#if loading}
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
      {#each Array(4) as _}<Skeleton h="h-24" rounded="lg" />{/each}
    </div>
  {:else if topics.length === 0}
    <EmptyState
      icon={FolderKanban}
      title="학습 주제가 없습니다"
      description="위 버튼으로 첫 주제를 만들고 필기·자료를 묶어보세요."
    />
  {:else}
    <div class="text-xs text-dim mb-2">총 {total}개</div>
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
      {#each topics as t (t.id)}
        <div class="relative p-4 rounded-lg border border-default bg-surface hover:border-accent transition-colors">
          <a href={`/study/topics/${t.id}`} class="block">
            <div class="flex items-center gap-2 mb-1">
              {#if t.color}
                <span class="inline-block w-3 h-3 rounded-full shrink-0" style="background-color: {t.color}"></span>
              {:else}
                <FolderKanban size={14} class="text-dim shrink-0" />
              {/if}
              <span class="text-sm font-semibold text-text truncate">{t.name}</span>
              {#if t.study_type}
                <span class="text-[10px] text-dim border border-default rounded px-1.5 py-0.5 shrink-0">{t.study_type}</span>
              {/if}
            </div>
            {#if t.description}
              <p class="text-xs text-dim line-clamp-2 mb-2">{t.description}</p>
            {/if}
            <div class="text-[10px] text-dim flex items-center gap-3 flex-wrap">
              <span>필기 <span class="text-text">{t.session_count}</span></span>
              <span>자료 <span class="text-text">{t.document_count}</span></span>
              <span>문제 <span class="text-text">{t.question_count ?? 0}</span></span>
              <span class="ml-auto">{fmtDate(t.created_at)}</span>
            </div>
          </a>
          <div class="absolute top-2 right-2 flex items-center gap-1">
            <button
              type="button"
              onclick={() => startEdit(t)}
              class="p-1.5 rounded hover:bg-bg text-dim hover:text-text"
              aria-label="편집"
            ><Pencil size={12} /></button>
            <button
              type="button"
              onclick={() => removeTopic(t)}
              class="p-1.5 rounded hover:bg-error/10 text-dim hover:text-error"
              aria-label="삭제"
            ><Trash2 size={12} /></button>
          </div>
        </div>
      {/each}
    </div>
  {/if}
</div>

<!-- 편집 모달 -->
{#if editing}
  <button
    type="button"
    aria-label="모달 닫기"
    onclick={() => (editing = null)}
    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-md 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>
      <div class="flex flex-col gap-3">
        <TextInput label="주제 이름" bind:value={editing.name} />
        <Textarea label="설명" bind:value={editing.description} rows={2} />
        <Select label="분류" bind:value={editing.study_type} options={STUDY_TYPE_OPTIONS} />
        <TextInput label="색상 (hex)" bind:value={editing.color} placeholder="#3B82F6" />

        <!-- PR-6: 시험 정보 -->
        <div class="border-t border-default pt-3 mt-1">
          <div class="text-xs font-semibold text-dim mb-2">시험 정보</div>
          <div class="flex flex-col gap-2">
            <label class="flex flex-col gap-1.5">
              <span class="text-xs text-dim">회차당 문항 수 (1~300, 비우면 미설정)</span>
              <input type="number" min="1" max="300" bind:value={editing.exam_round_size}
                placeholder="예: 100"
                class="px-3 py-2 bg-surface border border-default rounded text-sm text-text outline-none focus:border-accent" />
            </label>
            <div class="flex flex-col gap-1.5">
              <span class="text-xs text-dim">과목 리스트</span>
              <div class="flex gap-2">
                <input type="text" bind:value={edit_subject_input}
                  placeholder="예: 가스유체역학"
                  onkeydown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addEditSubject(); } }}
                  class="flex-1 px-3 py-1.5 bg-surface border border-default rounded text-sm text-text outline-none focus:border-accent" />
                <Button size="sm" variant="ghost" onclick={addEditSubject} icon={Plus}>추가</Button>
              </div>
              {#if editing.exam_subjects.length > 0}
                <div class="flex flex-wrap gap-1.5 mt-1">
                  {#each editing.exam_subjects as s}
                    <span class="inline-flex items-center gap-1 px-2 py-1 rounded bg-accent/10 border border-accent/30 text-xs text-text">
                      {s}
                      <button type="button" onclick={() => removeEditSubject(s)} class="text-dim hover:text-error" aria-label="제거">×</button>
                    </span>
                  {/each}
                </div>
              {/if}
            </div>
          </div>
        </div>
      </div>
      <div class="flex gap-2 justify-end mt-4">
        <Button variant="ghost" onclick={() => (editing = null)} disabled={savingEdit}>취소</Button>
        <Button onclick={saveEdit} loading={savingEdit}>저장</Button>
      </div>
    </div>
  </div>
{/if}
