<script setup>
import { onMounted, ref } from 'vue';
import HomePage from '@/components/HomePage.vue';
import { api } from '@/lib/api';

const loading = ref(true);
const error = ref('');
const publicData = ref({ organization: {}, notices: [], exams: [], stats: {} });
const session = ref({ user: null, profile: null, permissions: [] });

async function load() {
  loading.value = true;
  error.value = '';
  try {
    const [home, currentSession] = await Promise.all([
      api('/api/public/home'),
      api('/api/auth/me').catch(requestError => {
        if (requestError.status === 401) return { user: null, profile: null, permissions: [] };
        throw requestError;
      })
    ]);
    publicData.value = home;
    session.value = currentSession;
  } catch (requestError) {
    error.value = requestError.message || '首页服务暂时不可用，请稍后重试。';
  } finally {
    loading.value = false;
  }
}

async function logout() {
  try {
    await api('/api/auth/logout', { method: 'POST' });
    session.value = { user: null, profile: null, permissions: [] };
    await load();
  } catch (requestError) {
    error.value = requestError.message || '退出未完成，请稍后重试。';
  }
}

onMounted(load);
</script>

<template>
  <div v-if="loading" class="hz-loading" role="status" aria-live="polite">
    <span class="hz-loading__seal" aria-hidden="true">衡</span>
    <strong>正在接入考试公共服务</strong>
    <small>请稍候</small>
  </div>
  <main v-else-if="error" class="hz-failure">
    <span>服务提示</span>
    <h1>首页暂时无法加载</h1>
    <p>{{ error }}</p>
    <button type="button" @click="load">重新加载</button>
  </main>
  <HomePage
    v-else
    :public-data="publicData"
    :session="session"
    @logout="logout"
  />
</template>
