<template>
  <div>
    <div class="mb-2">
      <button class="btn" style="background: rgba(255,255,255,0.1); border: 1px solid var(--glass-border);" @click="goBack">
        &larr; 返回列表
      </button>
    </div>

    <div v-if="loading" class="text-center">
      <p>正在加载文档信息...</p>
    </div>
    <div v-else-if="error" class="text-center" style="color: #ef4444;">
      <p>{{ error }}</p>
    </div>
    <DocumentPreview v-else :url="document.url" :title="document.title" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import DocumentPreview from '../components/DocumentPreview.vue';

const route = useRoute();
const router = useRouter();
const document = ref(null);
const loading = ref(true);
const error = ref('');
const API = import.meta.env.VITE_API_BASE_URL;

onMounted(async () => {
  try {
    const id = route.params.id;
    const res = await axios.get(`${API}/api/documents/${id}`);
    // 将相对路径拼接为完整 URL，解决开发模式下跨端口访问问题
    const data = res.data;
    if (data.url && data.url.startsWith('/')) {
      data.url = `${API}${data.url}`;
    }
    document.value = data;
  } catch (err) {
    error.value = "文档未找到或无法访问。";
  } finally {
    loading.value = false;
  }
});

const goBack = () => {
  router.push('/');
}
</script>
