<script setup>
import { computed, ref } from 'vue';
import { dateRange, formatDate, registrationLabel, roleHome } from '@/lib/format';

const props = defineProps({
  publicData: { type: Object, required: true },
  session: { type: Object, required: true }
});

const emit = defineEmits(['logout']);
const mobileOpen = ref(false);

const notices = computed(() => props.publicData.notices || []);
const exams = computed(() => props.publicData.exams || []);
const stats = computed(() => props.publicData.stats || {});
const organization = computed(() => props.publicData.organization || {});
const siteCopy = computed(() => props.publicData.siteCopy || {});
const user = computed(() => props.session.user || null);
const featuredExam = computed(() => exams.value.find(exam => exam.registrationState === 'open') || exams.value[0] || null);
const topNotice = computed(() => notices.value[0] || null);

const portalLabel = computed(() => {
  if (!user.value) return '登录';
  if (user.value.role === 'candidate') return '进入考生中心';
  if (user.value.role === 'admission_school') return '进入招生学校端';
  return '进入管理后台';
});

const primaryRoute = computed(() => {
  if (user.value) return roleHome(user.value);
  return props.publicData.selfRegistrationEnabled ? 'register' : 'login';
});

const primaryLabel = computed(() => {
  if (user.value) return portalLabel.value;
  return props.publicData.selfRegistrationEnabled ? '申请固定报名号' : '使用报名号登录';
});

function go(route) {
  mobileOpen.value = false;
  location.hash = route;
}

