<template>
  <section class="page-card">
    <div class="hero">
      <h2>我的收藏夹</h2>
      <p class="tag">共 {{ wishlistItems.length }} 件商品</p>
    </div>

    <div v-if="loading" class="status">加载中...</div>

    <div v-else-if="wishlistItems.length === 0" class="empty">
      <div class="empty-icon">☆</div>
      <p class="empty-title">收藏夹是空的</p>
      <p class="tag">在商品卡片上点击 ☆ 即可加入收藏</p>
      <button class="ghost" @click="$router.push('/')">去逛逛</button>
    </div>

    <div v-else class="grid">
      <ProductCard
        v-for="item in wishlistItems"
        :key="item.id"
        :item="item"
        :class="{ 'card-dimmed': !item.active || item.quantity === 0 }"
        @click="handleClick"
      />
    </div>
  </section>
</template>

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

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

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

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

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

<style scoped>
.hero {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 20px;
}

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

.tag {
  font-size: 14px;
  color: var(--muted);
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 60px 0;
  text-align: center;
}

.empty-icon {
  font-size: 52px;
  color: var(--muted);
  opacity: 0.4;
  line-height: 1;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--text);
}

.card-dimmed {
  opacity: 0.5;
}
</style>
