<script setup lang="ts">
/**
 * 首页
 *
 * 布局：轮播图 → 公告栏 → 热门商品 → 新品上市
 */
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowRight, Bell } 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 { getBannersApi } from '@/api/banner'
import { getNoticesApi } from '@/api/notice'
import { getHotProductsApi, getNewProductsApi } from '@/api/product'
import type { BannerItem } from '@/types/banner'
import type { NoticeItem } from '@/types/notice'
import type { ProductItem } from '@/types/product'

const router = useRouter()

// ==================== 数据 ====================
const banners = ref<BannerItem[]>([])
const notices = ref<NoticeItem[]>([])
const hotProducts = ref<ProductItem[]>([])
const newProducts = ref<ProductItem[]>([])

const loading = ref({
  banners: true,
  notices: true,
  hot: true,
  new: true
})

// ==================== 加载 ====================
onMounted(async () => {
  // 并行加载所有数据
  await Promise.allSettled([
    getBannersApi().then(data => {
      banners.value = data || []
      loading.value.banners = false
    }).catch(() => { loading.value.banners = false }),
    getNoticesApi().then(data => {
      notices.value = data || []
      loading.value.notices = false
    }).catch(() => { loading.value.notices = false }),
    getHotProductsApi(10).then(data => {
      hotProducts.value = data || []
      loading.value.hot = false
    }).catch(() => { loading.value.hot = false }),
    getNewProductsApi(10).then(data => {
      newProducts.value = data || []
      loading.value.new = false
    }).catch(() => { loading.value.new = false })
  ])
})

// ==================== 轮播图 ====================
function handleBannerClick(banner: BannerItem) {
  if (banner.linkType === 1) {
    // 跳转商品详情
    router.push(`/product/${banner.linkValue}`)
  } else if (banner.linkType === 2) {
    // 跳转分类
    router.push(`/category/${banner.linkValue}`)
  } else if (banner.linkType === 3) {
    // 外链
    window.open(banner.linkValue, '_blank')
  }
}

// ==================== 公告 ====================
function handleNoticeClick(notice: NoticeItem) {
  router.push(`/notice/${notice.id}`)
}

function goToNotices() {
  router.push('/notice')
}
</script>

<template>
  <div class="home-page">
    <AppHeader />

    <main class="home-main">
      <!-- ======== 轮播图 ======== -->
      <section class="banner-section">
        <div class="container">
          <el-skeleton :loading="loading.banners" animated :count="1">
            <template #template>
              <div class="banner-skeleton" />
            </template>
            <template #default>
              <el-carousel
                v-if="banners.length > 0"
                :interval="4000"
                arrow="hover"
                indicator-position="outside"
                height="360px"
                class="home-carousel"
              >
                <el-carousel-item v-for="banner in banners" :key="banner.id">
                  <div
                    class="carousel-item"
                    :style="{ backgroundImage: `url(${banner.image})` }"
                    @click="handleBannerClick(banner)"
                  >
                    <div class="carousel-overlay" />
                    <div class="carousel-content">
                      <h2>{{ banner.title }}</h2>
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel>
              <EmptyState v-else description="暂无轮播图" />
            </template>
          </el-skeleton>
        </div>
      </section>

      <!-- ======== 公告栏 ======== -->
      <section class="notice-section">
        <div class="container">
          <div class="notice-bar">
            <div class="notice-header" @click="goToNotices">
              <el-icon :size="18"><Bell /></el-icon>
              <span class="notice-label">公告</span>
            </div>
            <div class="notice-scroll">
              <el-skeleton :loading="loading.notices" animated :count="1">
                <template #template>
                  <div style="height: 20px" />
                </template>
                <template #default>
                  <template v-if="notices.length > 0">
                    <div class="notice-scroll-inner">
                      <span
                        v-for="notice in notices"
                        :key="notice.id"
                        class="notice-item"
                        @click="handleNoticeClick(notice)"
                      >
                        <span v-if="notice.type === 2" class="notice-badge notice-badge-event">活动</span>
                        <span v-else-if="notice.type === 1" class="notice-badge notice-badge-important">重要</span>
                        <span v-else class="notice-badge notice-badge-normal">公告</span>
                        {{ notice.title }}
                      </span>
                    </div>
                  </template>
                  <span v-else class="notice-empty">暂无公告</span>
                </template>
              </el-skeleton>
            </div>
            <span class="notice-more" @click="goToNotices">
              更多 <el-icon><ArrowRight /></el-icon>
            </span>
          </div>
        </div>
      </section>

      <!-- ======== 热门商品 ======== -->
      <section class="product-section">
        <div class="container">
          <div class="section-header">
            <h2 class="section-title">
              <span class="section-icon">🔥</span> 热门推荐
            </h2>
            <span class="section-subtitle">大家都在买</span>
            <span class="section-more" @click="router.push('/products')">
              查看更多
              <el-icon :size="14"><ArrowRight /></el-icon>
            </span>
          </div>

          <el-skeleton :loading="loading.hot" animated :count="4">
            <template #template>
              <div class="product-grid">
                <div v-for="i in 8" :key="i" class="product-skeleton-card" />
              </div>
            </template>
            <template #default>
              <div v-if="hotProducts.length > 0" class="product-grid">
                <ProductCard
                  v-for="product in hotProducts"
                  :key="product.id"
                  :product="product"
                />
              </div>
              <EmptyState v-else description="暂无热门商品" />
            </template>
          </el-skeleton>
        </div>
      </section>

      <!-- ======== 新品上市 ======== -->
      <section class="product-section">
        <div class="container">
          <div class="section-header">
            <h2 class="section-title">
              <span class="section-icon">✨</span> 新品上市
            </h2>
            <span class="section-subtitle">最新上架的好零食</span>
            <span class="section-more" @click="router.push('/products')">
              查看更多
              <el-icon :size="14"><ArrowRight /></el-icon>
            </span>
          </div>

          <el-skeleton :loading="loading.new" animated :count="4">
            <template #template>
              <div class="product-grid">
                <div v-for="i in 8" :key="i" class="product-skeleton-card" />
              </div>
            </template>
            <template #default>
              <div v-if="newProducts.length > 0" class="product-grid">
                <ProductCard
                  v-for="product in newProducts"
                  :key="product.id"
                  :product="product"
                />
              </div>
              <EmptyState v-else description="暂无新品" />
            </template>
          </el-skeleton>
        </div>
      </section>
    </main>

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

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

