<template>
  <div>
    <div v-if="loading" class="space-y-4">
      <USkeleton v-for="i in 3" :key="i" class="h-24" />
    </div>

    <div v-else-if="comments.length === 0" class="text-center py-8">
      <p class="text-gray-600 dark:text-gray-400">暂无评论</p>
    </div>

    <div v-else class="space-y-6">
      <CommentItem
        v-for="comment in comments"
        :key="comment.id"
        :comment="comment"
        :depth="0"
        @reply="handleReply"
      />
    </div>

    <div class="mt-8">
      <CommentForm
        :article-id="articleId"
        @submitted="onCommentSubmitted"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Comment } from '~/types/models'

const props = defineProps<{
  articleId: number
}>()

const { fetchComments, createComment } = useComments()
const { isAuthenticated } = useAuth()

const comments = ref<Comment[]>([])
const loading = ref(true)
const replyTo = ref<Comment | null>(null)

const loadComments = async () => {
  loading.value = true
  try {
    comments.value = await fetchComments(props.articleId)
  } catch (error) {
    console.error('Failed to load comments:', error)
  } finally {
    loading.value = false
  }
}

const handleReply = (comment: Comment) => {
  if (!isAuthenticated.value) {
    // TODO: 跳转到登录页
    return
  }
  replyTo.value = comment
}

const onCommentSubmitted = async () => {
  replyTo.value = null
  await loadComments()
}

onMounted(() => {
  loadComments()
})
</script>
