<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-cyan-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-8 lg:px-6 md:px-4 px-4"
        >
          <div class="max-w-screen-2xl mx-auto">
            <nuxt-link
              :to="`${homepagePath}/`"
              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="`${homepagePath}/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-8 lg:px-6 md:px-4 px-4"
        >
          <div class="max-w-screen-2xl mx-auto">
            <div class="w-full grid grid-cols-1 md:grid-cols-12 gap-4">
              <div
                class="sticky top-24 col-span-1 md:col-span-3 flex flex-col gap-4 sm:gap-6 md:gap-8 lg:gap-10 xl:gap-12 2xl:gap-16 mb-4 sm:mb-6 md:mb-8 lg:mb-10 xl:mb-12 2xl:mb-16 pr-4"
              >
                <div
                  class="flex flex-col gap-2 sm:gap-3 md:gap-4 lg:gap-5 xl:gap-6"
                >
                  <div class="flex justify-between items-center">
                    <div
                      class="text-white text-base sm:text-lg md:text-xl lg:text-2xl xl:text-3xl font-medium"
                    >
                      {{ t("products.product_categories_title") }}
                    </div>
                    <button
                      v-if="selectedCategory"
                      @click="clearCategory"
                      class="flex items-center gap-1 px-1.5 py-0.5 sm:px-2 sm:py-1 md:px-2.5 md:py-1.5 lg:px-3 lg:py-2 text-xs sm:text-sm md:text-base text-white/60 hover:text-white bg-zinc-800/50 hover:bg-zinc-700/50 rounded-lg transition-all duration-300 active:scale-95"
                      v-show="false"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-2.5 w-2.5 sm:h-3 sm: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-row md:flex-col gap-1.5 sm:gap-2 md:gap-2.5 lg:gap-3 xl:gap-4 w-full md:w-fit overflow-x-auto md:overflow-x-visible pb-2 md:pb-0 whitespace-nowrap md:whitespace-normal"
                  >
                    <div
                      v-for="category in categories"
                      :key="category"
                      @click="handleCategoryFilter(category)"
                      class="select-none text-white text-xs sm:text-sm md:text-base lg:text-lg font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-2 py-1 sm:px-2.5 sm:py-1.5 md:px-3 md:py-2 lg:px-4 lg:py-2.5 rounded-lg inline-block active:scale-95 whitespace-nowrap"
                      :class="{
                        'font-bold bg-cyan-400 text-zinc-900 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-col gap-2 sm:gap-3 md:gap-4 lg:gap-5 xl:gap-6 hidden"
                >
                  <div class="flex justify-between items-center">
                    <div
                      class="text-white text-base sm:text-lg md:text-xl lg:text-2xl xl:text-3xl font-medium"
                    >
                      {{ t("products.product_categories_usage") }}
                    </div>
                    <button
                      v-if="selectedUsage"
                      @click="clearUsage"
                      class="flex items-center gap-1 px-1.5 py-0.5 sm:px-2 sm:py-1 md:px-2.5 md:py-1.5 lg:px-3 lg:py-2 text-xs sm:text-sm md:text-base text-white/60 hover:text-white bg-zinc-800/50 hover:bg-zinc-700/50 rounded-lg transition-all duration-300 active:scale-95"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-2.5 w-2.5 sm:h-3 sm: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-row md:flex-col gap-1.5 sm:gap-2 md:gap-2.5 lg:gap-3 xl:gap-4 w-full md:w-fit overflow-x-auto md:overflow-x-visible pb-2 md:pb-0 whitespace-nowrap md:whitespace-normal"
                  >
                    <div
                      v-for="usage in usages"
                      :key="usage"
                      @click="handleUsageFilter(usage)"
                      class="opacity-80 select-none text-white text-xs sm:text-sm md:text-base lg:text-lg font-normal cursor-pointer hover:opacity-100 transition-all duration-300 px-2 py-1 sm:px-2.5 sm:py-1.5 md:px-3 md:py-2 lg:px-4 lg:py-2.5 rounded-lg inline-block active:scale-95"
                      :class="{
                        'opacity-100 font-bold bg-cyan-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-9">
                <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>

                      <div
                        v-if="
                          getCategoryTags(category)?.length > 0 &&
                          selectedCategory
                        "
                        class="flex flex-wrap gap-4"
                      >
                        <span
                          @click="selectTag('all')"
                          class="text-white text-sm md:text-lg font-normal px-4 py-2 bg-zinc-800/50 rounded-lg cursor-pointer hover:bg-zinc-700/50 transition-all duration-300"
                          :class="{
                            '!bg-cyan-400 text-zinc-900 font-medium':
                              selectedTag === 'all',
                          }"
                        >
                          {{ t("common.all") }}
                        </span>
                        <span
                          v-for="tag in getCategoryTags(category)"
                          :key="tag"
                          @click="selectTag(tag)"
                          class="text-white text-sm md:text-lg font-normal px-4 py-2 bg-zinc-800/50 rounded-lg cursor-pointer hover:bg-zinc-700/50 transition-all duration-300"
                          :class="{
                            '!bg-cyan-400 text-zinc-900 font-medium':
                              selectedTag === tag,
                          }"
                        >
                          {{ tag }}
                        </span>
                      </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 &&
                                (selectedTag === 'all' || p.tag === selectedTag)
                              );
                            })
                          "
                          class="mb-8 md:mb-12"
                        >
                          <div class="relative">
                            <!-- 系列标题背景 -->
                            <div
                              class="absolute inset-0 bg-gradient-to-r from-cyan-900/20 to-cyan-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-cyan-400 text-zinc-900 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-cyan-500/20 rounded-full text-cyan-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-2 sm:grid-cols-2 md:grid-cols-3 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 &&
                                    (selectedTag === 'all' ||
                                      p.tag === selectedTag)
                                  );
                                })"
                                :key="product.id"
                                :to="`${homepagePath}/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-cyan-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-cyan-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-[#71717A] 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) &&
                              (selectedTag === 'all' || p.tag === selectedTag)
                            );
                          }).length > 0
                        "
                        name="fade"
                        tag="div"
                        class="w-full grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 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) &&
                              (selectedTag === 'all' || p.tag === selectedTag)
                            );
                          })"
                          :key="product.id"
                          :to="`${homepagePath}/products/${product.name}`"
                          class="group bg-zinc-900 rounded-lg transition-all duration-300 hover:bg-zinc-800 hover:shadow-lg hover:ring-2 hover:ring-cyan-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-cyan-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-[#71717A] 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();

