<template>
  <div class="home-container">
    <a-space class="header-bar" wrap>
      <div class="logo">
        <a-avatar :size="40" style="background: linear-gradient(135deg, #ff7eb3 0%, #ff758c 100%)">
          <icon-heart />
        </a-avatar>
        <span class="logo-text">萌贝母婴</span>
      </div>
      <a-input-search v-model="keyword" placeholder="搜索母婴好物..." search-button @search="loadProducts" class="search-box" />
      <div class="header-actions">
        <a-badge :count="cartCount" :max-count="99">
          <a-button v-if="userStore.role === 'CUSTOMER'" shape="round" @click="goCart">
            <template #icon><icon-apps /></template>
            购物车
          </a-button>
        </a-badge>
        <template v-if="userStore.loggedIn">
          <a-dropdown>
            <a-button shape="round">
              <template #icon><icon-user /></template>
              {{ userStore.profile?.nickname || userStore.profile?.username }}
            </a-button>
            <template #content>
              <a-doption @click="goOrders" v-if="userStore.role === 'CUSTOMER'">
                <template #icon><icon-file /></template>
                我的订单
              </a-doption>
              <a-doption @click="goFavorites" v-if="userStore.role === 'CUSTOMER'">
                <template #icon><icon-heart /></template>
                我的收藏
              </a-doption>
              <a-doption @click="goProfile">
                <template #icon><icon-settings /></template>
                个人信息
              </a-doption>
              <a-doption @click="goConsole" v-if="userStore.role === 'ADMIN' || userStore.role === 'MERCHANT'">
                <template #icon><icon-dashboard /></template>
                管理后台
              </a-doption>
              <a-doption @click="logout">
                <template #icon><icon-export /></template>
                退出登录
              </a-doption>
            </template>
          </a-dropdown>
        </template>
        <a-button v-else type="primary" shape="round" @click="goLogin">
          <template #icon><icon-export /></template>
          登录
        </a-button>
      </div>
    </a-space>

    <div class="banner-section">
      <a-carousel auto-play :interval="4000" style="height: 280px; border-radius: 16px; overflow: hidden; box-shadow: 0 8px 24px rgba(0,0,0,0.12)">
        <a-carousel-item v-for="b in banners" :key="b.id">
          <img :src="b.imageUrl" style="width: 100%; height: 280px; object-fit: cover" />
        </a-carousel-item>
        <a-carousel-item v-if="banners.length === 0">
          <div class="banner-placeholder">
            <icon-safe :size="80" style="color: #ff758c" />
            <p>萌贝母婴商城 · 呵护每一次成长</p>
          </div>
        </a-carousel-item>
      </a-carousel>
    </div>

    <div class="category-section">
      <a-card :bordered="false" class="category-card">
        <a-space wrap>
          <a-tag
            v-for="cat in categories"
            :key="cat"
            :color="selectedCategory === cat ? 'pink' : 'gray'"
            checkable
            :checked="selectedCategory === cat"
            @click="selectCategory(cat)"
            class="category-tag"
          >
            {{ cat }}
          </a-tag>
        </a-space>
      </a-card>
    </div>

    <div class="products-section">
      <a-empty v-if="filteredProducts.length === 0 && !loading" description="暂无相关商品" />
      <a-grid :cols="{ xs: 1, sm: 2, md: 3, lg: 4 }" :col-gap="16" :row-gap="16">
        <a-grid-item v-for="p in filteredProducts" :key="p.id">
          <a-card class="product-card" :bordered="false" hoverable @click="showProductDetail(p)">
            <template #cover>
              <div class="product-image">
                <img :src="p.imageUrl || 'https://picsum.photos/300/200?baby=' + p.id" style="width: 100%; height: 180px; object-fit: cover" />
                <div class="product-badge" v-if="p.stock < 10">库存紧张</div>
              </div>
            </template>
            <div class="product-info">
              <div class="product-category">
                <a-tag size="small" color="pink">{{ p.category || '未分类' }}</a-tag>
              </div>
              <div class="product-name">{{ p.name }}</div>
              <div class="product-price">
                <span class="price-symbol">¥</span>
                <span class="price-value">{{ p.price }}</span>
              </div>
              <div class="product-actions">
                <a-space>
                  <a-button size="small" shape="round" @click.stop="addCart(p.id)" :disabled="userStore.role !== 'CUSTOMER'">
                    <template #icon><icon-plus /></template>
                    加购
                  </a-button>
                  <a-button size="small" type="primary" shape="round" @click.stop="buyNow(p.id)" :disabled="userStore.role !== 'CUSTOMER'">
                    立即购买
                  </a-button>
                  <a-button size="small" shape="round" @click.stop="addFavorite(p.id)" :disabled="userStore.role !== 'CUSTOMER'">
                    <icon-heart :style="{ color: isFavorite(p.id) ? '#ff4d4f' : '#b37feb' }" />
                  </a-button>
                </a-space>
              </div>
            </div>
          </a-card>
        </a-grid-item>
      </a-grid>
    </div>

    <a-drawer v-model:visible="detailVisible" title="商品详情" :width="480" unmountOnClose>
      <template v-if="currentProduct">
        <img :src="currentProduct.imageUrl || 'https://picsum.photos/400/300?baby=' + currentProduct.id" style="width: 100%; border-radius: 8px; margin-bottom: 16px" />
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="商品名称">{{ currentProduct.name }}</a-descriptions-item>
          <a-descriptions-item label="分类">{{ currentProduct.category || '未分类' }}</a-descriptions-item>
          <a-descriptions-item label="价格">¥{{ currentProduct.price }}</a-descriptions-item>
          <a-descriptions-item label="库存">
            <a-tag :color="currentProduct.stock > 20 ? 'green' : currentProduct.stock > 0 ? 'orange' : 'red'">
              {{ currentProduct.stock }}件
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="描述">{{ currentProduct.description || '暂无描述' }}</a-descriptions-item>
        </a-descriptions>
        <a-space style="width: 100%; justify-content: center; margin-top: 20px">
          <a-button type="primary" size="large" shape="round" @click="addCart(currentProduct.id)" :disabled="userStore.role !== 'CUSTOMER'">
            <template #icon><icon-apps /></template>
            加入购物车
          </a-button>
          <a-button type="primary" size="large" shape="round" status="success" @click="buyNow(currentProduct.id)" :disabled="userStore.role !== 'CUSTOMER'">
            立即购买
          </a-button>
        </a-space>
      </template>
    </a-drawer>

    <a-affix :bottom="20" style="right: 20px">
      <a-space direction="vertical">
        <a-button shape="circle" size="large" @click="scrollToTop">
          <template #icon><icon-arrow-up /></template>
        </a-button>
      </a-space>
    </a-affix>
  </div>
