<script>
  import { goto } from '$app/navigation';
  import FormatIcon from './FormatIcon.svelte';
  import TagPill from './TagPill.svelte';

  let {
    doc,
    showDomain = true,
    selected = false,
    onselect = null,
    // D.3 다중 선택
    selectable = false,
    selectedIds = new Set(),
    onselectionchange = null,
  } = $props();

  let isChecked = $derived(selectedIds.has(doc.id));

  function toggleSelection(e) {
    e?.stopPropagation?.();
    const next = new Set(selectedIds);
    if (next.has(doc.id)) next.delete(doc.id);
    else next.add(doc.id);
    onselectionchange?.(next);
  }

  function formatDate(dateStr) {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    const now = new Date();
    const diff = now - d;
    if (diff < 86400000) return '오늘';
    if (diff < 172800000) return '어제';
    if (diff < 604800000) return `${Math.floor(diff / 86400000)}일 전`;
    return d.toLocaleDateString('ko-KR', { month: 'short', day: 'numeric' });
  }

  function formatSize(bytes) {
    if (!bytes) return '';
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)}KB`;
    return `${(bytes / 1048576).toFixed(1)}MB`;
  }

  const DOMAIN_COLORS = {
    'Knowledge/Philosophy': 'var(--domain-philosophy)',
    'Knowledge/Language': 'var(--domain-language)',
    'Knowledge/Engineering': 'var(--domain-engineering)',
    'Knowledge/Industrial_Safety': 'var(--domain-safety)',
    'Knowledge/Programming': 'var(--domain-programming)',
    'Knowledge/General': 'var(--domain-general)',
    'Reference': 'var(--domain-reference)',
  };

  let domainColor = $derived(DOMAIN_COLORS[doc.ai_domain] || 'var(--border)');

  // 반응형: CSS media query matchMedia 사용
  let isDesktop = $state(typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : true);
  if (typeof window !== 'undefined') {
    window.matchMedia('(min-width: 1024px)').addEventListener('change', (e) => isDesktop = e.matches);
  }

  function handleClick() {
    if (!isDesktop) {
      goto(`/documents/${doc.id}`);
      return;
    }
    if (onselect) {
      onselect(doc);
    } else {
      goto(`/documents/${doc.id}`);
    }
  }
</script>

<div
  class="relative flex items-stretch bg-surface border rounded-lg hover:border-accent transition-colors group overflow-hidden
    {selected ? 'border-accent bg-accent/5' : 'border-default'}
    {isChecked ? 'border-accent bg-accent/10' : ''}"
>
  {#if selectable}
    <span
      class="absolute top-2 left-2 z-10 flex items-center justify-center transition-opacity
        {isChecked ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}"
    >
      <input
        type="checkbox"
        checked={isChecked}
        onchange={toggleSelection}
        onclick={(e) => e.stopPropagation()}
        class="h-4 w-4 accent-accent cursor-pointer"
        aria-label="{doc.title || '문서'} 선택"
      />
    </span>
  {/if}

  <button
    type="button"
    onclick={handleClick}
    aria-label={doc.title || '문서 선택'}
    class="flex items-stretch w-full min-w-0 text-left"
  >
  <!-- domain 색상 바 -->
  <div class="w-1 shrink-0 rounded-l-lg" style="background: {domainColor}"></div>

  <!-- 콘텐츠 -->
  <div class="flex items-start gap-2 p-2 sm:gap-3 sm:p-3 flex-1 min-w-0 {selectable ? 'pl-8' : ''}">
  <!-- 포맷 아이콘 -->
  <div class="shrink-0 mt-0.5 text-dim group-hover:text-accent">
    <FormatIcon format={doc.file_format} size={18} />
  </div>

  <!-- 메인 콘텐츠 -->
  <div class="flex-1 min-w-0">
    <p class="text-sm font-medium truncate group-hover:text-accent">
      {doc.title || '제목 없음'}
    </p>
    {#if doc.ai_summary}
      <p class="text-xs text-dim truncate mt-0.5">{doc.ai_summary.replace(/[*#_`~]/g, '').slice(0, 100)}</p>
    {/if}
    <div class="flex items-center gap-2 mt-1.5 flex-wrap">
      {#if showDomain && doc.ai_domain}
        <span class="text-[10px] text-dim">
          {doc.ai_domain.replace('Knowledge/', '')}{doc.ai_sub_group ? ` / ${doc.ai_sub_group}` : ''}
        </span>
      {/if}
      {#if doc.ai_tags?.length}
        <div class="flex gap-1">
          {#each doc.ai_tags.slice(0, isDesktop ? 3 : 1) as tag}
            <TagPill {tag} />
          {/each}
        </div>
      {/if}
    </div>
  </div>

  <!-- 우측 메타 -->
  <div class="shrink-0 flex flex-col items-end gap-1 text-[10px]">
    {#if doc.source_channel === 'news' && doc.edit_url}
      <span class="text-blue-400">📰</span>
    {/if}
    {#if doc.score !== undefined}
      <span class="text-accent font-medium">{(doc.score * 100).toFixed(0)}%</span>
    {/if}
    {#if doc.category === 'library'}
      {#if (doc.read_count ?? 0) === 0}
        <span class="px-1.5 py-0.5 rounded text-dim border border-default/40">안 봄</span>
      {:else if doc.read_count === 1}
        <span class="px-1.5 py-0.5 rounded text-text border border-default/40">1회독</span>
      {:else if doc.read_count === 2}
        <span class="px-1.5 py-0.5 rounded text-text border border-default/40">2회독</span>
      {:else}
        <span class="px-1.5 py-0.5 rounded text-text border border-default/40">{doc.read_count}회독</span>
      {/if}
    {/if}
    {#if doc.doc_purpose}
      <span class="hidden sm:inline px-1.5 py-0.5 rounded {doc.doc_purpose === 'business' ? 'bg-blue-900/30 text-blue-400' : 'bg-emerald-900/30 text-emerald-400'}">
        {doc.doc_purpose === 'business' ? '업무' : '참조'}
      </span>
    {:else if doc.data_origin}
      <span class="hidden sm:inline px-1.5 py-0.5 rounded {doc.data_origin === 'work' ? 'bg-blue-900/30 text-blue-400' : 'bg-gray-800 text-gray-400'}">
        {doc.data_origin}
      </span>
    {/if}
    <span class="text-dim">{formatDate(doc.created_at)}</span>
    {#if doc.file_size}
      <span class="text-dim">{formatSize(doc.file_size)}</span>
    {/if}
  </div>
  </div>
  </button>
</div>
