<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Loading State -->
    <div v-if="loading" class="flex justify-center items-center min-h-screen">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
    </div>

    <!-- Book Content -->
    <div v-else-if="book" class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Book Header -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">{{ book.title }}</h1>
        <p class="text-gray-600">作者: {{ book.author }}</p>
      </div>

      <!-- Reading Area -->
      <div class="bg-white rounded-lg shadow-md p-8">
        <div class="prose max-w-none">
          <div class="whitespace-pre-wrap text-gray-800 leading-relaxed">{{ book.content }}</div>
        </div>
      </div>

      <!-- Save Progress Button -->
      <div class="mt-6 flex justify-end">
        <button 
          @click="saveProgress"
          :disabled="saving"
          class="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-60"
        >
          {{ saving ? '保存中...' : '保存阅读进度' }}
        </button>
      </div>
    </div>

    <!-- Error State -->
    <div v-else class="flex justify-center items-center min-h-screen">
      <p class="text-gray-500 text-lg">图书不存在</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { bookAPI, readingAPI } from '@/api'

const route = useRoute()
const loading = ref(true)
const saving = ref(false)
const book = ref(null)

const loadBook = async () => {
  try {
    const id = parseInt(route.params.id)
    book.value = await bookAPI.get(id)
  } catch (error) {
    console.error('Failed to load book:', error)
  } finally {
    loading.value = false
  }
}

const saveProgress = async () => {
  if (!book.value) return
  
  saving.value = true
  try {
    await readingAPI.saveRecord({
      book_id: book.value.id,
      read_percentage: 100 // 简化:标记为已读完
    })
    alert('阅读进度已保存!')
  } catch (error) {
    console.error('Failed to save progress:', error)
    alert('保存失败')
  } finally {
    saving.value = false
  }
}

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