<template>
  <section v-if="!loading && product">
    <div class="w-full max-w-[1180px] mx-auto">
      <div class="grid gap-4 lg:gap-6 lg:grid-cols-[minmax(0,1fr)_340px] items-start">
        <div class="min-w-0 flex flex-col gap-4 lg:gap-5">
          <div class="rounded-[16px] border border-white/40 bg-[rgba(255,252,248,0.46)] shadow-[0_18px_44px_rgba(42,28,22,0.08)] backdrop-blur-[16px] p-4 sm:p-5 lg:p-6">
            <div class="flex flex-col gap-4 sm:gap-5">
              <div class="flex items-start justify-between gap-3 sm:gap-4">
                <div class="min-w-0 flex-1">
                  <h3 class="text-[28px] leading-tight sm:text-[34px] lg:text-[38px] font-bold text-apptext">{{ product.name }}</h3>
                </div>

                <div class="lg:hidden shrink-0 rounded-[14px] border border-[rgba(184,109,92,0.18)] bg-[linear-gradient(160deg,rgba(255,252,248,0.95),rgba(248,232,223,0.78))] px-4 py-3 text-right shadow-[0_10px_24px_rgba(184,109,92,0.12)] min-w-[116px]">
                  <p class="text-[11px] tracking-[0.08em] text-muted mb-1">当前价格</p>
                  <p class="text-[28px] leading-none font-bold text-accent2">
                    <span v-if="isFree" class="text-[#3a9a68] font-black text-[24px]">免费</span>
                    <span v-else>¥ {{ unitPrice.toFixed(2) }}</span>
                  </p>
                  <p
                    v-if="hasDiscount"
                    class="text-[12px] text-muted line-through mt-2"
                  >原价 ¥ {{ product.price.toFixed(2) }}</p>
                </div>
              </div>


            </div>
          </div>

          <div v-if="galleryImages.length" class="rounded-[16px] border border-white/40 bg-[rgba(255,252,248,0.44)] shadow-[0_16px_38px_rgba(42,28,22,0.07)] backdrop-blur-[14px] p-4 sm:p-5 lg:p-6">
            <div class="flex items-center justify-between gap-3 mb-3 sm:mb-4">
              <div>
                <h3 class="text-[19px] sm:text-[21px] font-bold text-apptext">商品预览</h3>
              </div>
              <span class="shrink-0 rounded-full border border-white/45 bg-white/55 px-3 py-1 text-[12px] sm:text-[13px] font-semibold text-muted">
                {{ activeGalleryIndex + 1 }} / {{ galleryImages.length }}
              </span>
            </div>

            <div class="rounded-[15px] border border-white/35 bg-[linear-gradient(180deg,rgba(255,255,255,0.24),rgba(255,250,245,0.14))] p-3 sm:p-4">
              <div class="aspect-[4/3] sm:aspect-[16/10] rounded-[12px] border border-white/35 bg-[rgba(255,255,255,0.38)] overflow-hidden flex items-center justify-center">
                <img
                  :src="activeGalleryImage.url"
                  :alt="activeGalleryImage.label"
                  class="w-full h-full object-contain p-2 sm:p-3"
                  loading="lazy"
                />
              </div>
            </div>

            <div
              v-if="galleryImages.length > 1"
              class="mt-3 sm:mt-4 flex gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
            >
              <button
                v-for="(img, index) in galleryImages"
                :key="`${img.url}-${index}`"
                type="button"
                class="group shrink-0 w-[78px] sm:w-[92px] rounded-[12px] border bg-white/45 p-1.5 transition"
                :class="index === activeGalleryIndex ? 'border-accent2 shadow-[0_10px_20px_rgba(184,109,92,0.16)] bg-[rgba(255,247,242,0.82)]' : 'border-white/35 hover:border-accent2/35'"
                @click="activeGalleryIndex = index"
              >
                <div class="aspect-square rounded-[10px] overflow-hidden bg-white/60">
                  <img :src="img.url" :alt="img.label" class="w-full h-full object-cover" loading="lazy" />
                </div>
                <p class="text-[11px] text-muted mt-1 truncate">{{ img.label }}</p>
              </button>
            </div>

            <p class="text-[12px] sm:text-[13px] text-muted mt-3 text-center">{{ activeGalleryImage.label }}</p>
          </div>

          <div class="rounded-[16px] border border-white/40 bg-[rgba(255,252,248,0.46)] shadow-[0_16px_38px_rgba(42,28,22,0.07)] backdrop-blur-[14px] overflow-hidden">
            <div class="px-4 py-3 sm:px-5 sm:py-4 lg:px-6 border-b border-white/25 flex items-center justify-between gap-3">
              <div>
                <h3 class="text-[19px] sm:text-[21px] font-bold text-apptext">商品介绍</h3>
              </div>
            </div>

            <div class="px-4 pb-4 sm:px-5 sm:pb-5 lg:px-6 lg:pb-6 pt-4">
              <div class="relative">
                <div
                  class="markdown markdown-detail text-[14px] sm:text-[15px] leading-7 text-apptext max-w-none"
                  :class="descriptionExpanded ? '' : 'max-h-[220px] overflow-hidden'"
                  v-html="renderMarkdown(product.description)"
                />
                <div
                  v-if="showDescToggle && !descriptionExpanded"
                  class="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-[rgba(255,250,245,0.98)] to-transparent"
                ></div>
              </div>

              <div v-if="showDescToggle" class="mt-4">
                <button
                  type="button"
                  class="w-full sm:w-auto rounded-full border border-white/40 bg-white/55 px-4 py-2 text-[13px] sm:text-[14px] font-semibold text-accent2 hover:bg-white/75 transition"
                  @click="descriptionExpanded = !descriptionExpanded"
                >
                  {{ descriptionExpanded ? '收起介绍' : '展开完整介绍' }}
                </button>
              </div>
            </div>
          </div>

          <div class="lg:hidden rounded-[16px] border border-white/40 bg-[rgba(255,252,248,0.52)] shadow-[0_14px_34px_rgba(42,28,22,0.07)] backdrop-blur-[14px] p-4 sm:p-5">
            <div class="flex flex-col gap-2.5">
              <button class="buy-button w-full !py-3 text-[17px]" type="button" @click="goCheckout">立即下单</button>
              <button
                v-if="loggedIn"
                class="ghost w-full !py-3 !text-[15px]"
                :class="inWishlist ? 'text-[#e8826a] border-[rgba(232,130,106,0.35)] bg-[rgba(255,240,235,0.7)]' : 'text-muted'"
                type="button"
                @click="onToggleWishlist"
              >{{ inWishlist ? '★ 已收藏' : '☆ 加入收藏夹' }}</button>
              <button class="ghost w-full !py-3 !text-[15px]" type="button" @click="goBack">返回商店</button>
            </div>
          </div>
        </div>

        <aside class="hidden lg:flex flex-col gap-4 sticky top-[86px]">
          <div class="rounded-[18px] border border-[rgba(184,109,92,0.16)] bg-[linear-gradient(180deg,rgba(255,252,248,0.96),rgba(247,235,227,0.82))] shadow-[0_22px_48px_rgba(42,28,22,0.1)] backdrop-blur-[18px] p-5">
            <div v-if="coverMiniUrl" class="rounded-[14px] border border-white/45 bg-white/58 p-3 mb-4">
              <div class="aspect-[4/3] rounded-[12px] overflow-hidden bg-[rgba(255,255,255,0.62)] flex items-center justify-center">
                <img :src="coverMiniUrl" alt="封面" class="w-full h-full object-contain p-2" loading="lazy" />
              </div>
            </div>

            <p class="text-[38px] leading-none font-bold text-accent2">
              <span v-if="isFree" class="text-[#3a9a68] font-black text-[34px]">免费</span>
              <span v-else>¥ {{ unitPrice.toFixed(2) }}</span>
            </p>
            <p v-if="hasDiscount" class="text-[14px] text-muted line-through mt-3">原价 ¥ {{ product.price.toFixed(2) }}</p>

            <div class="grid grid-cols-1 gap-2 mt-5">
              <div class="rounded-xl border border-white/40 bg-white/45 px-3.5 py-3 flex items-center justify-between gap-3">
                <span class="text-[13px] text-muted">库存</span>
                <span class="text-[15px] font-semibold text-apptext">{{ stockLabel(product) }}</span>
              </div>
              <div class="rounded-xl border border-white/40 bg-white/45 px-3.5 py-3 flex items-center justify-between gap-3">
                <span class="text-[13px] text-muted">已售</span>
                <span class="text-[15px] font-semibold text-apptext">{{ totalSoldDisplay }}</span>
              </div>
              <div class="rounded-xl border border-white/40 bg-white/45 px-3.5 py-3 flex items-center justify-between gap-3">
                <span class="text-[13px] text-muted">浏览量</span>
                <span class="text-[15px] font-semibold text-apptext">{{ product.viewCount || 0 }}</span>
              </div>
            </div>

            <div class="flex flex-col gap-2.5 mt-5">
              <button class="buy-button w-full !py-3 text-[17px]" type="button" @click="goCheckout">立即下单</button>
              <button
                v-if="loggedIn"
                class="ghost w-full !py-3"
                :class="inWishlist ? 'text-[#e8826a] border-[rgba(232,130,106,0.35)] bg-[rgba(255,240,235,0.7)]' : 'text-muted'"
                type="button"
                @click="onToggleWishlist"
              >{{ inWishlist ? '★ 已收藏' : '☆ 加入收藏夹' }}</button>
              <button class="ghost w-full !py-3" type="button" @click="goBack">返回商店</button>
            </div>
          </div>

          <div class="rounded-[15px] border border-white/35 bg-[rgba(255,252,248,0.44)] shadow-[0_12px_30px_rgba(42,28,22,0.06)] backdrop-blur-[12px] p-4">
            <p class="text-[15px] font-semibold text-apptext">下单提示</p>
            <p class="text-[13px] text-muted leading-6 mt-2">
              下单后会进入订单页处理流程，数字商品通常会在短时间内完成交付。
            </p>
          </div>
        </aside>
      </div>
    </div>
  </section>

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

  <section v-else>
    <div class="py-4 text-muted text-[15px]">加载中...</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 activeGalleryIndex = ref(0)
const descriptionExpanded = ref(false)

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 hasDiscount = computed(() => {
  if (!product.value) return false
  return product.value.discountPrice > 0 && product.value.discountPrice < product.value.price
})
const totalSoldDisplay = computed(() => {
  const n = product.value?.totalSold
  return typeof n === 'number' && !Number.isNaN(n) ? n : 0
})
const renderMarkdown = (content) => md.render(content || '')

const showDescToggle = computed(() => {
  const t = product.value?.description || ''
  return t.replace(/\s/g, '').length > 120
})

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,) })
  return images
})

const activeGalleryImage = computed(() => {
  return galleryImages.value[activeGalleryIndex.value] || galleryImages.value[0] || { url: '', label: '' }
})

const coverMiniUrl = computed(() => {
  const c = (product.value?.coverUrl || '').trim()
  return c || galleryImages.value[0]?.url || ''
})

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

watch(() => product.value?.id, () => {
  descriptionExpanded.value = false
  activeGalleryIndex.value = 0
})

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}`)
}

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>