const homepagePath = computed(() => {
  return locale.value === "zh" ? "" : `/${locale.value}`;
});

// 产品接口定义
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;
  tag: string;
}

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

// 分页配置
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 selectedTag = ref(route.query.tag?.toString() || "all");

const getCategoryTags = (category: string) => {
  const categoryObj = allCategories.value.find((c) => c.title === category);
  return categoryObj?.tags || [];
};

// 使用缓存优化数据加载
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,
          tag: meta.tag || "",
        };
      })
      .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,
          tags: meta.tags || [],
        };
      })
      .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;

    // 验证URL参数中的分类和标签是否有效
    if (selectedCategory.value) {
      const categoryExists = allCategories.value.some(
        (c: Category) => c.title === selectedCategory.value
      );

      if (!categoryExists) {
        // 如果分类不存在于当前语言环境，清除分类和标签参数
        selectedCategory.value = "";
        selectedTag.value = "all";

        // 更新路由，移除无效的参数
        router.replace({
          query: {
            ...route.query,
            category: undefined,
            tag: undefined,
          },
        });
      } else if (selectedTag.value !== "all") {
        // 检查标签是否在当前分类中存在
        const categoryTags = getCategoryTags(selectedCategory.value);
        if (!categoryTags.includes(selectedTag.value)) {
          selectedTag.value = "all";

          // 更新路由，移除无效的标签参数
          router.replace({
            query: {
              ...route.query,
              tag: undefined,
            },
          });
        }
      }
    }
  } 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 = category;
  // 切换分类时，重置tag选择为'all'
  selectedTag.value = "all";
  currentPage.value = 1; // 重置页码
  filteredProducts.value = paginatedProducts.value;

  // 更新路由，移除tag参数
  router.push({
    query: {
      ...route.query,
      category: category,
      tag: undefined, // 清除tag参数
      page: currentPage.value > 1 ? currentPage.value.toString() : undefined,
    },
  });
}

