<script>
  import { onMount } from 'svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/ui';
  import { marked } from 'marked';
  import DOMPurify from 'dompurify';

  function renderMd(text) {
    return DOMPurify.sanitize(marked(text), {
      USE_PROFILES: { html: true },
      FORBID_TAGS: ['style', 'script'],
      FORBID_ATTR: ['onerror', 'onclick'],
      ALLOW_UNKNOWN_PROTOCOLS: false,
    });
  }

  let articles = $state([]);
  let total = $state(0);
  let loading = $state(true);
  let selectedArticle = $state(null);
  let filterSource = $state('');
  let showUnreadOnly = $state(false);
  let sources = $state([]);
  let currentPage = $state(1);
  let noteEditing = $state(false);
  let noteText = $state('');

  onMount(async () => {
    try {
      const srcData = await api('/news/sources');
      // 신문사별 유니크
      const names = new Set();
      srcData.forEach(s => names.add(s.name.split(' ')[0]));
      sources = [...names];
    } catch (e) {}
    loadArticles();
  });

  async function loadArticles() {
    loading = true;
    try {
      const params = new URLSearchParams();
      params.set('page', String(currentPage));
      params.set('page_size', '30');
      if (filterSource) params.set('source', filterSource);
      if (showUnreadOnly) params.set('unread_only', 'true');

      const data = await api(`/news/articles?${params}`);
      articles = data.items;
      total = data.total;
    } catch (err) {
      addToast('error', '뉴스 로딩 실패');
    } finally {
      loading = false;
    }
  }

  function selectArticle(article) {
    selectedArticle = article;
    if (!article.is_read) markRead(article);
  }

  async function markRead(article) {
    try {
      await api(`/documents/${article.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ is_read: true }),
      });
      article.is_read = true;
      articles = [...articles];
    } catch (e) {}
  }

  async function markAllRead() {
    try {
      const result = await api('/news/mark-all-read', { method: 'POST' });
      addToast('success', `${result.marked}건 읽음 처리`);
      articles = articles.map(a => ({ ...a, is_read: true }));
    } catch (e) {
      addToast('error', '실패');
    }
  }

  async function saveNote() {
    try {
      await api(`/documents/${selectedArticle.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ user_note: noteText }),
      });
      selectedArticle.user_note = noteText;
      noteEditing = false;
      addToast('success', '저장됨');
    } catch (e) {
      addToast('error', '저장 실패');
    }
  }

  function timeAgo(dateStr) {
    const diff = Date.now() - new Date(dateStr).getTime();
    const mins = Math.floor(diff / 60000);
    if (mins < 60) return `${mins}분 전`;
    const hours = Math.floor(mins / 60);
    if (hours < 24) return `${hours}시간 전`;
    const days = Math.floor(hours / 24);
    return `${days}일 전`;
  }

  // 필터 변경 시에만 1페이지 리셋
  let prevFilter = '';
  $effect(() => {
    const key = `${filterSource}|${showUnreadOnly}`;
    if (key !== prevFilter) {
      prevFilter = key;
      currentPage = 1;
      loadArticles();
    }
  });
</script>

