<script setup lang="ts">
import { ref, watch, onMounted, computed } from "vue"
import { useRoute, useRouter } from "vue-router"
import { getProductListApi } from "@/api/product"
import { getCategoryTreeApi } from "@/api/category"
import type { ProductListItem, CategoryTreeNode } from "@/types"
import { Grid, ArrowRight } from "@element-plus/icons-vue"

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

const products = ref<ProductListItem[]>([])
const categories = ref<CategoryTreeNode[]>([])
const currentCategory = ref<number>(Number(route.params.id))
const sortType = ref<"default" | "sales" | "price-asc" | "price-desc">("default")
const loading = ref(false)

const orderByMap: Record<string, "sales_desc" | "price_asc" | "price_desc" | "create_desc" | undefined> = {
  default: undefined,
  sales: "sales_desc",
  "price-asc": "price_asc",
  "price-desc": "price_desc"
}

async function loadData() {
  loading.value = true
  try {
    const [pRes, cRes] = await Promise.all([
      getProductListApi({
        categoryIds: [currentCategory.value],
        orderBy: orderByMap[sortType.value],
        limit: 100
      }),
      getCategoryTreeApi()
    ])
    products.value = pRes || []
    categories.value = (cRes || []).filter(c => c.level === 1)
  } finally {
    loading.value = false
  }
}

watch(
  () => route.params.id,
  (id) => {
    currentCategory.value = Number(id)
    sortType.value = "default"
    loadData()
  }
)
watch(sortType, loadData)

onMounted(loadData)

function goProduct(id: number) {
  router.push({ name: "product-detail", params: { id } })
}

const currentCategoryName = computed(() => {
  const c = categories.value.find(x => x.id === currentCategory.value)
  return c?.name || `分类 ${currentCategory.value}`
})

const sortOptions = [
  { label: '综合排序', value: 'default' },
  { label: '销量优先', value: 'sales' },
  { label: '价格 ↑', value: 'price-asc' },
  { label: '价格 ↓', value: 'price-desc' },
]
</script>

<template>
  <div class="category-page container">
    <!-- Breadcrumb -->
    <div class="breadcrumb-wrap">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentCategoryName }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="category-layout">
      <!-- Sidebar -->
      <aside class="category-sidebar">
        <div class="sidebar-header">
          <el-icon><Grid /></el-icon>
          <span>商品分类</span>
        </div>
        <div class="sidebar-list">
          <div
            v-for="cat in categories"
            :key="cat.id"
            class="cat-item"
            :class="{ active: cat.id === currentCategory }"
            @click="router.push({ name: 'category', params: { id: cat.id } })"
          >
            <span>{{ cat.name }}</span>
            <el-icon v-if="cat.id === currentCategory"><ArrowRight /></el-icon>
          </div>
        </div>
      </aside>

      <!-- Main -->
      <div class="category-main">
        <!-- Sort Bar -->
        <div class="sort-bar">
          <div class="sort-tabs">
            <button
              v-for="opt in sortOptions"
              :key="opt.value"
              class="sort-btn"
              :class="{ active: sortType === opt.value }"
              @click="sortType = opt.value as any"
            >
              {{ opt.label }}
            </button>
          </div>
          <span class="total">共 {{ products.length }} 件商品</span>
        </div>

        <!-- Product Grid -->
        <div v-loading="loading" class="product-grid">
          <div
            v-for="product in products"
            :key="product.id"
            class="product-card hover-card"
            @click="goProduct(product.id)"
          >
            <div class="card-img">
              <img :src="product.mainImage || 'https://placehold.co/300x300?text=SNACK'" :alt="product.name" />
              <span v-if="product.isHot" class="tag hot">热销</span>
              <span v-if="product.isNew" class="tag new">新品</span>
            </div>
            <div class="card-body">
              <h4>{{ product.name }}</h4>
              <p class="desc">月销 {{ product.sales }}</p>
              <div class="price-row">
                <span class="price-lg">¥{{ product.minPrice }}</span>
              </div>
            </div>
          </div>
        </div>

        <el-empty v-if="!loading && products.length === 0" description="暂无商品">
          <el-button type="primary" @click="router.push('/')">去首页</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<style scoped>
.category-page {
  padding: 20px 0 60px;
}
.breadcrumb-wrap {
  margin-bottom: 20px;
}

/* Layout */
.category-layout {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 24px;
}

/* Sidebar */
.category-sidebar {
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 8px;
  height: fit-content;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  position: sticky;
  top: 100px;
}
.sidebar-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 16px;
  font-weight: 700;
  font-size: 16px;
  color: var(--color-text);
  border-bottom: 1px solid var(--color-border-light);
  margin-bottom: 4px;
}
.sidebar-list {
  padding: 4px;
}
.cat-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 14px;
  cursor: pointer;
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
  font-size: 14px;
  color: var(--color-text-secondary);
  margin-bottom: 2px;
}
.cat-item:hover {
  background: var(--color-primary-light);
  color: var(--color-primary);
}
.cat-item.active {
  background: var(--color-primary-gradient);
  color: #fff;
  font-weight: 600;
  box-shadow: var(--shadow-sm);
}

/* Main */
.category-main {
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 24px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  min-height: 500px;
}

/* Sort Bar */
.sort-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--color-border-light);
}
.sort-tabs {
  display: flex;
  gap: 8px;
}
.sort-btn {
  padding: 8px 16px;
  border-radius: var(--radius-full);
  border: 1px solid var(--color-border-light);
  background: #fff;
  color: var(--color-text-secondary);
  font-size: 13px;
  cursor: pointer;
  transition: all var(--transition-fast);
  font-family: inherit;
}
.sort-btn:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
}
.sort-btn.active {
  background: var(--color-primary-gradient);
  color: #fff;
  border-color: var(--color-primary);
  font-weight: 600;
}
.total {
  color: var(--color-text-muted);
  font-size: 13px;
}

/* Product Grid */
.product-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}
.product-card {
  background: #fff;
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  transition: all var(--transition-base);
}
.card-img {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}
.card-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-slow);
}
.product-card:hover .card-img img {
  transform: scale(1.08);
}
.tag {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 12px;
  border-radius: var(--radius-full);
  font-size: 12px;
  color: #fff;
  font-weight: 700;
  box-shadow: var(--shadow-sm);
}
.tag.hot {
  background: linear-gradient(135deg, #FF6B35, #EF4444);
}
.tag.new {
  background: linear-gradient(135deg, #06D6A0, #3B82F6);
}
.card-body {
  padding: 14px;
}
.card-body h4 {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--color-text);
}
.desc {
  font-size: 13px;
  color: var(--color-text-muted);
  margin-bottom: 10px;
}
.price-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Responsive */
@media (max-width: 1024px) {
  .category-layout {
    grid-template-columns: 1fr;
  }
  .category-sidebar {
    position: static;
    display: none;
  }
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  .category-main {
    padding: 16px;
  }
  .sort-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