/**
 * 处理用途筛选
 */
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) => {
    // 先保存当前的值，方便后续比较变化
    const prevCategory = selectedCategory.value;
    const prevTag = selectedTag.value;

    // 更新本地状态
    selectedCategory.value = newQuery.category?.toString() || "";
    selectedUsage.value = newQuery.usage?.toString() || "";
    selectedTag.value = newQuery.tag?.toString() || "all";
    const page = parseInt(newQuery.page?.toString() || "1");
    if (page !== currentPage.value) {
      currentPage.value = page;
    }

    // 如果数据已加载完成，则验证URL参数的有效性
    if (allCategories.value.length > 0 && allProducts.value.length > 0) {
      // 检查分类是否有效
      if (selectedCategory.value && prevCategory !== selectedCategory.value) {
        const categoryExists = allCategories.value.some(
          (c: Category) => c.title === selectedCategory.value
        );

        if (!categoryExists) {
          // 如果分类不存在，重置选择并更新路由
          selectedCategory.value = "";
          selectedTag.value = "all";

          // 使用replace而不是push，避免在历史记录中添加新条目
          router.replace({
            query: {
              ...route.query,
              category: undefined,
              tag: undefined,
            },
          });
          return; // 提前退出，因为后续更新将由新的路由触发
        }
      }

      // 检查标签是否有效（仅当有选中分类时）
      if (
        selectedCategory.value &&
        selectedTag.value !== "all" &&
        prevTag !== selectedTag.value
      ) {
        const categoryTags = getCategoryTags(selectedCategory.value);
        if (!categoryTags.includes(selectedTag.value)) {
          selectedTag.value = "all";

          router.replace({
            query: {
              ...route.query,
              tag: undefined,
            },
          });
        }
      }
    }
  },
  { deep: true }
);

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

// SEO优化
useHead({
  title: `${t("products.title")} - Hanye`,
  meta: [
    {
      name: "description",
      content: `${t("products.description")}`,
    },
  ],
});

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);
  }
};

// 清除分类筛选 (已经隐藏按钮)
function 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,
  });
};

// 选择标签进行筛选
function selectTag(tag: string) {
  selectedTag.value = tag;

  // 更新路由查询参数
  router.push({
    query: {
      ...route.query,
      tag: tag === "all" ? undefined : tag,
    },
  });
}

// 组件卸载时清理资源
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-cyan-900/30 to-cyan-500/30;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 产品数量标签悬停效果 */
.relative:hover .bg-cyan-500\/20 {
  @apply bg-cyan-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-cyan-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;
  }
}

/* 导航栏样式优化 */
.bg-zinc-900\/50 {
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
}

/* 导航项悬停效果 */
.group:hover {
  transform: translateX(4px);
}

/* 清除按钮动画 */
button {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

button:active {
  transform: translateY(0);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .bg-zinc-900\/50 {
    padding: 1rem;
  }

  .group:hover {
    transform: translateX(2px);
  }
}

@media (min-width: 768px) {
  .bg-zinc-900\/50 {
    padding: 1.5rem;
  }
}

@media (min-width: 1024px) {
  .bg-zinc-900\/50 {
    padding: 2rem;
  }
}

/* 优化点击反馈 */
.active\:scale-95:active {
  transform: scale(0.95);
}

/* 优化过渡动画 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 150ms;
}

/* 优化横向滚动 */
.overflow-x-auto {
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.overflow-x-auto::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

/* 响应式断点说明：
sm: 640px
md: 768px
lg: 1024px
xl: 1280px
2xl: 1536px
*/
</style>
