<script setup lang="ts">
import type { CategoryNode } from './CategoryTreeNode.vue'
import { getTypeLabel, type CardType } from '~/config/cardTypes'
import { request } from '~/utils/http/factory'
import { marked } from 'marked'

export interface CardDetail {
  id: number
  type: CardType
  image?: string
  images?: string[]
  title: string
  description?: string
  content?: string | null
  tags?: string[]
  aspectRatio: number
  categoryId?: string | null
  createdAt?: string
  articles?: { id: number; title: string }[]
}

const props = withDefaults(defineProps<{
  card: CardDetail | null
  visible: boolean
  categories: CategoryNode[]
  size?: 'default' | 'expanded'
}>(), {
  size: 'default',
})

const dialogStyle = computed(() => {
  if (props.size === 'expanded') {
    return { width: '90vw', maxWidth: '1400px' }
  }
  return { width: '85vw', maxWidth: '1200px' }
})

const emit = defineEmits<{
  'update:visible': [v: boolean]
  'favorite-toggled': [cardId: number, favorited: boolean]
}>()

const { isFavorited, toggle, loadingIds } = useFavorite()

// ── Fetch full card data for articles ──

const fetchedArticles = ref<{ id: number; title: string }[]>([])

async function fetchCardDetail(cardId: number) {
  try {
    const raw = await request<{
      code: number
      data: { articles?: { id: number; title: string }[] }
    }>(`/api/cards/${cardId}`)
    fetchedArticles.value = raw.data?.articles ?? []
  } catch {
    fetchedArticles.value = []
  }
}

watch(
  () => props.card?.id,
  (id) => {
    if (id && props.visible) {
      fetchedArticles.value = []
      fetchCardDetail(id)
    }
  },
)

watch(
  () => props.visible,
  (v) => {
    if (v && props.card?.id) {
      fetchedArticles.value = []
      fetchCardDetail(props.card.id)
    }
  },
)

async function handleToggle(cardId: number) {
  const result = await toggle(cardId)
  emit('favorite-toggled', cardId, result)
}

const categoryName = computed(() => {
  if (!props.card?.categoryId) return null
  function find(nodes: CategoryNode[]): string | null {
    for (const n of nodes) {
      if (n.id === props.card!.categoryId) return n.name
      if (n.children) {
        const r = find(n.children)
        if (r) return r
      }
    }
    return null
  }
  return find(props.categories)
})

const contentHtml = computed(() => {
  if (!props.card?.content) return ''
  return marked(props.card.content, { breaks: true }) as string
})

const typeLabel = computed(() => getTypeLabel(props.card?.type ?? ''))

const imageCount = computed(() => props.card?.images?.length ?? (props.card?.image ? 1 : 0))

const activeImageIdx = ref(0)

watch(() => props.visible, () => { activeImageIdx.value = 0 })

function formatDate(d?: string) {
  if (!d) return ''
  return new Date(d).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}
</script>

