<template>
  <div>
    <div class="w-full h-[55px] sm:h-[72px]"></div>
    <ErrorBoundary :error="error">
      <div v-if="isLoading" class="flex justify-center py-12">
        <!-- 加载中 -->
        <div
          class="animate-spin h-8 w-8 border-4 border-blue-500 rounded-full border-t-transparent"
        ></div>
      </div>

      <div v-else>
        <div class="w-full mb-12 relative">
          <div class="absolute top-0 left-0 w-full h-full z-10">
            <div
              class="max-w-screen-2xl mx-auto h-full flex flex-col justify-center gap-4 p-4"
            >
              <div
                class="justify-start text-white text-2xl font-normal md:text-4xl lg:text-6xl"
              >
                {{ $t("products.product_list") }}
              </div>
              <div
                class="text-white text-sm lg:text-lg font-normal leading-loose"
              >
                {{ $t("products.product_list_description") }}
              </div>
            </div>
          </div>
          <img
            :src="banner"
            alt="products-banner"
            class="w-full object-cover h-60 lg:h-full"
          />
        </div>
        <div class="max-w-full mb-6 xl:px-2 lg:px-2 md:px-4 px-4">
          <div class="max-w-screen-2xl mx-auto">
            <nuxt-link
              to="/"
              class="justify-start text-white/60 text-base font-normal"
              >{{ $t("common.home") }}</nuxt-link
            >
            <span class="text-white/60 text-base font-normal px-2"> / </span>
            <nuxt-link
              to="/products"
              class="text-white text-base font-normal"
              >{{ $t("products.product_list") }}</nuxt-link
            >
          </div>
        </div>
        <div
          class="max-w-full mb-12 md:mb-20 lg:mb-32 xl:px-2 lg:px-2 md:px-4 px-4"
        >
          <div class="max-w-screen-2xl mx-auto">
            <div class="w-full grid grid-cols-1 md:grid-cols-10 gap-8 md:gap-2">
              <div
                class="col-span-1 md:col-span-2 flex flex-col gap-16 mb-8 md:mb-0"
              >
                <div class="flex flex-col gap-4">
                  <div class="text-white text-3xl font-medium">
                    {{ $t("products.product_categories_title") }}
                  </div>
                  <div class="flex flex-col gap-4 w-fit">
                    <div
                      v-for="category in categories"
                      :key="category"
                      @click="handleCategoryFilter(category)"
                      class="opacity-80 justify-start text-white text-base font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-4 py-2 rounded-lg inline-block"
                      :class="{
                        'opacity-100 font-bold bg-gradient-to-r from-blue-700 to-blue-400 text-white border-0 shadow-lg scale-105 transition-all duration-300':
                          selectedCategory === category,
                        'hover:bg-zinc-800/50': selectedCategory !== category,
                      }"
                    >
                      {{ category }}
                    </div>
                  </div>
                </div>

                <div class="flex flex-col gap-4">
                  <div class="text-white text-3xl font-medium">
                    {{ $t("products.product_categories_usage") }}
                  </div>
                  <div class="flex flex-col gap-4 w-fit">
                    <div
                      v-for="usage in usages"
                      :key="usage"
                      @click="handleUsageFilter(usage)"
                      class="opacity-80 justify-start text-white text-base font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-4 py-2 rounded-lg inline-block"
                      :class="{
                        'opacity-100 font-bold bg-gradient-to-r from-blue-700 to-blue-400 text-white border-0 shadow-lg scale-105 transition-all duration-300':
                          selectedUsage === usage,
                        'hover:bg-zinc-800/50': selectedUsage !== usage,
                      }"
                    >
                      {{ usage }}
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-span-1 md:col-span-8">
                <div class="flex flex-col gap-16">
                  <template v-for="category in categories" :key="category">
                    <div
                      v-if="
                        filteredProducts.filter((p) => p.category === category)
                          .length > 0
                      "
                      class="flex flex-col gap-4"
                    >
                      <div class="w-full text-white text-4xl font-normal mb-4">
                        {{ category }}
                      </div>
                      <transition-group
                        name="fade"
                        tag="div"
                        class="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
                      >
                        <nuxt-link
                          v-for="product in filteredProducts.filter(
                            (p) => p.category === category
                          )"
                          :key="product.id"
                          :to="`/products/${product.id}`"
                          class="bg-zinc-900 rounded-lg transition-all duration-300 hover:bg-zinc-800 hover:scale-105 hover:shadow-lg hover:ring-2 hover:ring-blue-400"
                        >
                          <div class="w-full p-8">
                            <img
                              :src="product.image"
                              :alt="product.name"
                              class="w-full h-full object-cover rounded-lg mb-4"
                            />
                            <div
                              class="text-center justify-start text-white text-xl font-normal"
                            >
                              {{ product.name }}
                            </div>
                            <div
                              class="text-center justify-start text-stone-400 text-base font-normal leading-normal"
                            >
                              {{ product.capacities.join(" / ") }}
                            </div>
                          </div>
                        </nuxt-link>
                      </transition-group>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  </div>
</template>

<script setup lang="ts">
/**
 * 产品列表页面
 * 展示所有产品，支持按分类和用途筛选
 */
import { useErrorHandler } from "~/composables/useErrorHandler";
import banner from "@/assets/images/product-banner.webp";

// 产品接口定义
interface Product {
  id: number;
  name: string;
  category: string;
  usage: string;
  capacities: string[];
  image: string;
  description: string;
}

interface ProductResponse {
  products: Product[];
  categories: string[];
  usages: string[];
}

const { error, isLoading, wrapAsync } = useErrorHandler();
const allProducts = ref<Product[]>([]);
const filteredProducts = ref<Product[]>([]);
const categories = ref<string[]>([]);
const usages = ref<string[]>([]);
const selectedCategory = ref<string>("");
const selectedUsage = ref<string>("");

/**
 * 加载产品数据
 */
async function loadProducts() {
  await wrapAsync(async () => {
    const response = await $fetch<ProductResponse>("/api/products");
    allProducts.value = response.products;
    categories.value = response.categories;
    usages.value = response.usages;
    filterProducts();
    return response;
  });
}

/**
 * 本地筛选产品
 */
function filterProducts() {
  let result = [...allProducts.value];
  if (selectedCategory.value) {
    result = result.filter((p) => p.category === selectedCategory.value);
  }
  if (selectedUsage.value) {
    result = result.filter((p) => p.usage === selectedUsage.value);
  }
  filteredProducts.value = result;
}

/**
 * 处理分类筛选
 */
function handleCategoryFilter(category: string) {
  selectedCategory.value = selectedCategory.value === category ? "" : category;
  filterProducts();
}

/**
 * 处理用途筛选
 */
function handleUsageFilter(usage: string) {
  selectedUsage.value = selectedUsage.value === usage ? "" : usage;
  filterProducts();
}

// 页面加载时获取产品数据
onMounted(() => {
  loadProducts();
});

// SEO优化
useHead({
  title: "产品列表 - Hanye",
  meta: [
    {
      name: "description",
      content: "浏览我们的产品列表，找到适合您的解决方案。",
    },
  ],
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