<div class="flex h-full">
  <!-- 좌측 필터 -->
  <div class="w-48 shrink-0 border-r border-[var(--border)] bg-[var(--sidebar-bg)] p-3 overflow-y-auto">
    <h2 class="text-xs font-semibold text-[var(--text-dim)] uppercase mb-3">필터</h2>

    <button
      onclick={() => { filterSource = ''; }}
      class="w-full text-left px-2 py-1.5 rounded text-sm mb-1 {filterSource === '' ? 'bg-[var(--accent)]/15 text-[var(--accent)]' : 'text-[var(--text-dim)] hover:bg-[var(--surface)]'}"
    >📰 전체</button>

    {#each sources as src}
      <button
        onclick={() => { filterSource = src; }}
        class="w-full text-left px-2 py-1.5 rounded text-sm mb-0.5 {filterSource === src ? 'bg-[var(--accent)]/15 text-[var(--accent)]' : 'text-[var(--text-dim)] hover:bg-[var(--surface)]'}"
      >{src}</button>
    {/each}

    <hr class="my-3 border-[var(--border)]">

    <label class="flex items-center gap-2 px-2 text-xs text-[var(--text-dim)]">
      <input type="checkbox" bind:checked={showUnreadOnly} class="rounded">
      읽지 않음만
    </label>
  </div>

  <!-- 메인 -->
  <div class="flex-1 flex flex-col min-h-0">
    <!-- 상단 바 -->
    <div class="flex items-center justify-between px-4 py-2 border-b border-[var(--border)] shrink-0">
      <span class="text-xs text-[var(--text-dim)]">{total}건</span>
      <button
        onclick={markAllRead}
        class="text-xs text-[var(--text-dim)] hover:text-[var(--accent)] px-2 py-1 rounded border border-[var(--border)]"
      >전체 읽음</button>
    </div>

    <!-- 상단: 기사 리스트 -->
    <div class="overflow-y-auto {selectedArticle ? 'h-[40%] shrink-0 border-b border-[var(--border)]' : 'flex-1'}">
      {#if loading}
        <div class="p-4 space-y-2">
          {#each Array(5) as _}
            <div class="h-12 bg-[var(--surface)] rounded animate-pulse"></div>
          {/each}
        </div>
      {:else if articles.length === 0}
        <div class="text-center py-16 text-[var(--text-dim)]">
          <p class="text-sm">뉴스가 없습니다</p>
        </div>
      {:else}
        {#each articles as article}
          <button
            onclick={() => selectArticle(article)}
            class="w-full text-left px-4 py-2.5 border-b border-[var(--border)]/30 hover:bg-[var(--surface)] transition-colors
              {selectedArticle?.id === article.id ? 'bg-[var(--accent)]/5 border-l-2 border-l-[var(--accent)]' : ''}"
          >
            <div class="flex items-start gap-2">
              <span class="mt-1 text-[10px] {article.is_read ? 'text-[var(--text-dim)]' : 'text-[var(--accent)]'}">
                {article.is_read ? '○' : '●'}
              </span>
              <div class="min-w-0">
                <p class="text-sm truncate {article.is_read ? 'text-[var(--text-dim)]' : 'font-medium'}">{article.title}</p>
                <div class="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--text-dim)]">
                  <span>{article.ai_sub_group || ''}</span>
                  {#if article.ai_tags?.length}
                    <span>{article.ai_tags[0]?.split('/').pop()}</span>
                  {/if}
                  <span>{timeAgo(article.created_at)}</span>
                </div>
              </div>
            </div>
          </button>
        {/each}
      {/if}
    </div>

    <!-- 페이지네이션 -->
    {#if total > 30}
      <div class="flex justify-center gap-1 py-2 border-t border-[var(--border)] shrink-0">
        {#each Array(Math.ceil(total / 30)) as _, i}
          <button
            onclick={() => { currentPage = i + 1; loadArticles(); }}
            class="px-2 py-0.5 rounded text-xs {currentPage === i + 1 ? 'bg-[var(--accent)] text-white' : 'text-[var(--text-dim)]'}"
          >{i + 1}</button>
        {/each}
      </div>
    {/if}

    <!-- 하단: 기사 미리보기 -->
    {#if selectedArticle}
      <div class="flex-1 overflow-y-auto bg-[var(--surface)] min-h-0">
        <!-- 미리보기 헤더 -->
        <div class="flex items-center justify-between px-5 py-2 border-b border-[var(--border)] sticky top-0 bg-[var(--surface)]">
          <div class="flex items-center gap-2 text-xs text-[var(--text-dim)]">
            <span>{selectedArticle.ai_sub_group}</span>
            <span>·</span>
            <span>{timeAgo(selectedArticle.created_at)}</span>
            <span>·</span>
            <span>{selectedArticle.file_format}</span>
          </div>
          <div class="flex items-center gap-2">
            {#if selectedArticle.edit_url}
              <a
                href={selectedArticle.edit_url}
                target="_blank"
                rel="noopener noreferrer"
                class="text-xs text-[var(--accent)] hover:underline"
              >원문 보기 →</a>
            {/if}
            <a
              href="/documents/{selectedArticle.id}"
              class="text-xs text-[var(--text-dim)] hover:text-[var(--text)]"
              target="_blank"
            >문서 상세 ↗</a>
            <button
              onclick={() => selectedArticle = null}
              class="text-xs text-[var(--text-dim)] hover:text-[var(--text)]"
            >닫기</button>
          </div>
        </div>

        <!-- 본문 -->
        <div class="p-5">
          <h2 class="text-lg font-bold mb-3">{selectedArticle.title}</h2>
          <div class="markdown-body mb-4">
            {@html renderMd(selectedArticle.extracted_text || '')}
          </div>

          <!-- 본문 입력 -->
          {#if noteEditing}
            <div class="mt-4 border-t border-[var(--border)] pt-4">
              <h4 class="text-xs font-semibold text-[var(--text-dim)] mb-2">본문 / 메모 입력</h4>
              <textarea
                bind:value={noteText}
                class="w-full h-32 px-3 py-2 bg-[var(--bg)] border border-[var(--border)] rounded-lg text-sm text-[var(--text)] resize-y outline-none focus:border-[var(--accent)]"
                placeholder="기사 본문이나 메모를 입력하세요..."
              ></textarea>
              <div class="flex gap-2 mt-2">
                <button onclick={saveNote} class="px-3 py-1 text-xs bg-[var(--accent)] text-white rounded">저장</button>
                <button onclick={() => noteEditing = false} class="px-3 py-1 text-xs text-[var(--text-dim)]">취소</button>
              </div>
            </div>
          {:else}
            <button
              onclick={() => { noteText = selectedArticle.user_note || ''; noteEditing = true; }}
              class="mt-4 text-xs text-[var(--text-dim)] hover:text-[var(--accent)]"
            >+ 본문/메모 입력</button>
            {#if selectedArticle.user_note}
              <div class="mt-2 p-3 bg-[var(--bg)] rounded-lg text-sm">
                {selectedArticle.user_note}
              </div>
            {/if}
          {/if}
        </div>
      </div>
    {/if}
  </div>
</div>