function scrollToSection(id) {
  mobileOpen.value = false;
  document.querySelector(`#${id}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function openExam() {
  go(user.value?.role === 'candidate' ? 'candidate/exams' : 'login');
}

function count(value) {
  return new Intl.NumberFormat('zh-CN').format(Number(value || 0));
}
</script>

<template>
  <div class="hz-site">
    <a class="hz-skip" href="#hz-main">跳到主要内容</a>

    <div class="hz-service-bar">
      <div class="hz-container hz-service-bar__inner">
        <p><span aria-hidden="true"></span>考试信息公共服务平台</p>
        <div>
          <span v-if="organization.phone">咨询电话：{{ organization.phone }}</span>
          <button type="button" @click="go('verify')">文书防伪查询</button>
        </div>
      </div>
    </div>

    <header class="hz-header">
      <div class="hz-container hz-header__inner">
        <button class="hz-brand" type="button" aria-label="返回首页" @click="go('home')">
          <span class="hz-brand__seal" aria-hidden="true">衡</span>
          <span class="hz-brand__copy">
            <strong>衡准考试服务</strong>
            <small>EXAMINATION INFORMATION SERVICE</small>
          </span>
        </button>

        <nav :class="['hz-nav', { 'is-open': mobileOpen }]" aria-label="主要导航">
          <button type="button" class="is-current" @click="go('home')">首页</button>
          <button type="button" @click="scrollToSection('hz-exams')">考试报名</button>
          <button type="button" @click="go('notices')">通知公告</button>
          <button type="button" @click="go('verify')">防伪查询</button>
          <button type="button" @click="scrollToSection('hz-guide')">办事指南</button>
        </nav>

        <div class="hz-header__actions">
          <button class="hz-account-link" type="button" @click="go(roleHome(user))">{{ portalLabel }}</button>
          <button v-if="user" class="hz-exit-link" type="button" @click="emit('logout')">退出</button>
          <button
            class="hz-menu"
            type="button"
            :aria-expanded="mobileOpen"
            aria-label="打开导航"
            @click="mobileOpen = !mobileOpen"
          >
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>
    </header>

    <main id="hz-main">
      <section class="hz-hero">
        <div class="hz-container">
          <button v-if="topNotice" class="hz-latest" type="button" @click="go(`notice/${topNotice.id}`)">
            <span>最新发布</span>
            <strong>{{ topNotice.title }}</strong>
            <time>{{ formatDate(topNotice.publishAt) }}</time>
            <i aria-hidden="true">→</i>
          </button>

          <div class="hz-hero__grid">
            <div class="hz-hero__content">
              <p class="hz-kicker">统一入口 · 规范办理 · 全程留痕</p>
              <h1>
                {{ siteCopy.heroTitle || '让每一次考试办理，' }}
                <em>{{ siteCopy.heroHighlight || '都有清晰、可信的依据。' }}</em>
              </h1>
              <p class="hz-hero__lead">
                {{ siteCopy.heroDescription || '面向考生、学校和考试管理机构，统一提供报名、准考证、成绩、录取与公开信息服务。' }}
              </p>
              <div class="hz-hero__actions">
                <button class="hz-button hz-button--primary" type="button" @click="go(primaryRoute)">
                  {{ primaryLabel }}<span aria-hidden="true">→</span>
                </button>
                <button class="hz-button hz-button--secondary" type="button" @click="scrollToSection('hz-exams')">
                  查看已发布考试
                </button>
              </div>
              <dl class="hz-trust-list">
                <div><dt>账户原则</dt><dd>一个报名号长期使用</dd></div>
                <div><dt>信息原则</dt><dd>以平台正式发布为准</dd></div>
                <div><dt>安全原则</dt><dd>重要文书支持在线核验</dd></div>
              </dl>
            </div>

            <aside v-if="featuredExam" class="hz-exam-docket" aria-label="重点考试">
              <header>
                <div>
                  <span>重点考试</span>
                  <small>{{ featuredExam.code }}</small>
                </div>
                <em :class="`is-${featuredExam.registrationState}`">{{ registrationLabel(featuredExam.registrationState) }}</em>
              </header>
              <div class="hz-exam-docket__body">
                <p>EXAMINATION NOTICE</p>
                <h2>{{ featuredExam.name }}</h2>
                <dl>
                  <div><dt>报名时间</dt><dd>{{ dateRange(featuredExam.registrationStart, featuredExam.registrationEnd) }}</dd></div>
                  <div><dt>考试时间</dt><dd>{{ dateRange(featuredExam.examStart, featuredExam.examEnd) }}</dd></div>
                  <div><dt>考试地点</dt><dd>{{ featuredExam.location || '以准考证公布为准' }}</dd></div>
                </dl>
                <div class="hz-subjects">
                  <span v-for="subject in featuredExam.subjects?.slice(0, 5)" :key="subject.id || subject.name">{{ subject.name }}</span>
                  <span v-if="featuredExam.subjects?.length > 5">+{{ featuredExam.subjects.length - 5 }}</span>
                </div>
              </div>
              <footer>
                <p><strong>{{ count(featuredExam.registrationCount) }}</strong><span>人已报名</span></p>
                <button type="button" @click="openExam">{{ featuredExam.registrationState === 'open' ? '办理报名' : '查看考试' }} →</button>
              </footer>
            </aside>

            <aside v-else class="hz-exam-docket hz-exam-docket--empty">
              <span>考试发布栏</span>
              <h2>当前暂无已发布考试</h2>
              <p>新考试发布后，将在此展示报名时间、考试安排和办理入口。</p>
            </aside>
          </div>
        </div>
      </section>

      <section class="hz-entry-section" aria-labelledby="hz-entry-title">
        <div class="hz-container">
          <div class="hz-section-heading hz-section-heading--compact">
            <div><p>ONLINE SERVICES</p><h2 id="hz-entry-title">常用服务</h2></div>
            <span>按事项进入，减少查找和重复填写</span>
          </div>
          <div class="hz-service-grid">
            <button type="button" @click="go(primaryRoute)">
              <span class="hz-service-grid__index">01</span>
              <strong>{{ user ? '个人业务中心' : '报名号登录' }}</strong>
              <small>{{ user ? '继续办理当前账户下的考试事项' : '使用固定报名号进入考生服务' }}</small>
              <i>进入服务 →</i>
            </button>
            <button type="button" @click="scrollToSection('hz-exams')">
              <span class="hz-service-grid__index">02</span>
              <strong>考试报名</strong>
              <small>查看开放考试、报名日期与科目安排</small>
              <i>查看考试 →</i>
            </button>
            <button type="button" @click="go(user?.role === 'candidate' ? 'candidate/results' : 'login')">
              <span class="hz-service-grid__index">03</span>
              <strong>成绩与准考证</strong>
              <small>下载准考证，查询已正式发布的成绩</small>
              <i>办理查询 →</i>
            </button>
            <button type="button" @click="go('verify')">
              <span class="hz-service-grid__index">04</span>
              <strong>文书防伪核验</strong>
              <small>核对成绩单、录取通知书签发记录</small>
              <i>立即核验 →</i>
            </button>
          </div>
        </div>
      </section>

      <section class="hz-public-records">
        <div class="hz-container hz-records-grid">
          <div class="hz-notices">
            <div class="hz-section-heading">
              <div><p>PUBLIC INFORMATION</p><h2>通知公告</h2></div>
              <button type="button" @click="go('notices')">查看全部 →</button>
            </div>
            <article v-if="topNotice" class="hz-featured-notice">
              <div>
                <span>{{ topNotice.category || '通知公告' }}</span>
                <time>{{ formatDate(topNotice.publishAt) }}</time>
              </div>
              <h3>{{ topNotice.title }}</h3>
              <p>{{ topNotice.summary || '请进入公告正文查看完整内容和办理要求。' }}</p>
              <button type="button" @click="go(`notice/${topNotice.id}`)">阅读全文 <span>→</span></button>
            </article>
            <div v-else class="hz-empty">当前暂无通知公告</div>
            <div class="hz-notice-list">
              <button v-for="notice in notices.slice(1, 5)" :key="notice.id" type="button" @click="go(`notice/${notice.id}`)">
                <time><strong>{{ String(new Date(notice.publishAt).getDate()).padStart(2, '0') }}</strong><span>{{ new Date(notice.publishAt).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit' }).replace('/', '.') }}</span></time>
                <span><em>{{ notice.category || '通知' }}</em><strong>{{ notice.title }}</strong></span>
                <i>→</i>
              </button>
            </div>
          </div>

          <aside class="hz-operation-board" aria-label="平台运行概况">
            <header><span>服务概况</span><small>数据随业务实时更新</small></header>
            <dl>
              <div><dt>在册考生</dt><dd>{{ count(stats.candidates) }}<small>人</small></dd></div>
              <div><dt>累计报名记录</dt><dd>{{ count(stats.registrations) }}<small>条</small></dd></div>
              <div><dt>当前开放考试</dt><dd>{{ count(stats.exams) }}<small>项</small></dd></div>
            </dl>
            <section>
              <strong>公开信息说明</strong>
              <p>考试安排、录取公示及其他重要事项，以平台通知公告栏目正式发布内容为准。</p>
              <button type="button" @click="go('notices')">进入公开信息目录</button>
            </section>
          </aside>
        </div>
      </section>

      <section id="hz-exams" class="hz-exams">
        <div class="hz-container">
          <div class="hz-section-heading">
            <div><p>EXAMINATIONS</p><h2>已发布考试</h2></div>
            <span>登录后按考试要求选择科目并提交报名</span>
          </div>
          <div v-if="exams.length" class="hz-exam-grid">
            <article v-for="exam in exams" :key="exam.id" class="hz-exam-card">
              <header>
                <span>{{ exam.code }}</span>
                <em :class="`is-${exam.registrationState}`">{{ registrationLabel(exam.registrationState) }}</em>
              </header>
              <h3>{{ exam.name }}</h3>
              <p>{{ exam.description || '考试具体安排与报名要求请以正式通知为准。' }}</p>
              <dl>
                <div><dt>报名日期</dt><dd>{{ dateRange(exam.registrationStart, exam.registrationEnd) }}</dd></div>
                <div><dt>考试日期</dt><dd>{{ dateRange(exam.examStart, exam.examEnd) }}</dd></div>
                <div><dt>科目</dt><dd>{{ exam.subjects?.length || 0 }} 科 · 总分 {{ exam.totalScore || 0 }} 分</dd></div>
              </dl>
              <footer>
                <span>{{ count(exam.registrationCount) }} 人已报名</span>
                <button type="button" @click="openExam">{{ exam.registrationState === 'open' ? '选择科目报名' : '查看考试' }} →</button>
              </footer>
            </article>
          </div>
          <div v-else class="hz-empty hz-empty--large">当前没有已发布的考试，请留意通知公告。</div>
        </div>
      </section>

      <section id="hz-guide" class="hz-guide">
        <div class="hz-container">
          <div class="hz-guide__intro">
            <p>办事指南</p>
            <h2>一个报名号，贯穿完整考试服务</h2>
            <span>报名号是考生的长期账户。每场考试新增报名记录，不重复创建个人账户。</span>
          </div>
          <ol>
            <li><span>1</span><div><strong>领取报名号</strong><p>由学校创建，或在开放自主注册时在线申请。</p></div></li>
            <li><span>2</span><div><strong>完善个人资料</strong><p>首次登录修改密码，并按要求提交真实资料。</p></div></li>
            <li><span>3</span><div><strong>选择考试科目</strong><p>资料审核通过后，在开放期内完成报名。</p></div></li>
            <li><span>4</span><div><strong>办理后续事项</strong><p>使用同一报名号下载准考证、查分和查看录取。</p></div></li>
          </ol>
        </div>
      </section>
    </main>

    <footer class="hz-footer">
      <div class="hz-container hz-footer__main">
        <div class="hz-footer__brand">
          <span class="hz-brand__seal" aria-hidden="true">衡</span>
          <div><strong>衡准考试服务</strong><small>规范 · 准确 · 可追溯</small></div>
        </div>
        <dl>
          <div><dt>主管单位</dt><dd>{{ organization.name || '考试信息管理机构' }}</dd></div>
          <div v-if="organization.phone"><dt>咨询电话</dt><dd>{{ organization.phone }}</dd></div>
          <div v-if="organization.address"><dt>联系地址</dt><dd>{{ organization.address }}</dd></div>
        </dl>
        <div class="hz-footer__links">
          <button type="button" @click="go('notices')">通知公告</button>
          <button type="button" @click="go('verify')">文书核验</button>
          <button type="button" @click="go('login')">服务登录</button>
        </div>
      </div>
      <div class="hz-footer__legal">
        <div class="hz-container">
          <span>{{ siteCopy.footerNotice || '公开信息以本平台正式发布内容为准' }}</span>
          <span>请勿在非官方页面提交密码或验证码</span>
        </div>
      </div>
    </footer>
  </div>
</template>
