<?php
/**
 * 双语首页入口：/（中文动态 HTML 外壳 + Vue 接管）与 /en（英文直出）
 * ---------------------------------------------------------------------------
 * 中文首页读取当前 Vite 外壳并注入数据库内容，让不执行 JavaScript 的搜索引擎、
 * AI 抓取器和弱网用户也能直接读到正文；浏览器随后由 Vue 接管交互。
 * 英文站保持「直出闭环」：/en → /en/cat/{slug} → /en/{slug}。
 *
 * 英文页面内容：应急要点 → 主题索引 → 最新文章 → 常见问答。
 * 所有列表都只收录「有英文译文」的内容，避免把读者导向 404。
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/seo.php';
require_once __DIR__ . '/../includes/i18n.php';
require_once __DIR__ . '/../includes/internal_links.php';
require_once __DIR__ . '/../includes/layout.php';

$lang = seo_lang();
if ($lang === seo_default_lang()) {
    require_once __DIR__ . '/../includes/home_shell.php';
    render_zh_home_shell();
    exit;
}
if (!i18n_active($lang)) {
    http_response_code(404);
    exit;
}

$siteName  = seo_site_name($lang);
$canonical = seo_home_url($lang);

// 最新文章（只收录有英文译文的）
$artStmt = db()->prepare("SELECT a.id, a.slug, a.title, a.summary, a.published_at, a.view_count
                          FROM articles a
                          WHERE a.status = 'published'
                            AND EXISTS (SELECT 1 FROM content_i18n ci
                                        WHERE ci.entity = 'article' AND ci.entity_id = a.id
                                          AND ci.lang = ? AND ci.status = 'published')
                          ORDER BY a.published_at DESC, a.id DESC LIMIT 12");
$artStmt->execute([$lang]);
$articles = i18n_localize_articles($artStmt->fetchAll(), $lang);

// 常见问答（只收录有英文译文的）
$faqStmt = db()->prepare("SELECT f.id, f.slug, f.question, f.answer FROM faqs f
                          WHERE f.status = 1
                            AND EXISTS (SELECT 1 FROM content_i18n ci
                                        WHERE ci.entity = 'faq' AND ci.entity_id = f.id
                                          AND ci.lang = ? AND ci.status = 'published')
                          ORDER BY f.sort, f.id LIMIT 10");
$faqStmt->execute([$lang]);
$faqs = i18n_localize_faqs($faqStmt->fetchAll(), $lang);

// 主题索引（il_category_groups 已按语言本地化并剔除无译文分类）
$groups = il_category_groups($lang);
$topicHtml = '';
$topicCount = 0;
foreach ($groups as $type => $group) {
    if (!$group['items']) {
        continue;
    }
    $tags = '';
    foreach ($group['items'] as $item) {
        if (empty($item['href'])) {
            continue;
        }
        $topicCount++;
        $tags .= '<a class="tag" href="' . seo_e($item['href']) . '">' . seo_e($item['name']) . '</a>';
    }
    if ($tags === '') {
        continue;
    }
    $topicHtml .= '<div class="dim"><h3>' . seo_e($group['label']) . '</h3><div class="tags">' . $tags . '</div></div>';
}

$emg = i18n_anaphylaxis_en();
$emgFlags = '';
foreach ($emg['flags'] as $f) {
    $emgFlags .= '<li>' . seo_e($f) . '</li>';
}
$emgSteps = '';
foreach ($emg['steps'] as $i => $step) {
    $emgSteps .= '<li><strong>' . ($i + 1) . '. ' . seo_e($step[0]) . '</strong><span>' . seo_e($step[1]) . '</span></li>';
}
$emgDonts = '';
foreach ($emg['donts'] as $d) {
    $emgDonts .= '<li>' . seo_e($d) . '</li>';
}

$artHtml = '';
foreach ($articles as $a) {
    $href = seo_article_path($a, $lang);
    if ($href === '') {
        continue;
    }
    $artHtml .= '<li><a href="' . seo_e($href) . '">' . seo_e($a['title']) . '</a>'
              . ($a['summary'] !== '' ? '<p>' . seo_e($a['summary']) . '</p>' : '')
              . '<span class="date">' . seo_e(substr((string)$a['published_at'], 0, 10)) . '</span></li>';
}

$faqHtml = '';
foreach ($faqs as $f) {
    $href = seo_faq_path($f, $lang);
    if ($href === '') {
        continue;
    }
    $faqHtml .= '<li><a href="' . seo_e($href) . '">' . seo_e($f['question']) . '</a></li>';
}

$desc = seo_site_desc($lang);

// ---------- JSON-LD：Organization + WebSite + 主题 ItemList ----------
$topicItems = [];
$pos = 1;
foreach ($groups as $type => $group) {
    foreach ($group['items'] as $item) {
        if (empty($item['href'])) {
            continue;
        }
        $topicItems[] = [
            '@type' => 'ListItem',
            'position' => $pos++,
            'name' => $item['name'],
            'url' => seo_locale_url('cat/' . $item['slug'], $lang)
        ];
    }
}

$jsonld = [
    '@context' => 'https://schema.org',
    '@graph' => [
        [
            '@type' => 'Organization',
            '@id' => SEO_SITE_URL . '/#organization',
            'name' => $siteName,
            'url' => seo_home_path($lang),
            'description' => $desc,
            'publishingPrinciples' => seo_editorial_policy_url($lang)
        ],
        [
            '@type' => 'WebSite',
            '@id' => SEO_SITE_URL . '/#website',
            'name' => $siteName,
            'url' => seo_home_path($lang),
            'publisher' => ['@id' => SEO_SITE_URL . '/#organization'],
            'inLanguage' => seo_locale($lang)
        ],
        [
            '@type' => 'CollectionPage',
            '@id' => $canonical,
            'name' => $siteName,
            'description' => $desc,
            'url' => $canonical,
            'inLanguage' => seo_locale($lang),
            'isPartOf' => ['@id' => SEO_SITE_URL . '/#website'],
            'mainEntity' => [
                '@type' => 'ItemList',
                'numberOfItems' => count($topicItems),
                'itemListElement' => $topicItems
            ]
        ]
    ]
];
$jsonldHtml = '<script type="application/ld+json">' . json_encode($jsonld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';

$extraStyle = <<<CSS
.emg { background: var(--c-danger-soft); border: 2px solid var(--c-danger); border-radius: var(--r-lg); padding: var(--sp-5); margin-bottom: var(--sp-6); }
.emg h2 { color: var(--c-danger-deep); margin: 0 0 var(--sp-2); font-size: var(--fs-h2); }
.emg .lead { margin: 0 0 var(--sp-3); color: var(--c-text); }
.emg h3 { margin: var(--sp-4) 0 var(--sp-2); font-size: var(--fs-h4); color: var(--c-danger-deep); }
.emg ul, .emg ol { margin: 0; padding-left: 1.2em; }
.emg ol { list-style: none; padding-left: 0; }
.emg ol li { margin-bottom: var(--sp-3); }
.emg ol li span { display: block; color: var(--c-text-sub); font-size: var(--fs-sm); }
.emg li { margin-bottom: var(--sp-1); }
.emg .note { margin-top: var(--sp-3); font-size: var(--fs-sm); color: var(--c-text-sub); }
.emg .more-link { margin-top: var(--sp-2); font-size: var(--fs-sm); }
.hero { margin-bottom: var(--sp-6); }
.hero h1 { font-size: var(--fs-h1); margin: 0 0 var(--sp-2); }
.hero .lead { color: var(--c-text-sub); margin: 0; }
@media (max-width: 560px) { .emg { padding: var(--sp-4); } }
CSS;

layout_head([
    'title'        => $siteName . ' — practical allergy information',
    'description'  => $desc,
    'keywords'     => 'allergy,allergy education,allergic rhinitis,asthma,eczema,urticaria,anaphylaxis,food allergy,dust mite,pollen',
    'canonical'    => $canonical,
    'jsonldHtml'   => $jsonldHtml,
    'hreflangPath' => '',
    'altLangs'     => ['en'],
    'extraStyle'   => $extraStyle,
    'bodyClass'    => 'home-en',
]);
?>
<main class="wrap">
  <div class="hero">
    <h1><?= seo_e($siteName) ?></h1>
    <p class="lead"><?= seo_e($desc) ?></p>
  </div>

  <section class="emg" id="emergency">
    <h2><?= seo_e($emg['title']) ?></h2>
    <p class="lead"><?= seo_e($emg['lead']) ?></p>
    <h3>Warning signs</h3>
    <ul><?= $emgFlags ?></ul>
    <h3>What to do</h3>
    <ol><?= $emgSteps ?></ol>
    <h3>Do not</h3>
    <ul><?= $emgDonts ?></ul>
    <p class="note"><?= seo_e($emg['note']) ?></p>
    <p class="more-link"><a href="<?= seo_e($emg['link']) ?>"><?= seo_e($emg['linkText']) ?></a></p>
  </section>

  <?php if ($topicHtml !== ''): ?>
  <section class="dimensions" id="topics">
    <h2><?= seo_e(i18n_t('section.dimensions', $lang)) ?></h2>
    <?= $topicHtml ?>
  </section>
  <?php endif; ?>

  <?php if ($artHtml !== ''): ?>
  <section class="post">
    <h2><?= seo_e(i18n_t('section.latest', $lang)) ?></h2>
    <ul class="list"><?= $artHtml ?></ul>
  </section>
  <?php endif; ?>

  <?php if ($faqHtml !== ''): ?>
  <section class="post">
    <h2><?= seo_e(i18n_t('crumb.faqs', $lang)) ?></h2>
    <ul class="faq-list"><?= $faqHtml ?></ul>
    <p class="app-link"><a href="<?= seo_e(seo_faqs_path($lang)) ?>">All questions</a></p>
  </section>
  <?php endif; ?>
</main>
<?php
layout_foot();
