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

      <div v-else>
        <div class="w-full mb-8 md:mb-12 lg:mb-16 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-2 md:gap-4 p-4 md:p-6 lg:p-8"
            >
              <div
                class="text-white text-xl sm:text-2xl md:text-3xl lg:text-4xl xl:text-6xl font-normal"
              >
                {{ t("products.product_list") }}
              </div>
              <div
                class="text-white text-xs sm:text-sm md:text-base lg:text-lg font-normal leading-relaxed md:leading-loose"
              >
                {{ t("products.product_list_description") }}
              </div>
            </div>
          </div>
          <img
            :src="banner"
            alt="products-banner"
            class="w-full object-cover h-40 sm:h-48 md:h-56 lg:h-64 xl:h-80"
          />
        </div>
        <div class="max-w-full mb-4 md:mb-6 lg:mb-8 xl:px-2 lg:px-2 md:px-4 px-4">
          <div class="max-w-screen-2xl mx-auto">
            <nuxt-link
              to="/"
              class="text-white/60 text-sm md:text-base font-normal hover:text-white transition-colors duration-300"
              >{{ t("common.home") }}</nuxt-link
            >
            <span class="text-white/60 text-sm md:text-base font-normal px-2"> / </span>
            <nuxt-link
              to="/products"
              class="text-white text-sm md:text-base font-normal"
              >{{ t("products.product_list") }}</nuxt-link
            >
          </div>
        </div>
        <div
          class="max-w-full mb-8 md:mb-12 lg:mb-16 xl:mb-20 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-4 md:gap-6 lg:gap-8">
              <div
                class="col-span-1 md:col-span-2 flex flex-col gap-8 md:gap-12 lg:gap-16 mb-6 md:mb-0"
              >
                <div class="flex flex-col gap-3 md:gap-4">
                  <div class="flex justify-between items-center">
                    <div class="text-white text-xl md:text-2xl lg:text-3xl font-medium">
                      {{ t("products.product_categories_title") }}
                    </div>
                    <button
                      v-if="selectedCategory"
                      @click="clearCategory"
                      class="flex items-center gap-1 px-2 py-1 md:px-3 md:py-1.5 text-xs md:text-sm text-white/60 hover:text-white bg-zinc-800/50 hover:bg-zinc-700/50 rounded-lg transition-all duration-300"
                    >
                      <span>{{ t("common.clear") }}</span>
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-3 w-3 md:h-4 md:w-4"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                          clip-rule="evenodd"
                        />
                      </svg>
                    </button>
                  </div>
                  <div class="flex flex-col gap-2 md:gap-3 w-fit">
                    <div
                      v-for="category in categories"
                      :key="category"
                      @click="handleCategoryFilter(category)"
                      class="opacity-80 select-none text-white text-sm md:text-base font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-3 py-1.5 md:px-4 md: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-3 md:gap-4">
                  <div class="flex justify-between items-center">
                    <div class="text-white text-xl md:text-2xl lg:text-3xl font-medium">
                      {{ t("products.product_categories_usage") }}
                    </div>
                    <button
                      v-if="selectedUsage"
                      @click="clearUsage"
                      class="flex items-center gap-1 px-2 py-1 md:px-3 md:py-1.5 text-xs md:text-sm text-white/60 hover:text-white bg-zinc-800/50 hover:bg-zinc-700/50 rounded-lg transition-all duration-300"
                    >
                      <span>{{ t("common.clear") }}</span>
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-3 w-3 md:h-4 md:w-4"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                          clip-rule="evenodd"
                        />
                      </svg>
                    </button>
                  </div>
                  <div class="flex flex-col gap-2 md:gap-3 w-fit">
                    <div
                      v-for="usage in usages"
                      :key="usage"
                      @click="handleUsageFilter(usage)"
                      class="opacity-80 select-none text-white text-sm md:text-base font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-3 py-1.5 md:px-4 md: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-8 md:gap-12 lg:gap-16">
                  <template v-for="category in categories" :key="category">
                    <div
                      v-if="
                        filteredProducts.filter((p) => {
                          const categoryObj = allCategories.find(
                            (c) => c.title === category
                          );
                          return categoryObj && p.categoryId === categoryObj.id;
                        }).length > 0
                      "
                      class="flex flex-col gap-4 md:gap-6"
                    >
                      <div class="w-full text-white text-2xl md:text-3xl lg:text-4xl font-normal mb-4 md:mb-6">
                        {{ category }}
                      </div>
                      
                      <!-- 添加系列分组 -->
                      <template v-for="[seriesName, seriesProducts] in Array.from(productsBySeries.entries())" :key="seriesName">
                        <div v-if="seriesProducts.some(p => {
                          const categoryObj = allCategories.find(c => c.title === category);
                          return categoryObj && p.categoryId === categoryObj.id;
                        })" class="mb-8 md:mb-12">
                          <div class="relative">
                            <!-- 系列标题背景 -->
                            <div class="absolute inset-0 bg-gradient-to-r from-blue-900/20 to-blue-500/20 rounded-lg transform -skew-x-6"></div>
                            
                            <!-- 系列标题内容 -->
                            <div class="relative flex items-center gap-3 md:gap-4 py-3 md:py-4 px-4 md:px-6">
                              <!-- 装饰线 -->
                              <div class="w-1 h-6 md:h-8 bg-gradient-to-b from-blue-500 to-blue-300 rounded-full"></div>
                              
                              <!-- 系列名称 -->
                              <h3 class="text-white text-lg md:text-xl lg:text-2xl font-medium tracking-wide">
                                {{ seriesName }}
                              </h3>
                              
                              <!-- 产品数量标签 -->
                              <div class="ml-auto px-2 py-0.5 md:px-3 md:py-1 bg-blue-500/20 rounded-full text-blue-300 text-xs md:text-sm">
                                {{ seriesProducts.length }} {{ t("products.product_count") }}
                              </div>
                            </div>
                          </div>
                          
                          <!-- 产品网格 -->
                          <div class="mt-4 md:mt-6">
                            <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-3 md:gap-4"
                            >
                              <nuxt-link
                                v-for="product in seriesProducts.filter(p => {
                                  const categoryObj = allCategories.find(c => c.title === category);
                                  return categoryObj && p.categoryId === categoryObj.id;
                                })"
                                :key="product.id"
                                :to="`/products/${product.name}`"
                                class="group 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 relative overflow-hidden"
                              >
                                <div class="w-full p-4 md:p-6 lg:p-8">
                                  <div class="relative w-full aspect-square mb-3 md:mb-4">
                                    <img
                                      v-if="!isImageError(product.id)"
                                      :src="product.image"
                                      :alt="product.name"
                                      class="w-full h-full object-cover rounded-lg transition-transform duration-300 group-hover:scale-110"
                                      @error="handleImageError($event, product)"
                                      @load="handleImageLoad($event, product)"
                                      loading="lazy"
                                    />
                                    <div
                                      v-if="isImageLoading(product.id)"
                                      class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 rounded-lg"
                                    >
                                      <div
                                        class="animate-spin h-6 w-6 md:h-8 md:w-8 border-4 border-blue-500 rounded-full border-t-transparent"
                                      ></div>
                                    </div>
                                    <div
                                      v-if="
                                        !product.image ||
                                        product.image === '' ||
                                        isImageError(product.id)
                                      "
                                      class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 rounded-lg"
                                    >
                                      <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        class="h-12 w-12 md:h-16 md:w-16 text-white/40"
                                        fill="none"
                                        viewBox="0 0 24 24"
                                        stroke="currentColor"
                                      >
                                        <path
                                          stroke-linecap="round"
                                          stroke-linejoin="round"
                                          stroke-width="2"
                                          d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                                        />
                                      </svg>
                                    </div>
                                  </div>
                                  <div class="text-center text-white text-base md:text-lg lg:text-xl font-normal mb-2">
                                    {{ product.name }}
                                  </div>
                                  <div class="text-center text-stone-400 text-sm md:text-base font-normal leading-normal">
                                    {{ product.capacities.join(" / ") }}
                                  </div>
                                  
                                  <!-- Summary 悬浮层 -->
                                  <div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-end">
                                    <div class="p-4 md:p-6 w-full">
                                      <div class="text-white text-sm md:text-base line-clamp-3">
                                        {{ product.summary }}
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </nuxt-link>
                            </transition-group>
                          </div>
                        </div>
                      </template>
                      
                      <!-- 展示没有系列的产品 -->
                      <transition-group
                        v-if="filteredProducts.filter(p => {
                          const categoryObj = allCategories.find(c => c.title === category);
                          return categoryObj && p.categoryId === categoryObj.id && (!p.series || p.series.length === 0);
                        }).length > 0"
                        name="fade"
                        tag="div"
                        class="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 md:gap-4"
                      >
                        <nuxt-link
                          v-for="product in filteredProducts.filter(p => {
                            const categoryObj = allCategories.find(c => c.title === category);
                            return categoryObj && p.categoryId === categoryObj.id && (!p.series || p.series.length === 0);
                          })"
                          :key="product.id"
                          :to="`/products/${product.name}`"
                          class="group 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 relative overflow-hidden"
                        >
                          <div class="w-full p-4 md:p-6 lg:p-8">
                            <div class="relative w-full aspect-square mb-3 md:mb-4">
                              <img
                                v-if="!isImageError(product.id)"
                                :src="product.image"
                                :alt="product.name"
                                class="w-full h-full object-cover rounded-lg transition-transform duration-300 group-hover:scale-110"
                                @error="handleImageError($event, product)"
                                @load="handleImageLoad($event, product)"
                                loading="lazy"
                              />
                              <div
                                v-if="isImageLoading(product.id)"
                                class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 rounded-lg"
                              >
                                <div
                                  class="animate-spin h-6 w-6 md:h-8 md:w-8 border-4 border-blue-500 rounded-full border-t-transparent"
                                ></div>
                              </div>
                              <div
                                v-if="
                                  !product.image ||
                                  product.image === '' ||
                                  isImageError(product.id)
                                "
                                class="absolute inset-0 flex items-center justify-center bg-zinc-800/50 rounded-lg"
                              >
                                <svg
                                  xmlns="http://www.w3.org/2000/svg"
                                  class="h-12 w-12 md:h-16 md:w-16 text-white/40"
                                  fill="none"
                                  viewBox="0 0 24 24"
                                  stroke="currentColor"
                                >
                                  <path
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                                  />
                                </svg>
                              </div>
                            </div>
                            <div class="text-center text-white text-base md:text-lg lg:text-xl font-normal mb-2">
                              {{ product.name }}
                            </div>
                            <div class="text-center text-stone-400 text-sm md:text-base font-normal leading-normal">
                              {{ product.capacities.join(" / ") }}
                            </div>
                            
                            <!-- Summary 悬浮层 -->
                            <div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-all duration-300 flex items-end">
                              <div class="p-4 md:p-6 w-full">
                                <div class="text-white text-sm md:text-base line-clamp-3">
                                  {{ product.summary }}
                                </div>
                              </div>
                            </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";
