<script setup lang="ts">
import { siteConfig } from '~/config/site'

useSeoMeta({
  title: '博客文章',
  description: `${siteConfig.siteName} 的所有文章`,
})

const route = useRoute()
const searchQuery = ref('')

watch(() => route.query.tag, (tag) => {
  if (typeof tag === 'string' && tag) {
    searchQuery.value = tag
    currentPage.value = 1
  }
}, { immediate: true })
const currentPage = ref(1)
const postsPerPage = 10

const searchFilters = ref({
  title: true,
  description: true,
  content: true,
  tags: true,
})

// 高频标签
const topTags = computed(() => {
  if (!allPosts.value) return []
  const count: Record<string, number> = {}
  for (const post of allPosts.value) {
    for (const tag of (post.tags || [])) {
      count[tag] = (count[tag] || 0) + 1
    }
  }
  return Object.entries(count)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 26)
    .map(([tag, count]) => ({ tag, count }))
})

function searchByTag(tag: string) {
  searchQuery.value = tag
  currentPage.value = 1
}

const { data: allPosts } = await useAsyncData('posts-list', () =>
  queryCollection('posts')
    .order('pinned', 'DESC')
    .order('published', 'DESC')
    .all()
)

const { searchResults, filteredPosts, highlight } = usePostSearch(allPosts, searchQuery, searchFilters)

const hasAnyFilter = computed(() => searchFilters.value.title || searchFilters.value.description || searchFilters.value.content || searchFilters.value.tags)

const totalPages = computed(() => Math.ceil(searchResults.value.length / postsPerPage))

const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * postsPerPage
  return searchResults.value.slice(start, start + postsPerPage)
})

watch(() => searchFilters.value, () => {
  currentPage.value = 1
}, { deep: true })
</script>

<template>
  <div class="container mx-auto max-w-4xl px-4 py-12">

    <!-- 页面标题 -->
    <div class="mb-12 text-center anim-fade-in-up">
      <h1 class="mb-4 text-4xl font-bold">博客文章</h1>
      <p class="text-muted-foreground">分享技术、想法和经验</p>
      <p class="mt-2 text-sm text-muted-foreground">
        共 {{ allPosts?.length || 0 }} 篇文章
      </p>
    </div>

    <!-- 搜索框 -->
    <div class="mb-8 anim-fade-in-up anim-delay-1">
      <div class="relative">
        <svg class="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="11" cy="11" r="8" />
          <path d="m21 21-4.3-4.3" />
        </svg>
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索文章标题、描述或内容..."
          class="w-full h-10 rounded-full border bg-transparent pl-10 pr-10 text-sm outline-none transition-all focus:ring-2"
          style="border-color: var(--color-border); --tw-ring-color: var(--color-border);"
          @input="currentPage = 1"
        />
        <button
          v-if="searchQuery"
          type="button"
          class="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground transition-colors cursor-pointer"
          @click="searchQuery = ''; currentPage = 1"
        >
          &times;
        </button>
      </div>

      <div class="mt-3 flex flex-wrap gap-4">
        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-muted-foreground">
          <input type="checkbox" v-model="searchFilters.title" class="w-4 h-4 rounded" style="accent-color: var(--color-text);" />
          <span>标题</span>
        </label>
        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-muted-foreground">
          <input type="checkbox" v-model="searchFilters.description" class="w-4 h-4 rounded" style="accent-color: var(--color-text);" />
          <span>简介</span>
        </label>
        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-muted-foreground">
          <input type="checkbox" v-model="searchFilters.content" class="w-4 h-4 rounded" style="accent-color: var(--color-text);" />
          <span>正文</span>
        </label>
        <label class="flex items-center gap-2 cursor-pointer select-none text-sm text-muted-foreground">
          <input type="checkbox" v-model="searchFilters.tags" class="w-4 h-4 rounded" style="accent-color: var(--color-text);" />
          <span>标签</span>
        </label>
      </div>

      <!-- 高频标签 -->
      <div v-if="topTags.length > 0" class="mt-3 flex flex-wrap gap-2">
        <button
          v-for="{ tag, count } in topTags"
          :key="tag"
          class="px-2.5 py-1 rounded-full text-xs font-medium transition-colors cursor-pointer"
          :style="searchQuery === tag
            ? 'background: var(--color-primary); color: white;'
            : 'background: var(--color-bg-hover); color: var(--color-text-secondary);'"
          @click="searchByTag(tag)"
        >
          {{ tag }}
          <span class="opacity-60">{{ count }}</span>
        </button>
      </div>

      <div v-if="searchQuery" class="mt-2 min-h-[20px]">
        <p v-if="!hasAnyFilter" class="text-sm text-red-500">请至少选择一个搜索范围</p>
        <p v-else-if="filteredPosts.length === 0" class="text-sm text-muted-foreground">未找到匹配的文章</p>
        <p v-else class="text-sm text-muted-foreground">找到 {{ filteredPosts.length }} 篇文章</p>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="space-y-6 anim-fade-in-up anim-delay-2">
      <BlogPostCard
        v-for="{ post, matchedLines } in paginatedResults"
        :key="post.id"
        :post="post"
        :matched-lines="matchedLines"
        :highlight="highlight"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="paginatedResults.length === 0" class="text-center py-12 text-muted-foreground">
      {{ searchQuery ? '未找到匹配的文章' : '暂无文章' }}
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="mt-8 flex flex-col items-center gap-4">
      <div class="flex items-center gap-2">
        <button
          :disabled="currentPage <= 1"
          class="btn-pill disabled:opacity-40"
          @click="currentPage--"
        >
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button
          :disabled="currentPage >= totalPages"
          class="btn-pill disabled:opacity-40"
          @click="currentPage++"
        >
          下一页
        </button>
      </div>
      <p class="text-center text-sm text-muted-foreground">
        共 {{ totalPages }} 页 / {{ filteredPosts.length }} 个
      </p>
    </div>
  </div>
</template>
