<script setup lang="ts">
/**
 * 商品列表页
 *
 * 全部商品 / 分类浏览，支持综合、销量、价格、最新排序
 */
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Goods } from '@element-plus/icons-vue'
import AppHeader from '@/components/layout/AppHeader.vue'
import AppFooter from '@/components/layout/AppFooter.vue'
import ProductCard from '@/components/product/ProductCard.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import { getCategoryTreeApi } from '@/api/category'
import { getProductsByCategoryApi } from '@/api/product'
import type { CategoryTreeNode } from '@/types/category'
import type { ProductItem } from '@/types/product'

type SortKey = 'default' | 'sales' | 'price_asc' | 'price_desc' | 'newest'

interface SortOption {
  key: SortKey
  label: string
}

const route = useRoute()
const router = useRouter()

const categories = ref<CategoryTreeNode[]>([])
const products = ref<ProductItem[]>([])
const loading = ref(true)
const activeCategoryId = ref<number | null>(null)
const activeSort = ref<SortKey>('default')

const sortOptions: SortOption[] = [
  { key: 'default', label: '综合' },
  { key: 'sales', label: '销量' },
  { key: 'price_asc', label: '价格 ↑' },
  { key: 'price_desc', label: '价格 ↓' },
  { key: 'newest', label: '最新' }
]

const activeRoot = computed(() => {
  if (activeCategoryId.value == null) return null
  return findCategoryRoot(activeCategoryId.value)
})

const pageTitle = computed(() => activeRoot.value?.name || '全部商品')

const sortedProducts = computed(() => {
  const list = [...products.value]
  switch (activeSort.value) {
    case 'sales':
      return list.sort((a, b) => b.sales - a.sales)
    case 'price_asc':
      return list.sort((a, b) => Number(a.minPrice || 0) - Number(b.minPrice || 0))
    case 'price_desc':
      return list.sort((a, b) => Number(b.minPrice || 0) - Number(a.minPrice || 0))
    case 'newest':
      return list.sort((a, b) => String(b.createTime).localeCompare(String(a.createTime)))
    default:
      return list.sort((a, b) => (b.isHot - a.isHot) || (b.sales - a.sales))
  }
})

function findCategoryRoot(
  targetId: number,
  nodes: CategoryTreeNode[] = categories.value
): CategoryTreeNode | null {
  for (const node of nodes) {
    if (node.id === targetId) return node
    if (node.children?.length) {
      const found = findCategoryRoot(targetId, node.children)
      if (found) return node
    }
  }
  return null
}

function collectCategoryIds(cat: CategoryTreeNode): number[] {
  const ids = [cat.id]
  if (cat.children?.length) {
    cat.children.forEach(child => ids.push(...collectCategoryIds(child)))
  }
  return ids
}

function syncFromRoute() {
  const rawId = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id
  const parsedId = Number(rawId)
  if (rawId && Number.isFinite(parsedId) && parsedId > 0) {
    activeCategoryId.value = findCategoryRoot(parsedId)?.id ?? parsedId
  } else {
    activeCategoryId.value = null
  }
}

async function fetchProducts() {
  loading.value = true
  try {
    const categoryIds = activeRoot.value
      ? collectCategoryIds(activeRoot.value).join(',')
      : ''
    const data = await getProductsByCategoryApi(categoryIds, 'create_desc', 100)
    products.value = data || []
  } catch {
    products.value = []
  } finally {
    loading.value = false
    document.title = pageTitle.value === '全部商品'
      ? '全部商品 - 零食商城'
      : `${pageTitle.value} - 零食商城`
  }
}

function selectCategory(id: number | null) {
  if (id == null) {
    router.push('/products')
  } else {
    router.push(`/category/${id}`)
  }
}

function selectSort(key: SortKey) {
  activeSort.value = key
}

watch(() => route.params.id, () => {
  syncFromRoute()
  fetchProducts()
})

onMounted(async () => {
  try {
    categories.value = await getCategoryTreeApi()
  } catch {
    categories.value = []
  }
  syncFromRoute()
  await fetchProducts()
})
</script>

