<template>
  <div>
    <!-- Hero / filters row -->
    <div class="flex items-end gap-3 flex-wrap mb-4 max-md:flex-col max-md:items-stretch max-md:gap-2 max-md:mb-3">
      <h2 class="text-lg md:text-xl font-bold shrink-0">所有商品</h2>
      <div class="flex gap-2 flex-wrap flex-1 min-w-0 max-md:flex-nowrap max-md:overflow-x-auto max-md:gap-1.5 max-md:w-full max-md:pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        <button
          v-for="opt in VIEW_OPTIONS"
          :key="opt.value"
          class="px-2.5 py-1 rounded-full border border-white/35 bg-white/60 text-apptext text-[13px] font-bold transition hover:-translate-y-px max-md:flex-shrink-0 max-md:px-2 max-md:py-1 max-md:text-[12px]"
          :class="opt.value === viewMode ? 'bg-gradient-to-br from-accent to-accent2 !border-transparent !text-white shadow-[0_6px_18px_rgba(184,109,92,0.28)]' : ''"
          type="button"
          @click="setViewMode(opt.value)"
        >
          {{ opt.label }}
        </button>
      </div>
      <input
        v-model="searchQuery"
        class="w-[240px] max-w-full shrink-0 rounded-full border border-white/35 bg-white/70 px-3 py-2 text-[14px] outline-none focus:border-accent focus:shadow-[0_0_0_3px_rgba(217,168,120,0.22)] transition max-md:w-full max-md:text-sm"
        style="font-family: var(--font-serif);"
        type="text"
        placeholder="搜索商品/标签"
      />
    </div>

    <div v-if="loading" class="py-6 text-muted">加载中...</div>
    <div v-else>
      <div class="product-grid">
        <ProductCard
          v-for="item in pagedProducts"
          :key="item.id"
          :item="item"
          @click="handleCardClick"
        />
      </div>

      <div v-if="totalPages > 1" class="flex items-center justify-center gap-2 mt-4 flex-wrap">
        <button class="ghost rounded-full px-3.5 py-1.5 text-sm min-w-[60px] disabled:opacity-40 disabled:cursor-not-allowed" :disabled="page === 1" @click="page = 1">首页</button>
        <button class="ghost rounded-full px-3.5 py-1.5 text-sm min-w-[60px] disabled:opacity-40 disabled:cursor-not-allowed" :disabled="page === 1" @click="page--">上一页</button>
        <span class="text-sm text-muted px-1.5">第 {{ page }} / {{ totalPages }} 页</span>
        <button class="ghost rounded-full px-3.5 py-1.5 text-sm min-w-[60px] disabled:opacity-40 disabled:cursor-not-allowed" :disabled="page === totalPages" @click="page++">下一页</button>
        <button class="ghost rounded-full px-3.5 py-1.5 text-sm min-w-[60px] disabled:opacity-40 disabled:cursor-not-allowed" :disabled="page === totalPages" @click="page = totalPages">末页</button>
      </div>
    </div>
  </div>
</template>

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

const router = useRouter()

const VIEW_OPTIONS = [
  { value: 'all', label: '全部' },
  { value: 'free', label: '免费' },
  { value: 'newest', label: '新上架' },
  { value: 'most-sold', label: '最多购买' },
  { value: 'most-viewed', label: '最多浏览' },
  { value: 'price-high', label: '价格最高' },
  { value: 'price-low', label: '价格最低' }
]

const products = ref([])
const loading = ref(true)
const page = ref(1)
const perPage = ref(20)
const viewMode = ref('all')
const searchQuery = ref('')

const updatePerPage = () => {
  perPage.value = window.innerWidth <= 900 ? 10 : 20
  page.value = 1
}

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

const isFree = (item) => getPayPrice(item) === 0
const isSoldOut = (item) => isSoldOutProduct(item)

const matchesSearch = (item) => {
  const q = (searchQuery.value || '').trim().toLowerCase()
  if (!q) return true
  const name = (item?.name || '').toLowerCase()
  const tags = (item?.tags || []).join(',').toLowerCase()
  return name.includes(q) || tags.includes(q)
}

const filteredProducts = computed(() => {
  let list = [...products.value]
  if (viewMode.value === 'free') list = list.filter((p) => isFree(p))
  if ((searchQuery.value || '').trim()) list = list.filter((p) => matchesSearch(p))
  switch (viewMode.value) {
    case 'newest':      list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); break
    case 'most-sold':   list.sort((a, b) => (b.totalSold || 0) - (a.totalSold || 0)); break
    case 'most-viewed': list.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0)); break
    case 'price-high':  list.sort((a, b) => getPayPrice(b) - getPayPrice(a)); break
    case 'price-low':   list.sort((a, b) => getPayPrice(a) - getPayPrice(b)); break
    default: break
  }
  return list
})

const totalPages = computed(() => Math.max(1, Math.ceil(filteredProducts.value.length / perPage.value)))
const pagedProducts = computed(() => {
  const start = (page.value - 1) * perPage.value
  return filteredProducts.value.slice(start, start + perPage.value)
})

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

const setViewMode = (next) => {
  viewMode.value = next
  page.value = 1
}

onMounted(async () => {
  updatePerPage()
  window.addEventListener('resize', updatePerPage)
  try {
    products.value = await fetchProducts()
  } finally {
    loading.value = false
  }
})

watch(viewMode, () => { page.value = 1 })
watch(searchQuery, () => { page.value = 1 })

onUnmounted(() => {
  window.removeEventListener('resize', updatePerPage)
})
</script>