import { useI18n } from "vue-i18n";
import { queryCollection } from "#imports";
import { useRoute, useRouter } from "vue-router";
import { useDebounceFn } from "@vueuse/core";

const { t, locale } = useI18n();
const route = useRoute();
const router = useRouter();

// 产品接口定义
interface Product {
  id: number;
  name: string;
  title: string;
  categoryId: number;
  usage: string[];
  series: string[];
  capacities: string[];
  image: string;
  description?: string;
  summary: string;
  gallery: string[];
  sort: number;
}

interface Category {
  id: number;
  title: string;
  description?: string;
  image: string;
  summary: string;
  capacities: string[];
  sort: number;
}

// 分页配置
const PAGE_SIZE = 100;
const currentPage = ref(1);
const totalPages = ref(1);

// 使用防抖优化路由更新
const debouncedRouterPush = useDebounceFn(
  (query: Record<string, string | undefined>) => {
    router.push({ query });
  },
  300
);

const { error, isLoading, wrapAsync } = useErrorHandler();
const allProducts = ref<Product[]>([]);
const allCategories = ref<Category[]>([]);
const filteredProducts = ref<Product[]>([]);
const categories = ref<string[]>([]);
const usages = ref<string[]>([]);
const selectedCategory = ref(route.query.category?.toString() || "");
const selectedUsage = ref(route.query.usage?.toString() || "");

