<script lang="ts">
  /**
   * StudyMetaEditor — 학습 세션의 도메인 메타 편집.
   *
   * - study_type 토글: certification / language
   * - 자격증: certification + learning_level + subject + topic
   * - 어학:   language_code + learning_level + subject + topic + metadata.reading/meaning/unit_type
   * - source_text + source_page (공통)
   * - mode 선택 (copy / trace / blank-repeat / dictation / shadowing)
   *
   * 부모가 onPatch(partial) 호출로 PATCH /api/study-sessions/{id} 트리거.
   * Phase 1 단순화: source_document 검색 모달 없음 — source_text 직접 입력만.
   * (Phase 2 에서 /library 검색 모달 추가)
   */
  import TextInput from '$lib/components/ui/TextInput.svelte';
  import Select from '$lib/components/ui/Select.svelte';
  import Textarea from '$lib/components/ui/Textarea.svelte';

  type StudyType = 'certification' | 'language';
  type Mode = 'copy' | 'trace' | 'blank-repeat' | 'dictation' | 'shadowing';

  export interface StudyMeta {
    study_type: StudyType;
    certification?: string | null;
    language_code?: string | null;
    learning_level?: string | null;
    subject?: string | null;
    topic?: string | null;
    source_text?: string | null;
    source_page?: number | null;
    mode: Mode;
    metadata?: Record<string, unknown> | null;
  }

  interface Props {
    meta: StudyMeta;
    onPatch?: (partial: Partial<StudyMeta>) => void;
  }
  let { meta, onPatch }: Props = $props();

  // 어학 metadata 의 자주 쓰는 필드를 분리해 binding (NULL 안전 처리)
  let lm = $derived((meta.metadata ?? {}) as Record<string, string>);

  function patchMetadata(key: string, value: string) {
    const next = { ...(meta.metadata ?? {}), [key]: value || undefined };
    // undefined 키 제거
    const cleaned: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(next)) if (v !== undefined && v !== '') cleaned[k] = v;
    onPatch?.({ metadata: cleaned });
  }

  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: '', label: '(미지정)' },
    { value: 'ja', label: '일본어 (ja)' },
    { value: 'en', label: '영어 (en)' },
    { value: 'zh', label: '중국어 (zh)' },
    { value: 'ko', label: '한국어 (ko)' },
  ];
  const UNIT_TYPE_OPTIONS = [
    { value: '', label: '(미지정)' },
    { value: 'kanji', label: '한자' },
    { value: 'vocabulary', label: '단어' },
    { value: 'sentence', label: '문장' },
    { value: 'listening', label: '듣기' },
    { value: 'shadowing', label: '쉐도잉' },
  ];
</script>

<div class="flex flex-col gap-3 p-3">
  <!-- study_type 토글 -->
  <div class="flex items-center gap-2">
    <span class="text-xs text-dim w-20">도메인</span>
    <div class="flex gap-1">
      <button
        type="button"
        onclick={() => onPatch?.({ study_type: 'certification' })}
        class="px-3 py-1 rounded text-xs transition-colors
          {meta.study_type === 'certification' ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface'}"
      >자격증</button>
      <button
        type="button"
        onclick={() => onPatch?.({ study_type: 'language' })}
        class="px-3 py-1 rounded text-xs transition-colors
          {meta.study_type === 'language' ? 'bg-accent/15 text-accent' : 'text-dim hover:bg-surface'}"
      >어학</button>
    </div>
  </div>

  <!-- 학습 모드 -->
  <Select
    label="학습 모드"
    value={meta.mode}
    options={MODE_OPTIONS}
    onchange={(e: Event) => onPatch?.({ mode: (e.target as HTMLSelectElement).value as Mode })}
  />

  {#if meta.study_type === 'certification'}
    <TextInput
      label="자격증"
      value={meta.certification ?? ''}
      placeholder="예: 산업안전기사"
      onblur={(e: FocusEvent) => onPatch?.({ certification: (e.target as HTMLInputElement).value })}
    />
    <TextInput
      label="학습 레벨"
      value={meta.learning_level ?? ''}
      placeholder="예: 1차, 2차"
      onblur={(e: FocusEvent) => onPatch?.({ learning_level: (e.target as HTMLInputElement).value })}
    />
  {:else}
    <Select
      label="언어"
      value={meta.language_code ?? ''}
      options={LANG_OPTIONS}
      onchange={(e: Event) => onPatch?.({ language_code: (e.target as HTMLSelectElement).value || null })}
    />
    <TextInput
      label="학습 레벨"
      value={meta.learning_level ?? ''}
      placeholder="예: JLPT N3, TOEIC 750"
      onblur={(e: FocusEvent) => onPatch?.({ learning_level: (e.target as HTMLInputElement).value })}
    />
  {/if}

  <TextInput
    label="과목 (subject)"
    value={meta.subject ?? ''}
    placeholder={meta.study_type === 'language' ? '예: 漢字, 어휘' : '예: 산업안전보건법'}
    onblur={(e: FocusEvent) => onPatch?.({ subject: (e.target as HTMLInputElement).value })}
  />
  <TextInput
    label="주제 (topic)"
    value={meta.topic ?? ''}
    placeholder={meta.study_type === 'language' ? '예: 安全' : '예: 안전보건관리책임자의 직무'}
    onblur={(e: FocusEvent) => onPatch?.({ topic: (e.target as HTMLInputElement).value })}
  />

  <!-- 원문 텍스트 snapshot -->
  <Textarea
    label="원문 텍스트 (snapshot)"
    value={meta.source_text ?? ''}
    rows={3}
    placeholder={meta.study_type === 'language' ? '예: 安全' : '예: 산업안전보건법 제15조 발췌'}
    onblur={(e: FocusEvent) => onPatch?.({ source_text: (e.target as HTMLTextAreaElement).value })}
  />

  {#if meta.study_type === 'language'}
    <!-- 어학 전용 metadata -->
    <Select
      label="단위 (unit_type)"
      value={(lm.unit_type as string) ?? ''}
      options={UNIT_TYPE_OPTIONS}
      onchange={(e: Event) => patchMetadata('unit_type', (e.target as HTMLSelectElement).value)}
    />
    <TextInput
      label="reading"
      value={(lm.reading as string) ?? ''}
      placeholder="예: あんぜん"
      onblur={(e: FocusEvent) => patchMetadata('reading', (e.target as HTMLInputElement).value)}
    />
    <TextInput
      label="meaning (한국어 뜻)"
      value={(lm.meaning as string) ?? ''}
      placeholder="예: 안전"
      onblur={(e: FocusEvent) => patchMetadata('meaning', (e.target as HTMLInputElement).value)}
    />
    <Textarea
      label="example_sentence"
      value={(lm.example_sentence as string) ?? ''}
      rows={2}
      placeholder="예: 安全第一です。"
      onblur={(e: FocusEvent) => patchMetadata('example_sentence', (e.target as HTMLTextAreaElement).value)}
    />
  {/if}
</div>
