<template>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <div class="flex items-center mb-6">
      <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
        {{ route.query.tag ? 'Posts tagged with' : 'Search Results' }}
      </h2>
      <p class="ml-4 text-gray-500 dark:text-gray-400">
        {{ route.query.tag ? route.query.tag : `for "${searchQuery}"` }}
      </p>
    </div>

    <div v-if="loading" class="flex justify-center py-8">
      <LoadingSpinner text="搜索中..." />
    </div>

    <div v-else-if="error" class="bg-red-50 dark:bg-red-900 p-4 rounded-lg">
      <p class="text-red-600 dark:text-red-400">{{ error }}</p>
    </div>

    <div v-else-if="results.length" class="grid gap-6">
      <PostCard
        v-for="post in results"
        :key="post.id"
        :post="post"
      />
    </div>

    <div v-else class="text-center py-8">
      <p class="text-gray-500 dark:text-gray-400 text-lg">No matching results found.</p>
      <p class="text-gray-400 dark:text-gray-500 mt-2">Try different keywords or check your spelling.</p>
    </div>

    <Pagination
      v-if="results.length"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePosts } from '../composables/usePosts'
import PostCard from '../components/PostCard.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import Pagination from '../components/Pagination.vue'

const route = useRoute()
const router = useRouter()
const { fetchPosts } = usePosts()

const results = ref([])
const loading = ref(false)
const error = ref(null)
const currentPage = ref(1)
const totalPages = ref(1)
const PAGE_SIZE = 10

const searchQuery = ref('')

const performSearch = async (page = 1) => {
  if (!route.query.q && !route.query.tag) {
    error.value = '请输入搜索关键词'
    return
  }

  loading.value = true
  error.value = null
  searchQuery.value = route.query.q || ''

  try {
    const { items, total } = await fetchPosts({
      search: route.query.q,
      tag: route.query.tag,
      page,
      size: PAGE_SIZE
    })
    results.value = items
    totalPages.value = Math.ceil(total / PAGE_SIZE)
    currentPage.value = page
  } catch (err) {
    error.value = '搜索失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  router.push({
    query: { ...route.query, page }
  })
}

// 监听路由变化，重新搜索
watch(() => route.query, () => {
  performSearch(parseInt(route.query.page) || 1)
}, { immediate: true })
</script>
