<template>
  <section class="page-card" v-if="!loading && product">
    <div class="detail-body">
      <div class="detail-summary">
        <h2>{{ product.name }}</h2>
        <p class="tag">库存：{{ product.quantity }}</p>
        <p class="tag">浏览量：{{ product.viewCount || 0 }}</p>
        <p class="product-price">
          <span v-if="isFree" class="free-price">免费</span>
          <span
            v-else-if="product.discountPrice > 0 && product.discountPrice < product.price"
          >
            <span class="price-original">¥ {{ product.price.toFixed(2) }}</span>
            <span class="price-discount">¥ {{ product.discountPrice.toFixed(2) }}</span>
          </span>
          <span v-else>¥ {{ product.price.toFixed(2) }}</span>
        </p>
      </div>

      <div class="markdown detail-description" v-html="renderMarkdown(product.description)"></div>

      <div class="detail-gallery" v-if="galleryImages.length">
        <div class="detail-gallery-main">
          <button
            v-if="galleryImages.length > 1"
            class="gallery-nav prev"
            type="button"
            aria-label="上一张"
            @click="prevImage"
          >
            ‹
          </button>
          <img
            class="detail-image"
            :src="galleryImages[currentImageIndex].url"
            :alt="galleryImages[currentImageIndex].label"
          />
          <button
            v-if="galleryImages.length > 1"
            class="gallery-nav next"
            type="button"
            aria-label="下一张"
            @click="nextImage"
          >
            ›
          </button>
        </div>

        <div class="detail-gallery-meta">
          <span class="badge">{{ galleryImages[currentImageIndex].label }}</span>
          <span class="tag">{{ currentImageIndex + 1 }} / {{ galleryImages.length }}</span>
        </div>

        <div class="detail-thumbs" v-if="galleryImages.length > 1">
          <button
            v-for="(image, index) in galleryImages"
            :key="`${image.url}-${index}`"
            class="detail-thumb"
            :class="{ active: index === currentImageIndex }"
            type="button"
            @click="currentImageIndex = index"
          >
            <img :src="image.url" :alt="image.label" />
            <span>{{ image.label }}</span>
          </button>
        </div>
      </div>

      <div class="detail-actions">
        <button class="buy-button" @click="goCheckout">立即下单</button>
        <button
          v-if="loggedIn"
          class="ghost wishlist-action"
          :class="{ 'wishlist-active': inWishlist }"
          type="button"
          @click="onToggleWishlist"
        >
          {{ inWishlist ? '★ 已收藏' : '☆ 加入收藏夹' }}
        </button>
        <button class="ghost" @click="goBack">返回商店首页</button>
      </div>
    </div>
  </section>

  <section class="page-card" v-else-if="!loading && !product">
    <h2>未找到该商品</h2>
    <p class="tag">请返回商店查看其他商品。</p>
    <div class="detail-actions">
      <button class="ghost" @click="goBack">返回商店首页</button>
    </div>
  </section>

  <section class="page-card" v-else>
    <div class="status">加载中...</div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { fetchProducts, recordProductView } from '../shared/api'
import { isLoggedIn } from '../shared/auth'
import { isInWishlist, toggleWishlist } from '../shared/useWishlist'

const route = useRoute()
const router = useRouter()
const md = new MarkdownIt()
const loading = ref(true)
const product = ref(null)
const currentImageIndex = ref(0)

const getPayPrice = (p) => {
  if (!p) return 0
  if (p.price === 0) return 0
  if (p.discountPrice > 0 && p.discountPrice < p.price) return p.discountPrice
  return p.price
}

const unitPrice = computed(() => getPayPrice(product.value))
const isFree = computed(() => unitPrice.value === 0)

const renderMarkdown = (content) => md.render(content || '')