.home-main {
  flex: 1;
}

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

// ==================== 轮播图 ====================
.banner-section {
  padding-top: 24px;
}

.banner-skeleton {
  width: 100%;
  height: 360px;
  border-radius: $radius-lg;
  background: $bg-hover;
}

.home-carousel {
  border-radius: $radius-lg;
  overflow: hidden;
  box-shadow: $clay-shadow-sm;
  border: 2px solid $color-border;

  :deep(.el-carousel__indicators--outside) {
    margin-top: 14px;
  }
}

.carousel-item {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: flex-end;
}

.carousel-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(60, 30, 20, 0.45) 0%, transparent 60%);
}

.carousel-content {
  position: relative;
  z-index: 1;
  padding: 40px 48px;

  h2 {
    margin: 0;
    font-size: $font-size-display;
    font-weight: 700;
    color: #fff;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  }
}

// ==================== 公告栏 ====================
.notice-section {
  margin-top: 24px;
}

.notice-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  box-shadow: $clay-shadow-sm;
}

.notice-header {
  display: flex;
  align-items: center;
  gap: 6px;
  color: $color-primary;
  font-weight: 600;
  font-size: $font-size-sm;
  cursor: pointer;
  flex-shrink: 0;
  padding-right: 12px;
  border-right: 1px solid $color-border;

  .notice-label {
    font-family: 'Fredoka', 'PingFang SC', sans-serif;
  }
}

.notice-scroll {
  flex: 1;
  overflow: hidden;
  min-width: 0;
}

.notice-scroll-inner {
  display: flex;
  gap: 32px;
  animation: notice-marquee 20s linear infinite;

  @media (prefers-reduced-motion: reduce) {
    animation: none;
  }
}

@keyframes notice-marquee {
  0% { transform: translateX(0); }
  100% { transform: translateX(-50%); }
}

.notice-item {
  white-space: nowrap;
  font-size: $font-size-sm;
  color: $color-text-regular;
  cursor: pointer;
  transition: color 0.2s;

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

.notice-badge {
  display: inline-block;
  padding: 1px 7px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
  line-height: 1.5;
  margin-right: 6px;

  &.notice-badge-event {
    background: $color-primary-light;
    color: $color-primary;
  }
  &.notice-badge-important {
    background: #FEF3C7;
    color: $color-warning;
  }
  &.notice-badge-normal {
    background: $bg-hover;
    color: $color-text-secondary;
  }
}

.notice-empty {
  font-size: $font-size-sm;
  color: $color-text-placeholder;
}

.notice-more {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: $font-size-sm;
  color: $color-text-secondary;
  cursor: pointer;
  flex-shrink: 0;
  transition: color 0.2s;

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

// ==================== 商品区域 ====================
.product-section {
  margin-top: 48px;
}

.section-header {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 24px;

  .section-title {
    margin: 0;
    font-size: $font-size-xxl;
    font-weight: 700;
    color: $color-text-primary;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .section-icon {
    font-size: 24px;
  }

  .section-subtitle {
    font-size: $font-size-sm;
    color: $color-text-secondary;
  }

  .section-more {
    margin-left: auto;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 6px 14px;
    border: 2px solid $color-border;
    border-radius: $radius-full;
    background: $color-primary-light;
    color: $color-primary;
    font-size: $font-size-sm;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.2s, transform 0.2s, box-shadow 0.2s;

    &:hover {
      background: #FFE4D9;
      transform: translateY(-1px);
    }
  }
}

.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) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  .carousel-content h2 {
    font-size: $font-size-display;
  }
}

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

  .home-carousel {
    height: 220px !important;
  }
}
</style>