// 使用缓存优化数据加载
const { data: productData } = await useAsyncData("products", async () => {
  try {
    const content = await queryCollection("content").all();
    const products = content
      .filter((item: any) => {
        const isProduct =
          item.path?.includes("/products/") &&
          !item.path?.includes("/categories/") &&
          item.path?.includes(`/${locale.value}/`);
        return isProduct;
      })
      .map((item: any, index: number) => {
        const meta = item.meta || item.frontmatter || {};
        const pathId = item.path?.match(/\/products\/(\d+)/)?.[1];
        return {
          id: pathId ? parseInt(pathId) : index + 1,
          name: meta.name || item.title || "",
          title: item.title || "",
          categoryId: parseInt(meta.categoryId?.toString() || "0"),
          usage: meta.usage || [],
          series: meta.series || [],
          capacities: meta.capacities || [],
          image: meta.image || "",
          description: meta.description || "",
          summary: meta.summary || "",
          gallery: meta.gallery || [],
          sort: meta.sort || 0,
        };
      })
      .sort((a, b) => a.sort - b.sort);

    // 计算总页数
    totalPages.value = Math.ceil(products.length / PAGE_SIZE);
    return products;
  } catch (error) {
    console.error("Error loading product content:", error);
    return [];
  }
});

// 使用缓存优化类别数据加载
const { data: categoryData } = await useAsyncData("categories", async () => {
  try {
    const content = await queryCollection("content").all();
    return content
      .filter((item: any) => {
        const isCategory =
          item.path?.includes("/categories/") &&
          item.path?.includes(`/${locale.value}/`);
        return isCategory;
      })
      .map((item: any, index: number) => {
        const meta = item.meta || item.frontmatter || {};
        const pathId = item.path?.match(/\/categories\/(\d+)/)?.[1];
        return {
          id: pathId ? parseInt(pathId) : index + 1,
          title: meta.title || item.title || "",
          description: meta.description || "",
          image: meta.image || "",
          summary: meta.summary || "",
          capacities: meta.capacities || [],
          sort: meta.sort || 0,
        };
      })
      .sort((a, b) => a.sort - b.sort);
  } catch (error) {
    console.error("Error loading category content:", error);
    return [];
  }
});

