<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getBannerListApi } from '@/api/banner'
import { getCategoryTreeApi } from '@/api/category'
import { getHotProductsApi, getNewProductsApi } from '@/api/product'
import { getSeckillActivitiesApi } from '@/api/seckill'
import { getNoticeListApi } from '@/api/notice'
import type { ProductListItem, Banner, SeckillActivity, Notice, CategoryTreeNode } from '@/types'
import { Timer, ArrowRight, TrendCharts, Star, Bell, Folder, Ticket, HotWater } from '@element-plus/icons-vue'

const router = useRouter()

const banners = ref<Banner[]>([])
const categories = ref<CategoryTreeNode[]>([])
const hotProducts = ref<ProductListItem[]>([])
const newProducts = ref<ProductListItem[]>([])
const seckillActivities = ref<SeckillActivity[]>([])
const notices = ref<Notice[]>([])
const loading = ref(true)

const countdown = ref({ h: '00', m: '00', s: '00' })

function formatCountdown(seconds: number) {
  const s = Math.max(0, seconds)
  const h = Math.floor(s / 3600)
  const m = Math.floor((s % 3600) / 60)
  const sec = s % 60
  return {
    h: String(h).padStart(2, '0'),
    m: String(m).padStart(2, '0'),
    s: String(sec).padStart(2, '0')
  }
}

onMounted(async () => {
  loading.value = true
  try {
    const [bRes, cRes, hRes, nRes, sRes, noRes] = await Promise.all([
      getBannerListApi(),
      getCategoryTreeApi(),
      getHotProductsApi(10),
      getNewProductsApi(10),
      getSeckillActivitiesApi(),
      getNoticeListApi()
    ])
    banners.value = bRes || []
    categories.value = (cRes || []).filter(c => c.level === 1)
    hotProducts.value = hRes || []
    newProducts.value = nRes || []
    seckillActivities.value = sRes || []
    notices.value = (noRes || []).slice(0, 5)
  } finally {
    loading.value = false
  }

  setInterval(() => {
    const a = seckillActivities.value[0]
    if (a && typeof a.countdownSeconds === 'number') {
      countdown.value = formatCountdown(a.countdownSeconds)
    }
  }, 1000)
})

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

function goCategory(id: number) {
  router.push({ name: 'category', params: { id } })
}

function handleBannerClick(b: Banner) {
  if (b.linkType === 1 && b.linkValue) {
    goProduct(Number(b.linkValue))
  } else if (b.linkType === 2 && b.linkValue) {
    goCategory(Number(b.linkValue))
  }
}
</script>

