<script lang="ts">
  // 야간 수집 뉴스 브리핑 (Morning Briefing) — 매일 KST 05:10 cron 으로 만들어진
  // topic×country 비교 분석 1페이지 카드. 기존 article list / source tree /
  // 북마크 / 노트 / 필터 UI 는 폐기 (PR-MorningBriefing-2 swap).
  import { onMount } from 'svelte';
  import { api, type ApiError } from '$lib/api';
  import Card from '$lib/components/ui/Card.svelte';

  type CountryPerspective = {
    country: string;
    summary: string;
    article_ids: number[];
  };

  type KeyQuote = {
    country: string;
    source: string;
    quote: string;
  };

  type BriefingTopic = {
    id: number;
    topic_rank: number;
    topic_label: string;
    headline: string;
    country_perspectives: CountryPerspective[];
    divergences: string[];
    convergences: string[];
    key_quotes: KeyQuote[];
    historical_context: string | null;
    cluster_members: number[];
    article_count: number;
    country_count: number;
    importance_score: number;
    llm_fallback_used: boolean;
    is_read: boolean;
    read_at: string | null;
    highlighted: boolean;
    highlighted_at: string | null;
  };

  type BriefingDateSummary = {
    briefing_date: string;
    total_topics: number;
    total_articles: number;
    status: string;
    read_count: number;
    highlighted_count: number;
  };

  type Briefing = {
    briefing_date: string;
    window_start: string;
    window_end: string;
    total_articles: number;
    total_countries: number;
    total_topics: number;
    llm_calls: number;
    llm_failures: number;
    status: 'success' | 'partial' | 'failed' | 'empty';
    headline_oneliner: string | null;
    topics: BriefingTopic[];
  };

  const COUNTRY_META: Record<string, { flag: string; label: string }> = {
    KR: { flag: '🇰🇷', label: '한국' },
    US: { flag: '🇺🇸', label: '미국' },
    JP: { flag: '🇯🇵', label: '일본' },
    CN: { flag: '🇨🇳', label: '중국' },
    HK: { flag: '🇭🇰', label: '홍콩' },
    TW: { flag: '🇹🇼', label: '대만' },
    DE: { flag: '🇩🇪', label: '독일' },
    FR: { flag: '🇫🇷', label: '프랑스' },
    GB: { flag: '🇬🇧', label: '영국' },
    UK: { flag: '🇬🇧', label: '영국' },
    IN: { flag: '🇮🇳', label: '인도' },
    RU: { flag: '🇷🇺', label: '러시아' },
    IR: { flag: '🇮🇷', label: '이란' },
    IL: { flag: '🇮🇱', label: '이스라엘' },
    PH: { flag: '🇵🇭', label: '필리핀' },
    AU: { flag: '🇦🇺', label: '호주' },
    NL: { flag: '🇳🇱', label: '네덜란드' },
  };
  function countryLabel(code: string): string {
    const meta = COUNTRY_META[code?.toUpperCase()];
    return meta ? `${meta.flag} ${meta.label}` : code;
  }

  let briefing = $state<Briefing | null>(null);
  let loading = $state(true);
  let errorMsg = $state<string | null>(null);
  // 2026-05-13 추가 — 날짜 선택 + 카드 액션
  let availableDates = $state<BriefingDateSummary[]>([]);
  let selectedDate = $state<string>('');  // YYYY-MM-DD ('' = 최신)

  async function loadBriefing(dateStr: string) {
    loading = true;
    errorMsg = null;
    try {
      const path = dateStr ? `/briefing?date=${dateStr}` : '/briefing/latest';
      briefing = await api<Briefing>(path);
    } catch (e) {
      const err = e as ApiError;
      briefing = null;
      errorMsg = err?.status === 404
        ? (dateStr ? `${dateStr} 자에는 briefing 이 없습니다.` : '아직 생성된 브리핑이 없습니다. 매일 새벽 05:10 KST 에 자동 생성됩니다.')
        : (err?.detail || '브리핑을 불러오지 못했습니다.');
    } finally {
      loading = false;
    }
  }

  async function loadDates() {
    try {
      availableDates = await api<BriefingDateSummary[]>('/briefing/dates');
    } catch {
      availableDates = [];
    }
  }

  function onDateChange() {
    loadBriefing(selectedDate);
  }

  async function toggleRead(topic: BriefingTopic) {
    if (!briefing) return;
    const next = !topic.is_read;
    try {
      const r = await api<{ id: number; is_read: boolean; read_at: string | null; highlighted: boolean; highlighted_at: string | null }>(
        `/briefing/topics/${topic.id}/read`,
        { method: 'PATCH', body: JSON.stringify({ value: next }) }
      );
      topic.is_read = r.is_read;
      topic.read_at = r.read_at;
    } catch (e) {
      console.error('toggleRead failed', e);
    }
  }

  async function toggleHighlight(topic: BriefingTopic) {
    if (!briefing) return;
    const next = !topic.highlighted;
    try {
      const r = await api<{ id: number; is_read: boolean; read_at: string | null; highlighted: boolean; highlighted_at: string | null }>(
        `/briefing/topics/${topic.id}/highlight`,
        { method: 'PATCH', body: JSON.stringify({ value: next }) }
      );
      topic.highlighted = r.highlighted;
      topic.highlighted_at = r.highlighted_at;
    } catch (e) {
      console.error('toggleHighlight failed', e);
    }
  }

  onMount(async () => {
    await Promise.all([loadDates(), loadBriefing('')]);
  });

  const fallbackPct = $derived(
    briefing && briefing.llm_calls > 0
      ? Math.round((briefing.llm_failures / briefing.llm_calls) * 100)
      : 0
  );
