<template>
  <div class="w-full lg:w-3/4 space-y-6">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center py-8">
      <LoadingSpinner text="加载中..." />
    </div>

    <!-- 文章列表 -->
    <template v-else>
      <PostCard 
        v-for="post in postsList" 
        :key="post.id" 
        :post="post"
        @like="handleLike"
        @unlike="handleUnlike"
      />
      
      <!-- 无数据提示 -->
      <div v-if="postsList.length === 0" class="text-center py-8 text-gray-500">
        暂无数据
      </div>

      <!-- 分页 -->
      <Pagination 
        v-if="postsList.length > 0"
        :current-page="currentPage"
        :total-pages="totalPages"
        @page-change="handlePageChange"
      />
    </template>
  </div>
</template>

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

const route = useRoute()
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const { 
  postsList, 
  loading, 
  error,
  fetchPosts,
  likePost,
  unlikePost 
} = usePosts()

const loadPosts = async (page = 1) => {
  try {
    const { items, total } = await fetchPosts({ 
      page, 
      size: pageSize.value,
      sort: route.name === 'hot' ? 'hot' : route.name === 'latest' ? 'latest' : undefined,
      ...route.query 
    })
    postsList.value = items
    totalPages.value = Math.ceil(total / pageSize.value)
    currentPage.value = page
  } catch (err) {
    console.error('Failed to load posts:', err)
  }
}

const handlePageChange = async (page) => {
  currentPage.value = page
  await loadPosts(page)
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleLike = async (postId) => {
  try {
    await likePost(postId)
  } catch (err) {
    console.error('Failed to like post:', err)
  }
}

const handleUnlike = async (postId) => {
  try {
    await unlikePost(postId)
  } catch (err) {
    console.error('Failed to unlike post:', err)
  }
}

// 监听路由变化（用于切换最新/最热/首页）
watch(
  () => route.name,
  () => {
    currentPage.value = 1
    loadPosts(1)
  }
)

// 初始加载
onMounted(() => {
  loadPosts(currentPage.value)
})
</script>