<script>
  /**
   * /study/write — 학습 세션 목록 + 새 세션 시작.
   *
   * 자격증/어학 study_type 토글 + 빠른 시작 폼 (필수 메타 최소만 입력 → 생성 후 작업 화면으로 이동).
   */
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { Plus, BookOpen, Languages, ArrowRight, Trash2 } 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';

  let studyType = $state('certification'); // 'certification' | 'language'
  let items = $state([]);
  let total = $state(0);
  let loading = $state(true);

  // 학습 워크스페이스(주제) 선택용 옵션
  let topicOptions = $state([{ value: '', label: '미지정' }]);

  // 빠른 시작 폼
  let formOpen = $state(false);
  let f_certification = $state('');
  let f_language_code = $state('ja');
  let f_learning_level = $state('');
  let f_subject = $state('');
  let f_topic = $state('');
  let f_source_text = $state('');
  let f_mode = $state('copy');
  let f_study_topic_id = $state('');
  let creating = $state(false);

  const MODE_OPTIONS = [
    { value: 'copy', label: '필사 (copy)' },
    { value: 'trace', label: '트레이싱 (trace)' },
    { value: 'blank-repeat', label: '깜지 (blank-repeat)' },
    { value: 'dictation', label: '받아쓰기 (dictation)' },
    { value: 'shadowing', label: '쉐도잉 (shadowing)' },
  ];
  const LANG_OPTIONS = [
    { value: 'ja', label: '일본어 (ja)' },
    { value: 'en', label: '영어 (en)' },
    { value: 'zh', label: '중국어 (zh)' },
    { value: 'ko', label: '한국어 (ko)' },
  ];

  async function load() {
    loading = true;
    try {
      const res = await api(`/study-sessions/?study_type=${studyType}&limit=50`);
      items = res.items;
      total = res.total;
    } catch (err) {
      addToast('error', '학습 세션 로딩 실패');
    } finally {
      loading = false;
    }
  }

  async function loadTopics() {
    try {
      const res = await api('/study-topics/?limit=200');
      topicOptions = [
        { value: '', label: '미지정' },
        ...res.items.map((t) => ({ value: String(t.id), label: t.name })),
      ];
    } catch {
      // 주제 로딩 실패는 비치명 — 미지정으로 진행 가능
    }
  }

  $effect(() => {
    void studyType;
    load();
  });

  onMount(() => {
    load();
    loadTopics();
  });

  async function createSession() {
    creating = true;
    try {
      const body = {
        study_type: studyType,
        learning_level: f_learning_level || null,
        subject: f_subject || null,
        topic: f_topic || null,
        source_text: f_source_text || null,
        mode: f_mode,
        study_topic_id: f_study_topic_id ? Number(f_study_topic_id) : null,
      };
      if (studyType === 'certification') {
        body.certification = f_certification || null;
      } else {
        body.language_code = f_language_code || null;
      }
      const sess = await api('/study-sessions/', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      addToast('success', '학습 세션 생성됨');
      goto(`/study/write/${sess.id}`);
    } catch (err) {
      addToast('error', err.detail || '세션 생성 실패');
    } finally {
      creating = false;
    }
  }

  async function removeSession(id) {
    if (!confirm('이 학습 세션을 삭제합니다. 연결된 documents 본체는 유지됩니다.')) return;
    try {
      await api(`/study-sessions/${id}`, { method: 'DELETE' });
      items = items.filter((s) => s.id !== id);
      total -= 1;
      addToast('success', '삭제됨');
    } catch (err) {
      addToast('error', err.detail || '삭제 실패');
    }
  }

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

<div class="p-4 md:p-6 max-w-5xl mx-auto">
  <!-- 헤더 + 도메인 토글 -->
  <div class="flex items-center justify-between mb-4">
    <h1 class="text-lg font-semibold text-text">공부</h1>
    <div class="flex items-center gap-1 bg-surface rounded-lg p-1 border border-default">
      <button
        type="button"
        onclick={() => (studyType = 'certification')}
        class="flex items-center gap-1.5 px-3 py-1.5 rounded text-sm transition-colors
          {studyType === 'certification' ? 'bg-accent/15 text-accent' : 'text-dim hover:text-text'}"
      >
        <BookOpen size={14} /> 자격증
      </button>
      <button
        type="button"
        onclick={() => (studyType = 'language')}
        class="flex items-center gap-1.5 px-3 py-1.5 rounded text-sm transition-colors
          {studyType === 'language' ? 'bg-accent/15 text-accent' : 'text-dim hover:text-text'}"
      >
        <Languages size={14} /> 어학
      </button>
    </div>
  </div>

  <!-- 빠른 시작 -->
  <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">새 {studyType === 'certification' ? '자격증' : '어학'} 세션</div>
            <Select
              label="학습 모드"
              bind:value={f_mode}
              options={MODE_OPTIONS}
            />
            {#if studyType === 'certification'}
              <TextInput label="자격증" bind:value={f_certification} placeholder="예: 산업안전기사" />
              <TextInput label="학습 레벨" bind:value={f_learning_level} placeholder="예: 1차" />
            {:else}
              <Select label="언어" bind:value={f_language_code} options={LANG_OPTIONS} />
              <TextInput label="학습 레벨" bind:value={f_learning_level} placeholder="예: JLPT N3" />
            {/if}
            <TextInput label="과목" bind:value={f_subject} placeholder={studyType === 'language' ? '예: 漢字' : '예: 산업안전보건법'} />
            <TextInput label="주제" bind:value={f_topic} placeholder={studyType === 'language' ? '예: 安全' : '예: 안전보건관리책임자의 직무'} />
            <Select label="학습 워크스페이스 (선택)" bind:value={f_study_topic_id} options={topicOptions} />
            <Textarea label="원문 텍스트" bind:value={f_source_text} rows={3} placeholder="발췌 원문 또는 학습 단어/문장" />
            <div class="flex gap-2 justify-end">
              <Button variant="ghost" onclick={() => (formOpen = false)} disabled={creating}>취소</Button>
              <Button onclick={createSession} loading={creating}>생성 후 시작</Button>
            </div>
          </div>
        {/if}
      </div>
    {/snippet}
  </Card>

  <!-- 목록 -->
  {#if loading}
    <div class="space-y-2">
      {#each Array(3) as _}
        <Skeleton class="h-16" />
      {/each}
    </div>
  {:else if items.length === 0}
    <EmptyState
      title="학습 세션이 없습니다"
      description="위 버튼으로 첫 세션을 시작하세요."
    />
  {:else}
    <div class="text-xs text-dim mb-2">총 {total}건</div>
    <div class="flex flex-col gap-2">
      {#each items as s (s.id)}
        <div class="flex items-center gap-3 p-3 rounded-lg border border-default bg-surface hover:bg-surface/80">
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-2 text-sm">
              {#if s.study_type === 'language'}
                <Languages size={14} class="text-dim" />
                <span class="text-dim text-xs">{s.language_code || '?'} · {s.learning_level || ''}</span>
              {:else}
                <BookOpen size={14} class="text-dim" />
                <span class="text-dim text-xs">{s.certification || '미지정'}</span>
              {/if}
              <span class="text-dim text-xs">·</span>
              <span class="text-dim text-xs">{s.mode}</span>
            </div>
            <div class="text-sm text-text mt-1 truncate">
              {s.subject || '(과목 미지정)'} — {s.topic || '(주제 미지정)'}
            </div>
            <div class="text-[10px] text-dim mt-1">
              stroke {Array.isArray(s.strokes_json?.strokes) ? s.strokes_json.strokes.length : 0}건
              · assets {s.assets?.length ?? 0}개
              · {fmtDate(s.created_at)}
            </div>
          </div>
          <Button href={`/study/write/${s.id}`} size="sm" variant="ghost" icon={ArrowRight} iconPosition="right">열기</Button>
          <button
            type="button"
            onclick={() => removeSession(s.id)}
            class="p-1.5 rounded hover:bg-error/10 text-dim hover:text-error"
            aria-label="삭제"
          ><Trash2 size={14} /></button>
        </div>
      {/each}
    </div>
  {/if}
</div>
