<template>
  <section class="card">
    <h2>儿童档案</h2>
    <p v-if="loading" class="muted">加载中…</p>
    <p v-else-if="error" class="error">{{ error }}</p>
    <div v-else>
      <div v-for="child in children" :key="child.id" class="list-item">
        <strong>{{ child.name }}</strong>
        <div class="muted">{{ child.birthday }} · {{ child.gender }}</div>
      </div>
      <button class="btn" style="margin-top: 16px" @click="goScreening">开始筛查</button>
      <button class="btn secondary" style="margin-top: 8px" @click="goPractice">跟练打卡</button>
    </div>
  </section>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { listChildren, type Child } from '../api'

const router = useRouter()
const children = ref<Child[]>([])
const loading = ref(true)
const error = ref('')

onMounted(async () => {
  try {
    const data = await listChildren()
    children.value = data.list
  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载失败'
  } finally {
    loading.value = false
  }
})

function goScreening() {
  if (!children.value.length) {
    error.value = '请先在后端 seed 或 Demo 中创建儿童档案'
    return
  }
  router.push('/screening')
}

function goPractice() {
  router.push('/practice')
}
</script>