<template>
  <BoDialog
    :show="visible"
    :mask-can-close="true"
    :style="dialogStyle"
    @update:show="(v: boolean) => emit('update:visible', v)"
  >
    <div v-if="card" class="detail" :class="{ 'detail--expanded': size === 'expanded' }">
      <!-- ═══ 左栏：图片 ═══ -->
      <div class="detail-image-col">
        <button type="button" class="detail-close" @click="emit('update:visible', false)">
          <Icon name="lucide:x" />
        </button>

        <div v-if="card.images && card.images.length > 0" class="detail-image-area">
          <img
            :src="card.images[activeImageIdx]"
            :alt="`${card.title} - ${activeImageIdx + 1}`"
            class="detail-image"
          >
          <div v-if="card.images.length > 1" class="detail-image-nav">
            <button
              v-for="(url, i) in card.images"
              :key="i"
              type="button"
              class="detail-dot"
              :class="{ active: i === activeImageIdx }"
              @click="activeImageIdx = i"
            />
          </div>
          <span class="detail-image-count">{{ activeImageIdx + 1 }} / {{ card.images.length }}</span>
        </div>
        <div v-else-if="card.image" class="detail-image-area">
          <img :src="card.image" :alt="card.title" class="detail-image">
        </div>
        <div v-else class="detail-image-placeholder">
          <Icon name="lucide:file-text" class="placeholder-icon" />
          <span>{{ typeLabel }}</span>
        </div>
      </div>

      <!-- ═══ 右栏：信息 ═══ -->
      <div class="detail-content-col">
        <div class="detail-meta-row">
          <span class="detail-type">{{ typeLabel }}</span>
          <span v-if="categoryName" class="detail-category">{{ categoryName }}</span>
          <span v-if="card.createdAt" class="detail-date">{{ formatDate(card.createdAt) }}</span>
        </div>

        <div class="detail-title-row">
          <h2 class="detail-title">{{ card.title }}</h2>
          <button
            type="button"
            class="detail-fav-btn"
            :class="{ favorited: isFavorited(card.id), loading: loadingIds.has(card.id) }"
            :disabled="loadingIds.has(card.id)"
            @click="handleToggle(card.id)"
          >
            <Icon :name="isFavorited(card.id) ? 'ph:star-fill' : 'ph:star'" />
          </button>
        </div>

        <p v-if="card.description" class="detail-desc">{{ card.description }}</p>

        <div v-if="card.content" class="detail-content">
          <div class="detail-section-label">正文</div>
          <div class="detail-content-body" v-html="contentHtml" />
        </div>

        <div v-if="card.tags && card.tags.length > 0" class="detail-tags">
          <span v-for="tag in card.tags" :key="tag" class="detail-tag">{{ tag }}</span>
        </div>

        <div v-if="card.aspectRatio" class="detail-meta-item">
          <span class="detail-section-label">宽高比</span>
          <span>{{ card.aspectRatio }}</span>
        </div>

        <div v-if="fetchedArticles.length > 0" class="detail-articles">
          <span class="detail-articles-label">关联文章</span>
          <div class="detail-articles-list">
            <NuxtLink
              v-for="a in fetchedArticles"
              :key="a.id"
              :to="`/articles/${a.id}`"
              class="detail-article-link"
            >
              {{ a.title }}
            </NuxtLink>
          </div>
        </div>
      </div>
    </div>
  </BoDialog>
</template>

<style scoped>
.detail {
  display: flex;
  flex-direction: row;
  max-height: 85vh;
  background: var(--color-canvas, #faf9f5);
  border-radius: 16px;
  overflow: hidden;
  position: relative;
}

/* ── Left: Image column ── */

.detail-image-col {
  position: relative;
  flex: 0 0 42%;
  min-width: 0;
  background: var(--color-surface-card);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.detail-image-area {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.detail-image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--color-muted-soft);
  font-size: 14px;
  font-weight: 500;
}

.placeholder-icon {
  width: 48px;
  height: 48px;
  opacity: 0.4;
}

/* ── Close ── */

.detail-close {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 2;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: rgba(20, 20, 19, 0.4);
  backdrop-filter: blur(8px);
  border-radius: 50%;
  color: #fff;
  cursor: pointer;
  transition: background 0.15s ease;
}

.detail-close :deep(svg) { width: 18px; height: 18px; }
.detail-close:hover { background: rgba(20, 20, 19, 0.65); }

/* ── Image nav dots ── */

.detail-image-nav {
  position: absolute;
  bottom: 12px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 6px;
}

.detail-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  border: none;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  padding: 0;
  transition: background 0.15s ease;
}

.detail-dot.active {
  background: #fff;
}

.detail-image-count {
  position: absolute;
  bottom: 12px;
  right: 14px;
  font-size: 12px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
  background: rgba(20, 20, 19, 0.4);
  backdrop-filter: blur(6px);
  padding: 3px 10px;
  border-radius: 9999px;
}

/* ── Right: Content column ── */