<template>
  <div class="home-page">
    <!-- Hero Section -->
    <section class="hero-section">
      <div class="container hero-wrap">
        <!-- Category Sidebar -->
        <div class="category-sidebar">
          <div class="sidebar-header">
            <el-icon><Folder /></el-icon>
            <span>商品分类</span>
          </div>
          <div class="sidebar-list">
            <div
              v-for="cat in categories" :key="cat.id"
              class="sidebar-item"
              @click="goCategory(cat.id)"
            >
              <span>{{ cat.name }}</span>
              <el-icon><ArrowRight /></el-icon>
            </div>
            <div v-if="!categories.length" class="sidebar-empty">加载中...</div>
          </div>
        </div>

        <!-- Banner Carousel -->
        <div class="banner-carousel">
          <el-carousel height="420px" arrow="always" indicator-position="outside">
            <el-carousel-item v-for="banner in banners" :key="banner.id">
              <div class="banner-slide" @click="handleBannerClick(banner)">
                <img :src="banner.image" :alt="banner.title || 'banner'" class="banner-img" />
                <div v-if="banner.title" class="banner-overlay">
                  <h3>{{ banner.title }}</h3>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- Right Panel -->
        <div class="hero-right">
          <div class="notice-board">
            <div class="board-header">
              <el-icon><Bell /></el-icon>
              <span>商城公告</span>
            </div>
            <div class="notice-list">
              <p v-for="n in notices" :key="n.id" @click="router.push('/notice')">
                <el-tag v-if="n.isTop" type="danger" size="small" effect="plain">置顶</el-tag>
                <span class="notice-title">{{ n.title }}</span>
              </p>
              <p v-if="!notices.length" class="empty">暂无公告</p>
            </div>
          </div>
          <div class="quick-actions">
            <div class="action-card seckill" @click="router.push('/seckill')">
              <div class="action-icon">
                <el-icon :size="24"><Timer /></el-icon>
              </div>
              <div class="action-text">
                <span class="action-label">限时秒杀</span>
                <span class="action-desc">超值抢购</span>
              </div>
            </div>
            <div class="action-card coupon" @click="router.push('/coupons')">
              <div class="action-icon">
                <el-icon :size="24"><Ticket /></el-icon>
              </div>
              <div class="action-text">
                <span class="action-label">领优惠券</span>
                <span class="action-desc">先领再买</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Seckill Section -->
    <section v-if="seckillActivities.length" class="seckill-section">
      <div class="container">
        <div class="section-header seckill-header">
          <div class="header-left">
            <div class="seckill-badge">
              <el-icon><HotWater /></el-icon>
            </div>
            <h2 class="seckill-title">限时秒杀</h2>
            <div class="countdown">
              <span class="cd-label">距结束</span>
              <span class="cd-num">{{ countdown.h }}</span>
              <span class="cd-sep">:</span>
              <span class="cd-num">{{ countdown.m }}</span>
              <span class="cd-sep">:</span>
              <span class="cd-num">{{ countdown.s }}</span>
            </div>
          </div>
          <a class="more-link" @click="router.push('/seckill')">
            更多秒杀 <el-icon><ArrowRight /></el-icon>
          </a>
        </div>
        <div class="seckill-grid">
          <div
            v-for="sp in (seckillActivities[0]?.products || []).slice(0, 5)" :key="sp.id"
            class="seckill-card hover-card"
            @click="goProduct(sp.productId)"
          >
            <div class="card-img">
              <img :src="sp.productImage || 'https://placehold.co/240x240?text=SNACK'" />
              <div class="discount-tag">-{{ Math.round((1 - sp.seckillPrice / sp.originPrice) * 100) }}%</div>
            </div>
            <div class="card-body">
              <p class="sp-name">{{ sp.productName }}</p>
              <div class="sp-price-row">
                <span class="sp-price">¥{{ sp.seckillPrice }}</span>
                <span class="sp-origin">¥{{ sp.originPrice }}</span>
              </div>
              <el-progress
                :percentage="sp.soldPercent ?? 0"
                :color="'var(--color-primary)'"
                :stroke-width="5"
                :show-text="false"
                class="sp-progress"
              />
              <p class="sp-stock">已抢 {{ sp.soldPercent ?? 0 }}%</p>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Hot Products -->
    <section class="products-section">
      <div class="container">
        <div class="section-header">
          <div class="header-left">
            <div class="section-icon hot">
              <el-icon><HotWater /></el-icon>
            </div>
            <h2>热门推荐</h2>
          </div>
          <a class="more-link" @click="router.push({ name: 'search', query: { hot: '1' } })">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </a>
        </div>
        <div class="product-grid">
          <div
            v-for="product in hotProducts" :key="product.id"
            class="product-card hover-card"
            @click="goProduct(product.id)"
          >
            <div class="product-img-wrap">
              <img :src="product.mainImage || 'https://placehold.co/300x300?text=SNACK'" :alt="product.name" />
              <span v-if="product.isHot" class="tag hot-tag">热销</span>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-desc">月销 {{ product.sales }}+</p>
              <div class="product-price">
                <span class="price-lg">¥{{ product.minPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- New Products -->
    <section class="products-section">
      <div class="container">
        <div class="section-header">
          <div class="header-left">
            <div class="section-icon new">
              <el-icon><Star /></el-icon>
            </div>
            <h2>新品上市</h2>
          </div>
          <a class="more-link" @click="router.push({ name: 'search', query: { new: '1' } })">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </a>
        </div>
        <div class="product-grid">
          <div
            v-for="product in newProducts" :key="product.id"
            class="product-card hover-card"
            @click="goProduct(product.id)"
          >
            <div class="product-img-wrap">
              <img :src="product.mainImage || 'https://placehold.co/300x300?text=SNACK'" :alt="product.name" />
              <span v-if="product.isNew" class="tag new-tag">新品</span>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-desc">新鲜上架</p>
              <div class="product-price">
                <span class="price-lg">¥{{ product.minPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
.home-page {
  padding-bottom: 60px;
}

/* ===== Hero Section ===== */
.hero-section {
  background: linear-gradient(180deg, #fff 0%, var(--color-background) 100%);
  padding: 20px 0 32px;
}
.hero-wrap {
  display: grid;
  grid-template-columns: 220px 1fr 260px;
  gap: 20px;
  align-items: start;
}

/* Category Sidebar */
.category-sidebar {
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  overflow: hidden;
}
.sidebar-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 18px;
  background: var(--color-primary-gradient);
  color: #fff;
  font-weight: 600;
  font-size: 15px;
}
.sidebar-list {
  padding: 8px 0;
}
.sidebar-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 18px;
  cursor: pointer;
  transition: all var(--transition-fast);
  font-size: 14px;
  color: var(--color-text);
}
.sidebar-item:hover {
  background: var(--color-primary-light);
  color: var(--color-primary);
  font-weight: 600;
}
.sidebar-empty {
  padding: 20px;
  text-align: center;
  color: var(--color-text-muted);
  font-size: 13px;
}

/* Banner */
.banner-carousel {
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
}
.banner-slide {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.banner-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 40px 24px 24px;
  background: linear-gradient(transparent, rgba(0,0,0,0.5));
  color: #fff;
}
.banner-overlay h3 {
  color: #fff;
  font-size: 22px;
  font-weight: 600;
}

/* Hero Right */
.hero-right {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.notice-board {
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  padding: 18px;
  flex: 1;
}
.board-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: var(--color-primary);
  margin-bottom: 14px;
  font-size: 15px;
}
.notice-list p {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--color-text-secondary);
  margin-bottom: 10px;
  cursor: pointer;
  line-height: 1.5;
  transition: color var(--transition-fast);
}
.notice-list p:hover {
  color: var(--color-primary);
}
.notice-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.notice-list .empty {
  color: var(--color-text-muted);
  cursor: default;
}
.quick-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}
.action-card {
  background: #fff;
  border-radius: var(--radius-lg);
  padding: 18px 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: all var(--transition-base);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
}
.action-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  border-color: var(--color-primary);
}
.action-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-full);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
.action-card.seckill .action-icon {
  background: linear-gradient(135deg, #FF6B35, #FF8F5D);
}
.action-card.coupon .action-icon {
  background: linear-gradient(135deg, #F59E0B, #FBBF24);
}
.action-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}
.action-label {
  font-weight: 600;
  font-size: 14px;
  color: var(--color-text);
}
.action-desc {
  font-size: 12px;
  color: var(--color-text-muted);
}

/* ===== Seckill Section ===== */
.seckill-section {
  margin-top: 8px;
}
.seckill-header {
  background: linear-gradient(135deg, #FFF0EB 0%, #FFF5F2 100%);
  padding: 16px 24px;
  border-radius: var(--radius-lg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border: 1px solid rgba(255, 107, 53, 0.1);
}
.header-left {
  display: flex;
  align-items: center;
  gap: 14px;
}
.seckill-badge {
  width: 40px;
  height: 40px;
  border-radius: var(--radius-full);
  background: var(--color-primary-gradient);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 20px;
  animation: pulse 2s infinite;
}
@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.08); }
}
.seckill-title {
  font-size: 22px;
  color: var(--color-primary-dark);
  font-weight: 700;
}
.countdown {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 700;
}
.cd-label {
  font-size: 13px;
  color: var(--color-text-secondary);
  margin-right: 4px;
}
.cd-num {
  background: var(--color-primary-gradient);
  color: #fff;
  padding: 4px 8px;
  border-radius: var(--radius-sm);
  font-size: 16px;
  font-variant-numeric: tabular-nums;
  min-width: 32px;
  text-align: center;
}
.cd-sep {
  color: var(--color-primary);
  font-weight: 700;
}
.more-link {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--color-text-secondary);
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: var(--radius-full);
  transition: all var(--transition-fast);
}
.more-link:hover {
  color: var(--color-primary);
  background: var(--color-primary-light);
}
.seckill-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
}
.seckill-card {
  background: #fff;
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
}
.card-img {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}
.card-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-slow);
}
.seckill-card:hover .card-img img {
  transform: scale(1.08);
}
.discount-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: var(--color-danger);
  color: #fff;
  padding: 4px 10px;
  border-radius: var(--radius-full);
  font-size: 12px;
  font-weight: 700;
  box-shadow: var(--shadow-sm);
}
.card-body {
  padding: 14px;
}
.sp-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--color-text);
}
.sp-price-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 10px;
}
.sp-price {
  color: var(--color-primary);
  font-size: 20px;
  font-weight: 700;
}
.sp-origin {
  color: var(--color-text-muted);
  text-decoration: line-through;
  font-size: 13px;
}
.sp-stock {
  font-size: 12px;
  color: var(--color-text-muted);
  margin-top: 6px;
}
.sp-progress :deep(.el-progress-bar__outer) {
  border-radius: var(--radius-full);
  background-color: var(--color-border-light);
}
.sp-progress :deep(.el-progress-bar__inner) {
  border-radius: var(--radius-full);
}

