<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="max-w-full xl:px-2 lg:px-2 md:px-4 px-4 mt-6 mb-20">
          <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="/faq" class="text-white text-base font-normal">{{
              t("faq.title")
            }}</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">
                <div class="flex flex-col gap-4">
                  <div class="text-white text-3xl font-medium">
                    {{ t("faq.category") }}
                  </div>
                  <div class="flex flex-col gap-4 w-fit">
                    <div
                      v-for="category in categoriesList"
                      :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>

              <!-- 右侧FAQ列表 -->
              <div class="col-span-1 md:col-span-8">
                <!-- 搜索框 -->
                <div class="mb-8 relative">
                  <input
                    v-model="searchTerm"
                    ref="searchInputRef"
                    type="search"
                    :placeholder="t('faq.searchPlaceholder')"
                    class="block w-full appearance-none rounded-lg border border-gray-600 bg-zinc-800/70 px-4 py-3 text-base text-gray-100 placeholder-gray-400 shadow-inner transition duration-200 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:ring-offset-2 focus:ring-offset-zinc-900"
                  />
                  <button
                    v-if="searchTerm"
                    @click="clearSearch"
                    class="absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center w-8 h-8 rounded-full bg-zinc-700/80 hover:bg-blue-500/90 text-gray-300 hover:text-white transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                    :aria-label="t('faq.clearSearch')"
                    tabindex="0"
                    type="button"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      class="h-5 w-5"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M6 18L18 6M6 6l12 12"
                      />
                    </svg>
                  </button>
                </div>
                <div class="flex flex-col gap-8">
                  <div
                    v-for="faq in filteredFaqs"
                    :key="generateFaqKey(faq)"
                    class="bg-zinc-900 rounded-lg p-8 transition-all duration-300 hover:bg-zinc-800 hover:shadow-lg"
                  >
                    <div
                      class="flex items-center justify-between cursor-pointer"
                      @click="toggleFaq(faq)"
                    >
                      <div class="text-white text-xl font-medium">
                        <template
                          v-for="(part, i) in highlightKeyword(faq.question)"
                          :key="i"
                        >
                          <span v-if="typeof part === 'string'">{{
                            part
                          }}</span>
                          <component v-else :is="part"></component>
                        </template>
                      </div>
                      <div
                        class="text-white text-2xl transition-transform duration-300"
                        :class="{ 'rotate-180': isFaqExpanded(faq) }"
                      >
                        ▼
                      </div>
                    </div>
                    <div
                      v-if="isFaqExpanded(faq)"
                      class="mt-4 text-white/80 text-base font-normal leading-relaxed"
                    >
                      <template
                        v-for="(part, i) in highlightKeyword(faq.answer)"
                        :key="i"
                      >
                        <span v-if="typeof part === 'string'">{{ part }}</span>
                        <component v-else :is="part"></component>
                      </template>
                    </div>
                  </div>
                  <div
                    v-if="filteredFaqs.length === 0"
                    class="text-center text-gray-400 py-8"
                  >
                    {{ t("faq.noResults") }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  </div>
</template>

<script setup lang="ts">
/**
 * FAQ页面
 * 展示常见问题及其答案
 */
import { useErrorHandler } from "~/composables/useErrorHandler";
import { queryCollection } from '#imports'

const { error, isLoading, wrapAsync } = useErrorHandler();
const { t, locale } = useI18n();

// FAQ数据
interface FAQ {
  id: string;
  category: string;
  question: string;
  answer: string;
  title: string;
  description: string;
  sort: number;
}

// 从content目录读取FAQ数据
const faqs = ref<FAQ[]>([]);
const categoriesList = ref<string[]>([]);

// 选中的分类
const selectedCategory = ref("");

// 使用 queryCollection 加载FAQ数据
const { data: faqData } = await useAsyncData('faqs', async () => {
  console.log('Loading FAQ data for locale:', locale.value);
  try {
    // 使用 queryCollection 加载 FAQ 数据
    const content = await queryCollection("content")
      .where("path", "LIKE", `/faq/${locale.value}/%`)
      .all();
    
    if (!content || !Array.isArray(content)) {
      console.error('No FAQ content found or invalid format:', content);
      return [];
    }
    
    console.log('Raw FAQ data:', content);
    
    // 转换数据格式
    const faqItems = content.map((item: any) => {
      // 提取路径中的ID
      const pathParts = item.path?.split('/');
      const id = pathParts?.[pathParts.length - 1] || '';
      
      return {
        id: id,
      category: item.category || '',
      question: item.title || '',
        answer: item.body || '',
      title: item.title || '',
      description: item.description || '',
      sort: item.sort || 0
      };
    });
    
    console.log('Processed FAQ items:', faqItems);
    
    // 按 sort 字段排序
    return faqItems.sort((a, b) => a.sort - b.sort);
  } catch (error) {
    console.error('Error loading FAQ content:', error);
    return [];
  }
}, {
  // 确保数据在构建时生成
  server: true,
  lazy: false,
  immediate: true,
  watch: [locale]
});

// 处理FAQ数据变化
watchEffect(() => {
  if (faqData.value) {
    isLoading.value = true;
    try {
      console.log('Processing FAQ data:', faqData.value);
      
      // 设置分类列表和默认选中的分类
      const allOption: string =
        locale.value === "en" ? "All" : locale.value === "zh" ? "全部" : "すべて";

      // 从FAQ数据中提取所有不同的分类
      const uniqueCategories = [
        ...new Set(faqData.value.map((faq: FAQ) => faq.category)),
      ].filter(category => category).sort(); // 过滤掉空分类并排序
      
      console.log('Unique categories:', uniqueCategories);

      // 设置分类列表和默认选中的分类
      categoriesList.value = [allOption, ...uniqueCategories];
      selectedCategory.value = categoriesList.value[0];
    } catch (err) {
      console.error("Error processing FAQ data:", err);
      error.value = new Error(t('faq.processError'));
    } finally {
      isLoading.value = false;
    }
  }
});

// 展开的FAQ标识
const expandedFaqKey = ref<string | null>(null);

// 搜索关键词
const searchTerm = ref("");
const searchInputRef = ref<HTMLInputElement | null>(null);

// 过滤后的FAQ列表
const filteredFaqs = computed(() => {
  if (!faqData.value) return [];
  
  let result = faqData.value;
  if (selectedCategory.value !== categoriesList.value[0]) {
    result = result.filter(
      (faq: FAQ) => faq.category === selectedCategory.value
    );
  }
  if (searchTerm.value.trim()) {
    const keyword = searchTerm.value.trim().toLowerCase();
    result = result.filter(
      (faq: FAQ) =>
        faq.question.toLowerCase().includes(keyword) ||
        faq.answer.toLowerCase().includes(keyword)
    );
  }
  return result;
});

/**
 * 高亮显示匹配的关键字
 * @param text 原始文本
 * @returns 高亮后的VNode数组
 */
function highlightKeyword(text: string): (string | any)[] {
  const keyword = searchTerm.value.trim();
  if (!keyword) return [text];
  // 构建正则，忽略大小写，转义特殊字符
  const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const reg = new RegExp(escaped, "gi");
  const parts = text.split(reg);
  const matches = text.match(reg);
  if (!matches) return [text];
  // 组装高亮
  const result: (string | any)[] = [];
  parts.forEach((part, i) => {
    result.push(part);
    if (i < matches.length) {
      result.push(
        h(
          "span",
          { class: "text-blue-400 bg-blue-400/10 font-bold" },
          matches[i]
        )
      );
    }
  });
  return result;
}

/**
 * 生成FAQ的唯一标识
 * @param faq FAQ对象
 * @returns string 唯一标识
 */
function generateFaqKey(faq: FAQ): string {
  return `${faq.category}-${faq.id}`;
}

/**
 * 切换FAQ展开状态
 * @param faq FAQ对象
 * @returns void
 */
function toggleFaq(faq: FAQ): void {
  if (!faq) return;
  
  const faqKey = generateFaqKey(faq);
  // 如果点击的是当前展开的FAQ，则关闭它
  if (expandedFaqKey.value === faqKey) {
    expandedFaqKey.value = null;
  } else {
    // 否则展开新的FAQ
    expandedFaqKey.value = faqKey;
  }
}

/**
 * 检查FAQ是否处于展开状态
 * @param faq FAQ对象
 * @returns boolean
 */
function isFaqExpanded(faq: FAQ): boolean {
  if (!faq) return false;
  return expandedFaqKey.value === generateFaqKey(faq);
}

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

// 自动展开匹配项
watch([filteredFaqs, searchTerm], ([faqs, keyword]: [FAQ[], string]) => {
  if (!faqs?.length) return;
  
  if (keyword.trim()) {
    // 搜索时展开第一个匹配项
    expandedFaqKey.value = faqs[0] ? generateFaqKey(faqs[0]) : null;
  } else {
    // 清除搜索时关闭所有展开项
    expandedFaqKey.value = null;
  }
}, { deep: true });

function clearSearch() {
  searchTerm.value = "";
  // 让输入框重新聚焦
  searchInputRef.value?.focus();
}

// SEO优化
useHead({
  title: t("faq.title") + " - Hanye",
  meta: [
    {
      name: "description",
      content: t("faq.description"),
    },
    {
      name: "keywords",
      content: t("faq.keywords"),
    },
  ],
});
</script>

<style scoped>
/* 添加过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
