<script>
  /**
   * /study/questions-review — 문제 신고함 (이상 태깅된 study_questions 검수).
   *
   * 퀴즈/문제 화면의 '이 문제 이상해요'(PATCH needs_review=true)로 신고된 문제를 전 토픽 횡단으로 모아
   * 확인 → 수정 / 검토 완료(신고 해제) / 폐기. 암기카드 검수(/study/cards-review)의 문제 버전.
   *
   * backend: GET /study-questions/needs-review (목록) · /needs-review/count (배지)
   *          PATCH /study-questions/{id} {needs_review:false} (검토 완료) · DELETE /study-questions/{id} (폐기, soft)
   */
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { ArrowLeft, Flag, Check, Pencil, Trash2, Eye } from 'lucide-svelte';
  import Button from '$lib/components/ui/Button.svelte';
  import Skeleton from '$lib/components/ui/Skeleton.svelte';
  import EmptyState from '$lib/components/ui/EmptyState.svelte';

  let loading = $state(true);
  let items = $state([]); // [{id, study_topic_id, question_text, flagged_at, flagged_by}]

  // flagged_by 사유 → 라벨/색 (서버 상수: user / source_changed / source_deleted)
  const REASON = {
    user: { label: '직접 신고', cls: 'border-warning/40 text-warning bg-warning/10' },
    source_changed: { label: '문제 수정됨', cls: 'border-accent-ring text-accent bg-accent/10' },
    source_deleted: { label: '문제 삭제됨', cls: 'border-error/40 text-error bg-error/10' },
  };
  function reasonOf(by) {
    return REASON[by] ?? { label: '신고', cls: 'border-default text-dim bg-surface' };
  }

  async function load() {
    loading = true;
    try {
      items = (await api('/study-questions/needs-review')) ?? [];
    } catch (err) {
      addToast('error', err?.detail || '신고 목록 조회 실패');
      items = [];
    } finally {
      loading = false;
    }
  }

  function removeLocal(id) {
    items = items.filter((it) => it.id !== id);
  }

  async function resolve(it) {
    try {
      await api(`/study-questions/${it.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ needs_review: false }),
      });
      removeLocal(it.id);
      addToast('success', '검토 완료 — 신고를 해제했어요');
    } catch (err) {
      addToast('error', err?.detail || '처리 실패');
    }
  }

  async function discard(it) {
    if (!confirm('이 문제를 폐기할까요? (되돌릴 수 없음)')) return;
    try {
      await api(`/study-questions/${it.id}`, { method: 'DELETE' });
      removeLocal(it.id);
      addToast('success', '문제를 폐기했어요');
    } catch (err) {
      addToast('error', err?.detail || '삭제 실패');
    }
  }

  function fmtDate(s) {
    if (!s) return '';
    return new Date(s).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' });
  }

  onMount(load);
</script>

<svelte:head><title>문제 신고함</title></svelte:head>

<div class="mx-auto max-w-3xl px-4 py-6">
  <div class="mb-5 flex items-center gap-3">
    <Button variant="ghost" size="sm" icon={ArrowLeft} onclick={() => goto('/study')}>공부</Button>
    <h1 class="text-xl font-bold text-text">문제 신고함</h1>
    {#if items.length > 0}
      <span class="rounded-full bg-warning px-2.5 py-0.5 text-xs font-bold text-white">{items.length}</span>
    {/if}
  </div>

  <p class="mb-4 text-sm text-dim">
    퀴즈나 문제 화면에서 <b class="text-text">이상하다고 신고한 문제</b>가 여기에 모입니다.
    내용을 확인해 <b class="text-text">수정하거나, 검토 완료(신고 해제)하거나, 폐기</b>하세요.
  </p>

  {#if loading}
    <div class="space-y-3">{#each Array(4).fill(0) as _, i (i)}<Skeleton class="h-24 w-full" />{/each}</div>
  {:else if items.length === 0}
    <EmptyState
      title="신고된 문제가 없습니다"
      description="문제나 정답이 이상할 때 퀴즈·문제 화면의 '이 문제 이상해요'로 신고하면 여기에 쌓입니다."
      icon={Flag}
    />
  {:else}
    <div class="space-y-2.5">
      {#each items as it (it.id)}
        {@const r = reasonOf(it.flagged_by)}
        <div class="rounded-card border border-default bg-surface p-3.5">
          <div class="mb-2 flex items-center gap-2">
            <span class="rounded-full border px-2 py-0.5 text-[11px] font-semibold {r.cls}">{r.label}</span>
            {#if it.flagged_at}<span class="text-[11px] text-faint">{fmtDate(it.flagged_at)}</span>{/if}
          </div>
          <div class="text-sm leading-relaxed text-text">{it.question_text}</div>
          <div class="mt-3 flex flex-wrap gap-2">
            <Button href={`/study/topics/${it.study_topic_id}/questions/${it.id}`} variant="secondary" size="sm" icon={Eye}>문제 보기</Button>
            <Button href={`/study/topics/${it.study_topic_id}/questions/${it.id}/edit`} variant="ghost" size="sm" icon={Pencil}>수정</Button>
            <Button variant="ghost" size="sm" icon={Check} onclick={() => resolve(it)}>검토 완료</Button>
            <Button variant="danger" size="sm" icon={Trash2} onclick={() => discard(it)}>폐기</Button>
          </div>
        </div>
      {/each}
    </div>
  {/if}
</div>