/* ===== Products Section ===== */
.products-section {
  margin-top: 40px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.section-icon {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
.section-icon.hot {
  background: linear-gradient(135deg, #FF6B35, #FF8F5D);
}
.section-icon.new {
  background: linear-gradient(135deg, #06D6A0, #34D399);
}
.section-header h2 {
  font-size: 22px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 10px;
}
.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 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);
}
.product-img-wrap {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}
.product-img-wrap img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-slow);
}
.product-card:hover .product-img-wrap 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);
}
.hot-tag {
  background: linear-gradient(135deg, #FF6B35, #EF4444);
}
.new-tag {
  background: linear-gradient(135deg, #06D6A0, #3B82F6);
}
.product-info {
  padding: 14px;
}
.product-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--color-text);
}
.product-desc {
  font-size: 13px;
  color: var(--color-text-muted);
  margin-bottom: 10px;
}
.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* ===== Responsive ===== */
@media (max-width: 1280px) {
  .hero-wrap {
    grid-template-columns: 200px 1fr 240px;
  }
  .product-grid {
    grid-template-columns: repeat(4, 1fr);
  }
  .seckill-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1024px) {
  .hero-wrap {
    grid-template-columns: 1fr;
  }
  .category-sidebar,
  .hero-right {
    display: none;
  }
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  .seckill-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  .seckill-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  .seckill-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
    padding: 14px 16px;
  }
  .products-section {
    margin-top: 24px;
  }
  .home-page {
    padding-bottom: 24px;
  }
}
</style>