.detail-content-col {
  flex: 1;
  min-width: 0;
  overflow-y: auto;
  padding: 24px 28px 28px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-meta-row {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.detail-type {
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 1px;
  text-transform: uppercase;
  padding: 3px 10px;
  border-radius: 9999px;
  background: var(--color-primary);
  color: var(--color-on-primary, #fff);
}

.detail-category {
  font-size: 12px;
  color: var(--color-muted);
}

.detail-date {
  font-size: 12px;
  color: var(--color-muted-soft);
  margin-left: auto;
}

.detail-title-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.detail-fav-btn {
  flex-shrink: 0;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: var(--color-muted-soft);
  cursor: pointer;
  transition: all 0.15s ease;
  margin-top: 2px;
}

.detail-fav-btn :deep(svg) { width: 18px; height: 18px; }
.detail-fav-btn:hover {
  color: var(--color-accent-amber);
  background: rgba(232, 165, 90, 0.1);
}
.detail-fav-btn.favorited { color: var(--color-accent-amber); }
.detail-fav-btn.loading { opacity: 0.5; pointer-events: none; }

.detail-title {
  flex: 1;
  font-family: var(--font-display);
  font-size: 24px;
  font-weight: 400;
  color: var(--color-ink);
  line-height: 1.2;
  margin: 0;
  letter-spacing: -0.3px;
}

.detail-desc {
  font-size: 14px;
  line-height: 1.7;
  color: var(--color-body);
  margin: 0;
  white-space: pre-wrap;
}

/* ── Content / Body ── */

.detail-content {
  padding-top: 4px;
}

.detail-section-label {
  font-size: 11px;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 6px;
}

.detail-content-body {
  font-size: 14px;
  line-height: 1.9;
  color: var(--color-body);
  word-break: break-word;
}

.detail-content-body :deep(h1),
.detail-content-body :deep(h2),
.detail-content-body :deep(h3) {
  font-family: var(--font-display);
  color: var(--color-ink);
  margin: 1.2em 0 0.4em;
  line-height: 1.3;
}
.detail-content-body :deep(h1) { font-size: 1.4em; }
.detail-content-body :deep(h2) { font-size: 1.2em; }
.detail-content-body :deep(h3) { font-size: 1.05em; }
.detail-content-body :deep(h1:first-child),
.detail-content-body :deep(h2:first-child),
.detail-content-body :deep(h3:first-child) { margin-top: 0; }

.detail-content-body :deep(p) { margin: 0.5em 0; }
.detail-content-body :deep(ul),
.detail-content-body :deep(ol) { padding-left: 1.2em; margin: 0.4em 0; }
.detail-content-body :deep(li) { margin: 0.2em 0; }
.detail-content-body :deep(code) {
  font-size: 0.9em;
  background: var(--color-surface-soft);
  padding: 1px 5px;
  border-radius: 4px;
}
.detail-content-body :deep(pre) {
  background: var(--color-surface-soft);
  padding: 12px 14px;
  border-radius: 8px;
  overflow-x: auto;
  font-size: 0.85em;
  line-height: 1.6;
}
.detail-content-body :deep(pre code) {
  background: none;
  padding: 0;
}
.detail-content-body :deep(blockquote) {
  border-left: 3px solid var(--color-primary);
  margin: 0.5em 0;
  padding-left: 12px;
  color: var(--color-muted);
}
.detail-content-body :deep(a) {
  color: var(--color-primary);
  text-decoration: underline;
}
.detail-content-body :deep(img) {
  max-width: 100%;
  border-radius: 8px;
  margin: 0.5em 0;
}
.detail-content-body :deep(hr) {
  border: none;
  border-top: 1px solid var(--color-hairline);
  margin: 1em 0;
}

.detail-meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--color-body);
}

/* ── Tags ── */

.detail-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding-top: 4px;
}

.detail-tag {
  font-size: 12px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 9999px;
  background: var(--color-surface-soft);
  color: var(--color-body);
  border: 1px solid var(--color-hairline);
}

/* ── Articles ── */

.detail-articles {
  padding-top: 8px;
  border-top: 1px solid var(--color-hairline);
}

.detail-articles-label {
  font-size: 11px;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 6px;
  display: block;
}

.detail-articles-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.detail-article-link {
  font-size: 13px;
  padding: 3px 10px;
  border-radius: 6px;
  background: #e8f4f0;
  color: #2d6a4f;
  text-decoration: none;
  transition: background 0.15s;
}

.detail-article-link:hover {
  background: #d0ece4;
}

/* ── Responsive ── */

@media (max-width: 767.98px) {
  .detail {
    flex-direction: column;
    max-height: 92vh;
  }

  .detail-image-col {
    flex: 0 0 auto;
    max-height: 40vh;
  }

  .detail-content-col {
    padding: 20px 16px 24px;
  }

  .detail-title {
    font-size: 20px;
  }
}
</style>
