<template>
  <div>
    <div class="flex items-baseline gap-3 mb-5">
      <h2>我的收藏夹</h2>
      <p class="tag">共 {{ wishlistItems.length }} 件商品</p>
    </div>

    <div v-if="loading" class="py-6 text-muted">加载中...</div>

    <div v-else-if="wishlistItems.length === 0" class="flex flex-col items-center gap-3 py-[60px] text-center">
      <div class="text-[52px] text-muted opacity-40 leading-none">☆</div>
      <p class="text-xl font-semibold text-apptext">收藏夹是空的</p>
      <p class="tag">在商品卡片上点击 ☆ 即可加入收藏</p>
      <button class="ghost" @click="$router.push('/')">去逛逛</button>
    </div>

    <div v-else class="product-grid">
      <ProductCard
        v-for="item in wishlistItems"
        :key="item.id"
        :item="item"
        :class="{ 'opacity-50': isUnavailable(item) }"
        @click="handleClick"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchProducts } from '../shared/api'
import { isSoldOutProduct } from '../shared/fulfillment'
import { getWishlistProducts, loadWishlist } from '../shared/useWishlist'
import ProductCard from '../store/components/ProductCard.vue'

const router = useRouter()
const allProducts = ref([])
const loading = ref(true)

const isUnavailable = (item) => !item.active || isSoldOutProduct(item)

const wishlistItems = computed(() => {
  const items = getWishlistProducts(allProducts.value)
  return items.sort((a, b) => {
    const aOk = a.active && !isSoldOutProduct(a) ? 0 : 1
    const bOk = b.active && !isSoldOutProduct(b) ? 0 : 1
    return aOk - bOk
  })
})

const handleClick = (item) => {
  if (!item || isUnavailable(item)) return
  router.push(`/product/${item.id}`)
}

onMounted(async () => {
  try {
    const [prods] = await Promise.all([fetchProducts(), loadWishlist()])
    allProducts.value = prods
  } finally {
    loading.value = false
  }
})
</script>