// 使用计算属性优化数据过滤
const filteredProductsByCategory = computed(() => {
  if (!selectedCategory.value) return allProducts.value;

  const category = allCategories.value.find(
    (c: Category) => c.title === selectedCategory.value
  );
  if (!category) return allProducts.value;

  return allProducts.value.filter((p: Product) => p.categoryId === category.id);
});

const filteredProductsByUsage = computed(() => {
  if (!selectedUsage.value) return filteredProductsByCategory.value;
  return filteredProductsByCategory.value.filter((p: Product) =>
    p.usage.includes(selectedUsage.value)
  );
});

// 分页后的产品列表
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * PAGE_SIZE;
  const end = start + PAGE_SIZE;
  return filteredProductsByUsage.value.slice(start, end);
});

// 使用计算属性优化用途列表
const uniqueUsages = computed(() => {
  const usageSet = new Set<string>();
  allProducts.value.forEach((product: Product) => {
    product.usage.forEach((u: string) => usageSet.add(u));
  });
  return Array.from(usageSet);
});

// 使用计算属性优化类别列表
const categoryTitles = computed(() =>
  allCategories.value.map((c: Category) => c.title)
);

// 使用计算属性优化系列分组
const productsBySeries = computed(() => {
  const seriesMap = new Map<string, Product[]>();
  
  filteredProducts.value.forEach((product: Product) => {
    if (product.series && product.series.length > 0) {
      const series = product.series[0]; // 取第一个系列作为分组依据
      if (!seriesMap.has(series)) {
        seriesMap.set(series, []);
      }
      seriesMap.get(series)?.push(product);
    }
  });
  
  return seriesMap;
});

// 处理数据变化
watchEffect(() => {
  if (!productData.value || !categoryData.value) return;

  isLoading.value = true;
  try {
    allProducts.value = productData.value;
    allCategories.value = categoryData.value;
    usages.value = uniqueUsages.value;
    categories.value = categoryTitles.value;
    filteredProducts.value = paginatedProducts.value;
  } catch (err) {
    console.error("Error processing data:", err);
    error.value = new Error(t("products.processError"));
  } finally {
    isLoading.value = false;
  }
});

/**
 * 处理分类筛选
 */
function handleCategoryFilter(category: string) {
  selectedCategory.value = selectedCategory.value === category ? "" : category;
  currentPage.value = 1; // 重置页码
  filteredProducts.value = paginatedProducts.value;
}

/**
 * 处理用途筛选
 */
function handleUsageFilter(usage: string) {
  selectedUsage.value = selectedUsage.value === usage ? "" : usage;
  currentPage.value = 1; // 重置页码
  filteredProducts.value = paginatedProducts.value;
}

/**
 * 处理页码变化
 */
function handlePageChange(page: number) {
  currentPage.value = page;
  filteredProducts.value = paginatedProducts.value;
}

// 监听分类变化
watch(selectedCategory, (newValue) => {
  debouncedRouterPush({
    ...route.query,
    category: newValue || undefined,
  });
});

