<template>
  <section class="page-card" v-if="!loading && product">
    <div class="flex flex-col gap-[18px]">
      <!-- Summary -->
      <div class="flex flex-col gap-2">
        <h2>{{ product.name }}</h2>
        <p class="tag">库存：{{ stockLabel(product) }}</p>
        <p class="tag">浏览量：{{ product.viewCount || 0 }}</p>
        <p class="font-semibold text-accent2">
          <span v-if="isFree" class="text-[#3a9a68] font-black">免费</span>
          <span v-else-if="product.discountPrice > 0 && product.discountPrice < product.price">
            <span class="line-through text-muted mr-1.5 text-[15px]">¥ {{ product.price.toFixed(2) }}</span>
            <span class="font-semibold">¥ {{ product.discountPrice.toFixed(2) }}</span>
          </span>
          <span v-else>¥ {{ product.price.toFixed(2) }}</span>
        </p>
      </div>

      <!-- Description (full markdown, not clamped) -->
      <div
        class="block text-apptext text-[17px] leading-[1.8] [display:block] [overflow:visible] [-webkit-box-orient:unset] [-webkit-line-clamp:unset] markdown"
        v-html="renderMarkdown(product.description)"
      ></div>

      <!-- Gallery -->
      <div v-if="galleryImages.length" class="flex flex-col gap-3.5">
        <div class="relative overflow-hidden rounded-[10px] border border-white/35 bg-white/45">
          <button
            v-if="galleryImages.length > 1"
            class="absolute left-4 top-1/2 -translate-y-1/2 z-[1] w-[42px] h-[42px] rounded-full p-0 bg-white/88 text-apptext text-[28px] leading-none shadow-[0_10px_20px_rgba(33,33,40,0.12)]"
            type="button"
            aria-label="上一张"
            @click="prevImage"
          >‹</button>
          <img
            class="w-full h-[360px] object-cover block max-md:h-60"
            :src="galleryImages[currentImageIndex].url"
            :alt="galleryImages[currentImageIndex].label"
          />
          <button
            v-if="galleryImages.length > 1"
            class="absolute right-4 top-1/2 -translate-y-1/2 z-[1] w-[42px] h-[42px] rounded-full p-0 bg-white/88 text-apptext text-[28px] leading-none shadow-[0_10px_20px_rgba(33,33,40,0.12)]"
            type="button"
            aria-label="下一张"
            @click="nextImage"
          >›</button>
        </div>

        <div class="flex items-center gap-2.5 flex-wrap">
          <span class="badge">{{ galleryImages[currentImageIndex].label }}</span>
          <span class="tag">{{ currentImageIndex + 1 }} / {{ galleryImages.length }}</span>
        </div>

        <div v-if="galleryImages.length > 1" class="grid gap-2.5" style="grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));">
          <button
            v-for="(image, index) in galleryImages"
            :key="`${image.url}-${index}`"
            class="flex flex-col gap-2 p-2 text-left bg-white/58 border transition max-md:p-1.5"
            :class="index === currentImageIndex ? 'border-accent2 shadow-[0_10px_24px_rgba(145,168,208,0.16)]' : 'border-transparent'"
            type="button"
            @click="currentImageIndex = index"
          >
            <img :src="image.url" :alt="image.label" class="w-full h-[76px] object-cover rounded-md" />
            <span class="text-sm text-muted">{{ image.label }}</span>
          </button>
        </div>
      </div>

      <!-- Actions -->
      <div class="flex gap-3 mt-[18px] flex-wrap">
        <button class="buy-button" @click="goCheckout">立即下单</button>
        <button
          v-if="loggedIn"
          class="ghost"
          :class="inWishlist ? 'text-[#e8826a] border-[rgba(232,130,106,0.35)] bg-[rgba(255,240,235,0.6)]' : 'text-muted'"
          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 mt-2">请返回商店查看其他商品。</p>
    <div class="flex gap-3 mt-[18px]">
      <button class="ghost" @click="goBack">返回商店首页</button>
    </div>
  </section>

  <section class="page-card" v-else>
    <div class="py-6 text-muted">加载中...</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 { stockLabel } from '../shared/fulfillment'
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>
