<template>
  <div class="flex flex-col lg:flex-row gap-6">
    <!-- 主要内容区域 -->
    <div v-if="loading" class="w-full lg:w-3/4 flex justify-center py-8">
      <LoadingSpinner text="加载中..." />
    </div>
    
    <div v-else-if="currentPost" class="w-full lg:w-3/4">
      <article class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
        <!-- 文章标题 -->
        <div class="flex items-center justify-between mb-4">
          <h1 class="text-3xl font-bold text-gray-900 dark:text-white">{{ currentPost.title }}</h1>
          <button
            v-if="isAuthor"
            @click="$router.push(`/posts/${currentPost.id}/edit`)"
            class="px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md shadow-sm"
          >
            编辑帖子
          </button>
        </div>
        
        <!-- 作者信息和日期 -->
        <div class="flex items-center mb-6">
          <div class="flex items-center">
            <div v-if="currentPost.author.avatar" class="w-10 h-10 rounded-full overflow-hidden">
              <img :src="getAssetUrl(currentPost.author.avatar)" :alt="currentPost.author.username" class="w-full h-full object-cover">
            </div>
            <div v-else class="w-10 h-10 bg-gray-200 dark:bg-gray-700 rounded-full flex items-center justify-center">
              <span class="text-gray-600 dark:text-gray-300 text-lg">{{ currentPost.author.username[0] }}</span>
            </div>
            <div class="ml-3">
              <p class="text-gray-900 dark:text-white font-medium">{{ currentPost.author.username }}</p>
              <p class="text-gray-500 dark:text-gray-400 text-sm">{{ currentPost.author.bio || '旅行爱好者' }}</p>
            </div>
          </div>
          <span class="mx-4 text-gray-300 dark:text-gray-600">|</span>
          <time class="text-gray-500 dark:text-gray-400">{{ formatDate(currentPost.created_at) }}</time>
        </div>

        <!-- 文章内容 -->
        <div class="prose dark:prose-invert max-w-none" v-html="formattedContent"></div>

        <!-- 互动区域 -->
        <div class="flex items-center mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
          <button 
            @click="handleLikeClick"
            class="flex items-center transition duration-150 ease-in-out"
            :class="[
              currentPost.is_liked 
                ? 'text-green-600 dark:text-green-400' 
                : 'text-gray-500 hover:text-green-600 dark:hover:text-green-400'
            ]"
          >
            <HandThumbUpIcon class="w-5 h-5 mr-1.5" />
            <span>{{ currentPost.likes_count }} 点赞</span>
          </button>
          <button class="flex items-center text-gray-500 dark:text-gray-400 hover:text-green-600 dark:hover:text-green-400 ml-6">
            <ChatBubbleOvalLeftEllipsisIcon class="w-5 h-5 mr-1.5" />
            <span>{{ currentPost.comments_count }} 评论</span>
          </button>
        </div>
      </article>

      <!-- 评论区域 -->
      <CommentSection :post-id="currentPost.id" />
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="w-full lg:w-3/4 p-6 bg-red-50 dark:bg-red-900 rounded-lg">
      <p class="text-red-600 dark:text-red-400">{{ error }}</p>
    </div>

    <!-- 侧边栏 -->
    <Sidebar />
  </div>
</template>

<script setup>
import { onMounted, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { HandThumbUpIcon, ChatBubbleOvalLeftEllipsisIcon } from '@heroicons/vue/24/outline'
import Sidebar from '../components/Sidebar.vue'
import CommentSection from '../components/CommentSection.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import { usePosts } from '../composables/usePosts'
import { marked } from 'marked'
import { useAuth } from '../composables/useAuth'
import { getAssetUrl } from '../utils/assets'

const route = useRoute()
const { currentPost, loading, error, getPost, likePost, unlikePost } = usePosts()
const { user } = useAuth()

const processContent = (content) => {
  // 替换所有 localhost:8000 为实际域名
  return content.replace(
    /http:\/\/localhost:8000\/media/g, 
    'https://domaintestaccount.store/media'
  )
}

const formattedContent = computed(() => {
  if (!currentPost.value?.content) return ''
  const processedContent = processContent(currentPost.value.content)
  return marked(processedContent)
})

const isAuthor = computed(() => user.value?.id === currentPost.value?.author?.id)

const handleLikeClick = async () => {
  try {
    if (currentPost.value.is_liked) {
      await unlikePost(currentPost.value.id)
    } else {
      await likePost(currentPost.value.id)
    }
  } catch (err) {
    console.error('Failed to handle like:', err)
  }
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

onMounted(async () => {
  const postId = route.params.id
  if (postId) {
    await getPost(postId)
  }
})

// Add watcher for route params changes
watch(() => route.params.id, async (newId) => {
  if (newId) {
    await getPost(newId)
  }
}, { immediate: false })
</script>