<template>
  <div class="product-list-page">
    <AppHeader />

    <main class="list-main">
      <div class="container">
        <div class="page-head">
          <div class="title-row">
            <button
              v-if="activeCategoryId != null"
              type="button"
              class="back-btn"
              @click="selectCategory(null)"
            >
              <el-icon :size="15"><ArrowLeft /></el-icon>
              全部商品
            </button>
            <h1 class="page-title">
              <span class="title-badge">
                <el-icon :size="18"><Goods /></el-icon>
              </span>
              {{ pageTitle }}
            </h1>
            <span class="count-badge">{{ products.length }} 件商品</span>
          </div>
        </div>

        <div class="filter-bar">
          <div class="category-tabs">
            <button
              type="button"
              class="category-tab"
              :class="{ active: activeCategoryId == null }"
              @click="selectCategory(null)"
            >
              全部
            </button>
            <button
              v-for="cat in categories"
              :key="cat.id"
              type="button"
              class="category-tab"
              :class="{ active: activeCategoryId === cat.id }"
              @click="selectCategory(cat.id)"
            >
              {{ cat.name }}
            </button>
          </div>

          <div class="sort-bar">
            <button
              v-for="option in sortOptions"
              :key="option.key"
              type="button"
              class="sort-option"
              :class="{ active: activeSort === option.key }"
              @click="selectSort(option.key)"
            >
              {{ option.label }}
            </button>
          </div>
        </div>

        <section class="product-section">
          <div v-if="loading" class="product-grid">
            <div v-for="i in 10" :key="i" class="product-skeleton-card" />
          </div>

          <EmptyState
            v-else-if="sortedProducts.length === 0"
            description="该分类下还没有商品，看看其他分类吧"
          />

          <div v-else class="product-grid">
            <ProductCard
              v-for="product in sortedProducts"
              :key="product.id"
              :product="product"
            />
          </div>
        </section>
      </div>
    </main>

    <AppFooter />
  </div>
</template>

<style lang="scss" scoped>
.product-list-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-page;
}

.list-main {
  flex: 1;
  padding: 28px 0 48px;
}

.container {
  max-width: $container-max;
  margin: 0 auto;
  padding: 0 24px;
}

// ==================== 页头 ====================
.page-head {
  margin-bottom: 20px;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 14px;
  flex-wrap: wrap;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 14px;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  background: $bg-surface;
  color: $color-text-regular;
  font-size: $font-size-sm;
  font-weight: 600;
  box-shadow: 0 2px 0 0 $color-border-dark;
  cursor: pointer;
  transition: color 0.2s, border-color 0.2s, transform 0.2s, box-shadow 0.2s;

  &:hover {
    color: $color-primary;
    border-color: $color-primary;
    transform: translateY(-1px);
  }
}

.page-title {
  margin: 0;
  font-family: 'Fredoka', 'PingFang SC', sans-serif;
  font-size: $font-size-xxl;
  font-weight: 700;
  color: $color-text-primary;
  display: flex;
  align-items: center;
  gap: 10px;

  .title-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: $color-primary-light;
    color: $color-primary;
  }
}

.count-badge {
  padding: 5px 12px;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  background: $bg-surface;
  color: $color-text-secondary;
  font-size: $font-size-sm;
  font-weight: 600;
}

// ==================== 筛选栏 ====================
.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
  padding: 14px 18px;
  margin-bottom: 24px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  box-shadow: $clay-shadow-sm;
}

.category-tabs {
  display: flex;
  gap: 8px;
  max-width: 100%;
  overflow-x: auto;
  padding-bottom: 2px;
}

.category-tab {
  flex-shrink: 0;
  min-height: 40px;
  padding: 0 18px;
  border: 2px solid transparent;
  border-radius: $radius-full;
  background: transparent;
  color: $color-text-secondary;
  font-size: $font-size-md;
  font-weight: 600;
  cursor: pointer;
  transition: color 0.2s, background-color 0.2s, border-color 0.2s, box-shadow 0.2s;

  &:hover {
    color: $color-primary;
    background: $color-primary-light;
  }

  &.active {
    color: #fff;
    background: linear-gradient(135deg, $color-primary, $color-cta);
    border-color: $color-border-dark;
    box-shadow: 0 3px 0 0 $color-primary-dark;
  }
}

.sort-bar {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.sort-option {
  flex-shrink: 0;
  min-height: 36px;
  padding: 0 12px;
  border: 2px solid transparent;
  border-radius: $radius-full;
  background: transparent;
  color: $color-text-secondary;
  font-size: $font-size-sm;
  font-weight: 600;
  cursor: pointer;
  transition: color 0.2s, background-color 0.2s, border-color 0.2s;

  &:hover {
    color: $color-primary;
  }

  &.active {
    color: $color-primary;
    background: $color-primary-light;
    border-color: $color-border;
  }
}

// ==================== 商品区 ====================
.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

.product-skeleton-card {
  aspect-ratio: 1 / 1.35;
  border-radius: $radius-lg;
  background: $bg-hover;
}

// ==================== 响应式 ====================
@media (max-width: 1200px) {
  .product-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 900px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .product-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }
}

@media (max-width: 640px) {
  .container {
    padding: 0 16px;
  }

  .page-title {
    font-size: $font-size-xl;
  }

  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .category-tabs {
    margin: 0 -6px;
    padding: 2px 6px;
  }
}
</style>