</template>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #fff5f8 0%, #f0f5ff 100%);
}

.header-bar {
  background: white;
  padding: 12px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-text {
  font-size: 22px;
  font-weight: 700;
  background: linear-gradient(135deg, #ff7eb3 0%, #ff758c 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.search-box {
  width: 360px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.banner-section {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 16px;
}

.banner-placeholder {
  width: 100%;
  height: 280px;
  background: linear-gradient(135deg, #fff0f5 0%, #f0f5ff 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.banner-placeholder p {
  font-size: 24px;
  font-weight: 600;
  color: #ff758c;
  margin: 0;
}

.category-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.category-card {
  background: white;
  border-radius: 12px;
  padding: 12px 16px;
}

.category-tag {
  cursor: pointer;
  padding: 6px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.category-tag:hover {
  transform: scale(1.05);
}

.products-section {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 16px 40px;
}

.product-card {
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(255, 117, 140, 0.2);
}

.product-image {
  position: relative;
  overflow: hidden;
}

.product-image img {
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.08);
}

.product-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: linear-gradient(135deg, #ff9a44 0%, #ff6b6b 100%);
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.product-info {
  padding: 8px 0;
}

.product-category {
  margin-bottom: 6px;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 2px;
  margin-bottom: 10px;
}

.price-symbol {
  font-size: 14px;
  color: #ff4d4f;
  font-weight: 600;
}

.price-value {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: 700;
}

.product-actions {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

:deep(.arco-card-body) {
  padding: 12px 16px;
}

:deep(.arco-input-search .arco-btn) {
  background: linear-gradient(135deg, #ff7eb3 0%, #ff758c 100%);
  border-color: transparent;
}

:deep(.arco-tag-checkable:checked) {
  background: linear-gradient(135deg, #ff7eb3 0%, #ff758c 100%);
  color: white;
  border-color: transparent;
}
</style>
<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { IconHeart, IconApps, IconUser, IconSettings, IconDashboard, IconExport, IconPlus, IconArrowUp, IconCheckCircle, IconFile, IconSafe } from '@arco-design/web-vue/es/icon'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

const keyword = ref('')
const cartCount = ref(0)
const banners = ref([])
const products = ref([])
const categories = ref(['全部', '奶粉', '尿裤', '玩具', '辅食', '服饰', '用品'])
const selectedCategory = ref('全部')
const currentProduct = ref(null)
const detailVisible = ref(false)
const loading = ref(false)
const favorites = ref([])

const filteredProducts = computed(() => {
  if (selectedCategory.value === '全部') return products.value
  return products.value.filter(p => p.category === selectedCategory.value)
})

const goCart = () => router.push('/cart')
const goOrders = () => router.push('/orders')
const goFavorites = () => router.push('/favorites')
const goProfile = () => router.push('/profile')
const goConsole = () => {
  if (userStore.role === 'ADMIN') router.push('/admin')
  else if (userStore.role === 'MERCHANT') router.push('/merchant')
}
const goLogin = () => router.push('/login')
const logout = async () => {
  await userStore.logout()
  router.replace('/login')
}

const loadBanners = async () => {
  try {
    banners.value = await api.banners()
  } catch (e) {
    console.error('加载轮播图失败', e)
  }
}

const loadProducts = async () => {
  loading.value = true
  try {
    products.value = await api.products(keyword.value)
  } catch (e) {
    console.error('加载商品失败', e)
  } finally {
    loading.value = false
  }
}

const loadFavorites = async () => {
  try {
    favorites.value = await api.customerFavorites()
  } catch (e) {
    console.error('加载收藏失败', e)
  }
}

const loadCartCount = async () => {
  try {
    const cart = await api.customerCart()
    cartCount.value = cart.length
  } catch (e) {
    console.error('加载购物车失败', e)
  }
}

const selectCategory = (cat) => {
  selectedCategory.value = cat
}

const showProductDetail = (product) => {
  currentProduct.value = product
  detailVisible.value = true
}

const addCart = async (productId) => {
  try {
    await api.addCart({ productId, quantity: 1 })
    Message.success('已加入购物车')
    await loadCartCount()
  } catch (e) {
    Message.error('添加失败')
  }
}

const buyNow = async (productId) => {
  try {
    await api.customerBuyNow({ productId, quantity: 1, address: '' })
    Message.success('购买成功')
    router.push('/orders')
  } catch (e) {
    Message.error('购买失败')
  }
}

const addFavorite = async (productId) => {
  try {
    await api.addFavorite({ productId })
    Message.success('已收藏')
    await loadFavorites()
  } catch (e) {
    Message.error('收藏失败')
  }
}

const isFavorite = (productId) => {
  return favorites.value.some(f => f.productId === productId)
}

const scrollToTop = () => {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

onMounted(async () => {
  await loadBanners()
  await loadProducts()
  const token = localStorage.getItem('token')
  if (token) {
    try {
      await userStore.fetchMe()
      if (userStore.role === 'CUSTOMER') {
        await Promise.all([loadFavorites(), loadCartCount()])
      }
    } catch (e) {
      userStore.profile = null
      localStorage.removeItem('token')
    }
  }
})
</script>
