<template>
  <div
    class="block no-underline text-inherit h-full"
    :class="isSoldOut ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'"
    @click="$emit('click', item)"
  >
    <article class="product-card flex flex-col flex-1 gap-3 h-full bg-white/72 border border-white/35 rounded-xl p-4 shadow-[0_8px_22px_rgba(33,33,40,0.08)] max-md:gap-2.5 max-md:rounded-lg max-md:p-3">
      <div class="relative rounded-lg overflow-hidden h-[168px] sm:h-[188px] md:h-[208px] max-md:h-[128px] max-md:rounded-md">
        <img
          :src="item.coverUrl"
          :alt="item.name"
          class="w-full h-full object-cover block"
        />
        <div
          v-if="isSoldOut"
          class="absolute inset-0 flex items-center justify-center bg-[rgba(20,18,22,0.52)] backdrop-blur-sm text-white text-[17px] font-semibold tracking-[3px] pointer-events-none"
          style="font-family: var(--font-serif);"
        >已售空</div>
        <div
          v-else-if="item.requireLogin"
          class="absolute top-1.5 right-1.5 px-2 py-0.5 rounded-full bg-accent/85 text-white text-[11px] font-bold pointer-events-none backdrop-blur-sm"
        >需登录</div>
        <button
          v-if="loggedIn"
          class="absolute bottom-1.5 right-1.5 p-0 w-auto h-auto border-none bg-transparent shadow-none text-lg leading-none text-white/90 [text-shadow:0_1px_4px_rgba(0,0,0,0.5)] transition-transform hover:scale-125"
          :class="inWishlist ? 'text-[#ffb347] [text-shadow:0_1px_6px_rgba(255,140,0,0.6)]' : ''"
          type="button"
          @click="onWishlistClick"
          :title="inWishlist ? '取消收藏' : '加入收藏'"
        >{{ inWishlist ? '★' : '☆' }}</button>
      </div>

      <div class="flex items-start justify-between gap-2 min-h-0">
        <h3 class="text-[17px] sm:text-[18px] font-bold text-apptext leading-tight line-clamp-2 flex-1 min-w-0 max-md:text-[14px]">{{ item.name }}</h3>
        <div class="flex items-center justify-end shrink-0 text-[16px] max-md:text-[13px]">
          <span v-if="isFree" class="text-[#3a9a68] font-black whitespace-nowrap">免费</span>
          <span v-else-if="item.discountPrice > 0 && item.discountPrice < item.price" class="text-accent2 font-semibold whitespace-nowrap text-right">
            <span class="line-through text-muted mr-1 text-[12px] max-md:text-[10px]">¥{{ item.price.toFixed(2) }}</span>
            ¥{{ item.discountPrice.toFixed(2) }}
          </span>
          <span v-else class="text-accent2 font-semibold whitespace-nowrap">¥{{ item.price.toFixed(2) }}</span>
        </div>
      </div>

      <p
        class="product-card-description text-left text-[14px] text-muted leading-snug max-md:text-[12px]"
        :title="descriptionText"
      >{{ descriptionText || '暂无商品介绍' }}</p>

      <div class="mt-auto flex flex-col gap-1.5 pt-0.5 border-t border-white/20">
        <div v-if="item.tags && item.tags.length" class="flex flex-wrap gap-1">
          <span
            v-for="tag in item.tags"
            :key="tag"
            class="px-1.5 py-0.5 rounded-full text-[11px] font-semibold text-accent2 bg-[rgba(217,168,120,0.12)] border border-[rgba(184,109,92,0.22)] max-md:text-[10px]"
          >{{ tag }}</span>
        </div>
        <p class="text-[13px] text-muted m-0 max-md:text-[10px]">
          库存 {{ stockLabel(item) }}<span class="text-muted/70"> · </span>已售 {{ totalSoldDisplay }}<span class="text-muted/70"> · </span>浏览 {{ item.viewCount || 0 }}
        </p>
      </div>
    </article>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import MarkdownIt from 'markdown-it'
import { isLoggedIn } from '../../shared/auth'
import { isSoldOutProduct, stockLabel } from '../../shared/fulfillment'
import { isInWishlist, toggleWishlist } from '../../shared/useWishlist'

const md = new MarkdownIt()

const props = defineProps({
  item: { type: Object, required: true }
})

defineEmits(['click'])

const inWishlist = computed(() => isInWishlist(props.item.id))
const loggedIn = computed(() => isLoggedIn())

const onWishlistClick = (e) => {
  e.stopPropagation()
  toggleWishlist(props.item.id)
}

const payPrice = computed(() => {
  if (!props.item) return 0
  if (props.item.price === 0) return 0
  if (props.item.discountPrice > 0 && props.item.discountPrice < props.item.price) {
    return props.item.discountPrice
  }
  return props.item.price
})

const isFree = computed(() => payPrice.value === 0)
const isSoldOut = computed(() => isSoldOutProduct(props.item))
const totalSoldDisplay = computed(() => {
  const n = props.item?.totalSold
  return typeof n === 'number' && !Number.isNaN(n) ? n : 0
})

const descriptionText = computed(() => {
  const html = md.render(props.item.description || '')
  return html
    .replace(/<[^>]*>/g, ' ')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/\s+/g, ' ')
    .trim()
})
</script>
