<script setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import PublicFrame from '@/components/common/PublicFrame.vue';
import PageState from '@/components/common/PageState.vue';
import { api } from '@/lib/api';
import { formatDate } from '@/lib/format';
import { buildPublicDocuments } from '@/lib/publicDocuments';
import { sessionStore } from '@/stores/session';

const router = useRouter();
const loading = ref(true);
const error = ref('');
const documents = ref([]);
const query = ref('');
const category = ref('全部');
const page = ref(1);
const pageSize = 10;

const categories = computed(() => ['全部', ...new Set(documents.value.map(item => item.category || '通知公告'))]);
const filtered = computed(() => {
  const needle = query.value.trim().toLowerCase();
  return documents.value.filter(item => (category.value === '全部' || item.category === category.value)
    && (!needle || [item.title, item.summary, item.category, item.subtype].join(' ').toLowerCase().includes(needle)));
});
const totalPages = computed(() => Math.max(1, Math.ceil(filtered.value.length / pageSize)));
const pageRows = computed(() => filtered.value.slice((page.value - 1) * pageSize, page.value * pageSize));

async function load() {
  loading.value = true;
  error.value = '';
  try {
    const data = await api('/api/public/announcements');
    documents.value = buildPublicDocuments(sessionStore.state.publicData, data);
  } catch (requestError) {
    error.value = requestError.message;
  } finally {
    loading.value = false;
  }
}

function chooseCategory(value) { category.value = value; page.value = 1; }
function search() { page.value = 1; }
onMounted(load);
</script>

<template>
  <PublicFrame>
    <section class="public-page-head">
      <div class="app-container"><p>PUBLIC RECORDS</p><h1>通知公告与公开公示</h1><span>考试通知、成绩发布、招生计划和录取公示统一归档。</span></div>
    </section>
    <section class="app-container public-directory">
      <PageState :loading="loading" :error="error" :empty="!documents.length" @retry="load">
        <aside class="public-directory__filters">
          <strong>信息分类</strong>
          <button v-for="item in categories" :key="item" :class="{ active: category === item }" type="button" @click="chooseCategory(item)">
            {{ item }}<span>{{ item === '全部' ? documents.length : documents.filter(row => row.category === item).length }}</span>
          </button>
        </aside>
        <div class="public-directory__content">
          <div class="directory-toolbar">
            <label><span>搜索公开信息</span><input v-model="query" placeholder="输入标题、分类或摘要" @input="search"></label>
            <small>共 {{ filtered.length }} 条</small>
          </div>
          <div class="directory-list">
            <button v-for="item in pageRows" :key="item.documentId" type="button" @click="router.push(`/announcements/${item.documentId}`)">
              <time><strong>{{ String(new Date(item.publishedAt).getDate()).padStart(2, '0') }}</strong><span>{{ formatDate(item.publishedAt).slice(0, 7) }}</span></time>
              <span><em>{{ item.subtype }}</em><strong>{{ item.title }}</strong><small>{{ item.summary || '进入查看完整公开内容' }}</small></span>
              <i>→</i>
            </button>
            <div v-if="!pageRows.length" class="page-state page-state--empty"><strong>没有符合条件的信息</strong><p>请调整分类或搜索关键词。</p></div>
          </div>
          <nav v-if="totalPages > 1" class="app-pagination" aria-label="公告分页">
            <button type="button" :disabled="page <= 1" @click="page--">上一页</button>
            <span>第 {{ page }} / {{ totalPages }} 页</span>
            <button type="button" :disabled="page >= totalPages" @click="page++">下一页</button>
          </nav>
        </div>
      </PageState>
    </section>
  </PublicFrame>
</template>
