<template>
  <div class="home">
    <div class="text-center mb-2">
      <h1 style="font-size: 2.5rem; margin-bottom: 1rem;">可用文档列表</h1>
      <p style="color: var(--text-muted); font-size: 1.1rem;">浏览我们的文档库。点击任意文档即可预览内容。</p>
    </div>

    <div v-if="loading" class="text-center">
      <p>正在加载文档...</p>
    </div>
    
    <div v-else-if="documents.length === 0" class="text-center">
      <p>暂无上传的文档。</p>
    </div>

    <div v-else class="doc-grid">
      <div v-for="doc in documents" :key="doc.id" class="glass-card doc-card" @click="goToPreview(doc.id)">
        <div class="doc-icon">📄</div>
        <h3>{{ doc.title }}</h3>
        <p class="date">{{ new Date(doc.created_at).toLocaleDateString() }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const documents = ref([]);
const loading = ref(true);
const router = useRouter();
const API = import.meta.env.VITE_API_BASE_URL;

onMounted(async () => {
  try {
    const res = await axios.get(`${API}/api/documents`);
    documents.value = res.data;
  } catch (error) {
    console.error("Error fetching docs", error);
  } finally {
    loading.value = false;
  }
});

const goToPreview = (id) => {
  router.push(`/preview/${id}`);
};
</script>

<style scoped>
.doc-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 2rem;
}

.doc-card {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.doc-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.doc-card h3 {
  margin-bottom: 0.5rem;
  font-size: 1.2rem;
}

.date {
  color: var(--text-muted);
  font-size: 0.85rem;
}
</style>