const galleryImages = computed(() => {
  if (!product.value) {
    return []
  }

  const images = []
  const seen = new Set()
  const appendImage = (url, label) => {
    const trimmed = (url || '').trim()
    if (!trimmed || seen.has(trimmed)) {
      return
    }
    seen.add(trimmed)
    images.push({ url: trimmed, label })
  }

  appendImage(product.value.coverUrl, '商品封面')

  const screenshots = Array.isArray(product.value.screenshotUrls)
    ? product.value.screenshotUrls
    : []

  screenshots.forEach((url, index) => {
    appendImage(url, `商品截图 ${index + 1}`)
  })

  return images
})

const loggedIn = computed(() => isLoggedIn())
const inWishlist = computed(() => product.value ? isInWishlist(product.value.id) : false)
const onToggleWishlist = () => {
  if (product.value) toggleWishlist(product.value.id)
}

const goBack = () => {
  router.push('/')
}

const goCheckout = () => {
  if (!product.value) {
    return
  }
  router.push(`/checkout/${product.value.id}`)
}

const prevImage = () => {
  if (!galleryImages.value.length) {
    return
  }
  currentImageIndex.value =
    (currentImageIndex.value - 1 + galleryImages.value.length) % galleryImages.value.length
}

const nextImage = () => {
  if (!galleryImages.value.length) {
    return
  }
  currentImageIndex.value = (currentImageIndex.value + 1) % galleryImages.value.length
}

watch(
  galleryImages,
  (images) => {
    if (!images.length || currentImageIndex.value >= images.length) {
      currentImageIndex.value = 0
    }
  },
  { immediate: true }
)

onMounted(async () => {
  try {
    const list = await fetchProducts()
    product.value = list.find((item) => item.id === route.params.id) || null
    if (product.value) {
      try {
        const result = await recordProductView(product.value.id)
        if (typeof result.viewCount === 'number') {
          product.value = {
            ...product.value,
            viewCount: result.viewCount
          }
        }
      } catch (error) {
        console.warn('record product view failed', error)
      }
    }
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.detail-body {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.detail-summary {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-description {
  display: block;
  color: var(--text);
  font-size: 17px;
  line-height: 1.8;
  -webkit-line-clamp: initial;
  -webkit-box-orient: initial;
  overflow: visible;
}

.detail-gallery {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.detail-gallery-main {
  position: relative;
  overflow: hidden;
  border-radius: 10px;
  border: 1px solid var(--line);
  background: rgba(255, 255, 255, 0.45);
}

.gallery-nav {
  position: absolute;
  top: 50%;
  z-index: 1;
  width: 42px;
  height: 42px;
  border-radius: 999px;
  padding: 0;
  background: rgba(255, 255, 255, 0.88);
  color: var(--text);
  font-size: 28px;
  line-height: 1;
  transform: translateY(-50%);
  box-shadow: 0 10px 20px rgba(33, 33, 40, 0.12);
}

.gallery-nav.prev {
  left: 16px;
}

.gallery-nav.next {
  right: 16px;
}

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

.detail-thumbs {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 10px;
}

.detail-thumb {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
  text-align: left;
  background: rgba(255, 255, 255, 0.58);
  border: 1px solid transparent;
}

.detail-thumb.active {
  border-color: var(--accent-2);
  box-shadow: 0 10px 24px rgba(145, 168, 208, 0.16);
}

.detail-thumb img {
  width: 100%;
  height: 76px;
  object-fit: cover;
  border-radius: 6px;
}

.detail-thumb span {
  font-size: 14px;
  color: var(--muted);
}

.status {
  padding: 24px 0;
  color: var(--muted);
}

.free-price {
  color: #3a9a68;
  font-weight: 900;
}

.wishlist-action {
  color: var(--muted);
}

.wishlist-action.wishlist-active {
  color: #e8826a;
  border-color: rgba(232, 130, 106, 0.35);
  background: rgba(255, 240, 235, 0.6);
}

@media (max-width: 900px) {
  .detail-thumb {
    padding: 6px;
  }
}
</style>