// 监听用途变化
watch(selectedUsage, (newValue) => {
  debouncedRouterPush({
    ...route.query,
    usage: newValue || undefined,
  });
});

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    selectedCategory.value = newQuery.category?.toString() || "";
    selectedUsage.value = newQuery.usage?.toString() || "";
    const page = parseInt(newQuery.page?.toString() || "1");
    if (page !== currentPage.value) {
      currentPage.value = page;
    }
  },
  { deep: true }
);

// 重置筛选条件
const resetFilters = () => {
  selectedCategory.value = "";
  selectedUsage.value = "";
  currentPage.value = 1;
  debouncedRouterPush({});
};

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

const fallbackImage = "/images/placeholder.jpg";

// 图片加载状态管理
const loadingImages = ref<Set<number>>(new Set());
const errorImages = ref<Set<number>>(new Set());

// 检查图片是否正在加载
const isImageLoading = (productId: number) => {
  return loadingImages.value.has(productId);
};

// 检查图片是否加载错误
const isImageError = (productId: number) => {
  return errorImages.value.has(productId);
};

// 处理图片加载开始
const handleImageLoadStart = (productId: number) => {
  loadingImages.value.add(productId);
  errorImages.value.delete(productId);
};

// 处理图片加载完成
const handleImageLoad = (event: Event, product: Product) => {
  loadingImages.value.delete(product.id);
  errorImages.value.delete(product.id);
};

// 处理图片加载错误
const handleImageError = (event: Event, product: Product) => {
  console.warn(`Image load failed for product: ${product.title}`);
  if (event.target instanceof HTMLImageElement) {
    loadingImages.value.delete(product.id);
    errorImages.value.add(product.id);
  }
};

// 清除分类筛选
const clearCategory = () => {
  selectedCategory.value = "";
  currentPage.value = 1;
  filteredProducts.value = paginatedProducts.value;
  debouncedRouterPush({
    ...route.query,
    category: undefined,
  });
};

// 清除用途筛选
const clearUsage = () => {
  selectedUsage.value = "";
  currentPage.value = 1;
  filteredProducts.value = paginatedProducts.value;
  debouncedRouterPush({
    ...route.query,
    usage: undefined,
  });
};

// 组件卸载时清理资源
onBeforeUnmount(() => {
  allProducts.value = [];
  allCategories.value = [];
  filteredProducts.value = [];
  categories.value = [];
  usages.value = [];
  loadingImages.value.clear();
  errorImages.value.clear();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 系列标题悬停效果 */
.relative:hover .bg-gradient-to-r {
  @apply from-blue-900/30 to-blue-500/30;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 产品数量标签悬停效果 */
.relative:hover .bg-blue-500\/20 {
  @apply bg-blue-500/30;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 装饰线动画效果 */
.relative:hover .w-1 {
  @apply h-10;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.products-page {
  min-height: 100vh;
  background-color: #f9fafb;
}

/* 添加过渡动画 */
.bg-primary {
  @apply bg-blue-600;
}

button {
  transition: all 0.3s ease;
}

.rounded-full {
  @apply transition-all duration-300 ease-in-out;
}

.rounded-full:hover {
  @apply bg-gray-200;
}

/* 添加清除按钮悬停效果 */
button:hover {
  transform: translateY(-1px);
}

/* 添加图片容器过渡效果 */
.aspect-square {
  transition: all 0.3s ease;
  background-color: rgb(39, 39, 42); /* 添加背景色 */
}

.aspect-square:hover {
  transform: scale(1.02);
}

/* 加载动画优化 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式间距调整 */
@media (max-width: 640px) {
  .gap-4 {
    gap: 0.75rem;
  }
  .p-4 {
    padding: 0.75rem;
  }
}

@media (min-width: 768px) {
  .gap-4 {
    gap: 1rem;
  }
  .p-4 {
    padding: 1rem;
  }
}

@media (min-width: 1024px) {
  .gap-4 {
    gap: 1.25rem;
  }
  .p-4 {
    padding: 1.5rem;
  }
}

/* 添加新的样式 */
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 优化过渡动画 */
.group {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.group:hover {
  transform: translateY(-4px);
}

/* 图片缩放效果 */
.group img {
  transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Summary 悬浮层动画 */
.group .absolute {
  transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 确保文字在悬浮层上清晰可见 */
.group .text-white {
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

/* 响应式调整 */
@media (max-width: 640px) {
  .group .absolute {
    padding: 0.75rem;
  }
}

@media (min-width: 768px) {
  .group .absolute {
    padding: 1rem;
  }
}

@media (min-width: 1024px) {
  .group .absolute {
    padding: 1.5rem;
  }
}
</style>
