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

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

const props = defineProps<{
  card: CardDetail | null
  visible: boolean
  categories: CategoryNode[]
}>()

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

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

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 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="{ width: '600px' }"
    @update:show="(v: boolean) => emit('update:visible', v)"
  >
    <div v-if="card" class="detail">
      <!-- Image area -->
      <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"
        >
        <button type="button" class="detail-close" @click="emit('update:visible', false)">
          <Icon name="lucide:x" />
        </button>
        <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">
        <button type="button" class="detail-close" @click="emit('update:visible', false)">
          <Icon name="lucide:x" />
        </button>
      </div>

      <!-- Content -->
      <div class="detail-body">
        <div v-if="!card.image && !(card.images && card.images.length > 0)" class="detail-top-row">
          <span />
          <button type="button" class="detail-close-inline" @click="emit('update:visible', false)">
            <Icon name="lucide:x" />
          </button>
        </div>
        <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.tags && card.tags.length > 0" class="detail-tags">
          <span v-for="tag in card.tags" :key="tag" class="detail-tag">{{ tag }}</span>
        </div>
      </div>
    </div>
  </BoDialog>
</template>

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

/* ── 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); }

.detail-close-inline {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: none;
  border-radius: 8px;
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.12s ease;
}

.detail-close-inline :deep(svg) { width: 18px; height: 18px; }
.detail-close-inline:hover { background: var(--color-surface-soft); color: var(--color-ink); }

.detail-top-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2px;
}

/* ── Image ── */

.detail-image-area {
  position: relative;
  background: var(--color-surface-card);
  min-height: 200px;
  max-height: 55vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.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;
}

/* ── Body ── */

.detail-body {
  padding: 24px 28px 28px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
}

.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: 26px;
  font-weight: 400;
  color: var(--color-ink);
  line-height: 1.2;
  margin: 0;
  letter-spacing: -0.3px;
}

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

.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);
}
</style>