</script>

<div class="mx-auto max-w-3xl px-4 py-6 space-y-4">
  <header class="space-y-2">
    <div class="flex items-center justify-between gap-3 flex-wrap">
      <h1 class="text-xl font-semibold">야간 뉴스 브리핑</h1>
      {#if availableDates.length > 0}
        <div class="flex items-center gap-2">
          <label for="briefing-date" class="text-xs text-dim">날짜</label>
          <select
            id="briefing-date"
            bind:value={selectedDate}
            onchange={onDateChange}
            class="text-sm border border-default rounded-md px-2 py-1 bg-surface"
          >
            <option value="">최신</option>
            {#each availableDates as d}
              <option value={d.briefing_date}>
                {d.briefing_date} · {d.total_topics}토픽
                {#if d.highlighted_count > 0}⭐{d.highlighted_count}{/if}
              </option>
            {/each}
          </select>
        </div>
      {/if}
    </div>
    <p class="text-sm text-dim">
      {#if briefing}
        {briefing.briefing_date} 새벽 수집 · 총 {briefing.total_articles}건 / {briefing.total_countries}개국 / {briefing.total_topics}개 토픽
      {:else}
        매일 KST 자정~05:00 누적 뉴스를 주제별로 다국 비교 분석합니다.
      {/if}
    </p>
  </header>

  {#if loading}
    <Card>
      <p class="text-sm text-dim">불러오는 중…</p>
    </Card>
  {:else if errorMsg}
    <Card>
      <p class="text-sm">{errorMsg}</p>
    </Card>
  {:else if briefing}
    {#if briefing.status === 'empty'}
      <Card>
        <p class="text-sm">
          오늘 새벽({briefing.briefing_date}) 다국 비교 가능한 토픽이 없습니다.
        </p>
        <p class="mt-2 text-xs text-dim">
          (수집 뉴스 0건 또는 2개국 이상 다룬 주제 없음)
        </p>
      </Card>
    {:else}
      {#if briefing.status === 'failed'}
        <div class="border border-error/40 bg-error/10 text-sm rounded-md px-4 py-3">
          ⚠ LLM 분석 실패율이 높습니다 ({briefing.llm_failures}/{briefing.llm_calls}, {fallbackPct}%). 일부 토픽이 원문 묶음으로 표시됩니다.
        </div>
      {:else if briefing.status === 'partial'}
        <div class="border border-warning/40 bg-warning/10 text-sm rounded-md px-4 py-3">
          일부 토픽 LLM 실패 ({briefing.llm_failures}/{briefing.llm_calls}). 다른 토픽은 정상 분석되었습니다.
        </div>
      {/if}

      {#each briefing.topics as topic (topic.id)}
        <div class:opacity-60={topic.is_read}>
        <Card class={topic.highlighted ? "ring-2 ring-yellow-400" : ""}>
          <div class="space-y-3">
            <div class="flex items-start gap-2">
              <span class="text-xs text-faint shrink-0 pt-1">#{topic.topic_rank}</span>
              <div class="flex-1 min-w-0">
                <h2 class="text-base font-semibold leading-snug">
                  {topic.topic_label}
                  {#if topic.llm_fallback_used}
                    <span class="ml-1 text-xs text-dim">(원문 묶음)</span>
                  {/if}
                </h2>
                <p class="text-sm text-dim mt-1">{topic.headline}</p>
                <p class="text-xs text-faint mt-1">
                  {topic.country_count}개국 · {topic.article_count}건
                </p>
              </div>
              <div class="flex flex-col items-end gap-1 shrink-0">
                <button
                  type="button"
                  onclick={() => toggleHighlight(topic)}
                  class="text-base leading-none px-1.5 py-0.5 rounded hover:bg-surface"
                  class:text-yellow-500={topic.highlighted}
                  class:text-faint={!topic.highlighted}
                  title={topic.highlighted ? '하이라이트 해제' : '하이라이트'}
                  aria-label="하이라이트 토글"
                >★</button>
                <button
                  type="button"
                  onclick={() => toggleRead(topic)}
                  class="text-xs px-1.5 py-0.5 rounded border border-default hover:bg-surface"
                  title={topic.is_read ? '읽지 않음으로' : '읽음 처리'}
                  aria-label="읽음 토글"
                >{topic.is_read ? '✓읽음' : '읽음'}</button>
              </div>
            </div>

            {#if topic.country_perspectives.length > 0}
              <div class="space-y-1.5">
                {#each topic.country_perspectives as cp}
                  <div class="text-sm leading-relaxed">
                    <span class="font-medium">{countryLabel(cp.country)}</span>
                    <span class="text-dim mx-1">·</span>
                    <span>{cp.summary}</span>
                    {#if cp.article_ids.length > 0}
                      <span class="ml-1 text-xs text-faint">
                        {#each cp.article_ids as id, i}
                          {#if i > 0}<span class="mx-0.5">·</span>{/if}<a
                            href={`/documents/${id}`}
                            class="hover:text-accent"
                          >#{id}</a>
                        {/each}
                      </span>
                    {/if}
                  </div>
                {/each}
              </div>
            {/if}

            {#if topic.divergences.length > 0}
              <div class="text-xs">
                <span class="text-dim">차이 </span>
                <span class="text-text">{topic.divergences.join(' · ')}</span>
              </div>
            {/if}

            {#if topic.convergences.length > 0}
              <div class="text-xs">
                <span class="text-dim">공통 </span>
                <span class="text-text">{topic.convergences.join(' · ')}</span>
              </div>
            {/if}

            {#if topic.key_quotes.length > 0}
              <ul class="text-xs space-y-1 border-l-2 border-default pl-3">
                {#each topic.key_quotes as q}
                  <li>
                    <span class="text-dim">{countryLabel(q.country)} · {q.source}</span>
                    <span class="text-text">"{q.quote}"</span>
                  </li>
                {/each}
              </ul>
            {/if}

            {#if topic.historical_context}
              <p class="text-xs text-faint italic">
                ↩ 지난 흐름 · {topic.historical_context}
              </p>
            {/if}
          </div>
        </Card>
        </div>
      {/each}
    {/if}
  {/if}
</div>
