<?php
$site = require __DIR__ . '/data/site.php';
$pageTitle = $site['meta']['name'];
$pageDescription = $site['meta']['description'];
$activePage = 'home';
$currentStaffCount = count(array_filter($site['staff_page']['people'] ?? [], static function (array $person): bool {
    return ($person['category'] ?? '') !== 'former';
}));
$russianCountWord = static function (int $count, string $one, string $few, string $many): string {
    $lastTwo = $count % 100;
    $last = $count % 10;

    if ($lastTwo >= 11 && $lastTwo <= 14) {
        return $many;
    }

    if ($last === 1) {
        return $one;
    }

    if ($last >= 2 && $last <= 4) {
        return $few;
    }

    return $many;
};
$homeFacts = [
    ['value' => count($site['staff_page']['units'] ?? []), 'label' => $russianCountWord(count($site['staff_page']['units'] ?? []), 'структурное подразделение', 'структурных подразделения', 'структурных подразделений')],
    ['value' => $currentStaffCount, 'label' => $russianCountWord($currentStaffCount, 'сотрудник', 'сотрудника', 'сотрудников') . ' в справочнике'],
    ['value' => count($site['publications_page']['items'] ?? []), 'label' => $russianCountWord(count($site['publications_page']['items'] ?? []), 'публикация', 'публикации', 'публикаций') . ' в каталоге'],
];

require __DIR__ . '/includes/header.php';
?>

<main>
    <section class="hero" aria-labelledby="hero-title">
        <img class="hero__image" src="<?= h($site['hero']['image']) ?>" alt="<?= h($site['hero']['alt']) ?>" decoding="async" fetchpriority="high">
        <div class="hero__shade"></div>
        <div class="container hero__content">
            <p class="eyebrow"><?= h($site['hero']['eyebrow']) ?></p>
            <h1 id="hero-title"><?= h($site['hero']['title']) ?></h1>
            <p class="hero__lead"><?= h($site['hero']['lead']) ?></p>
            <div class="hero__actions">
                <a class="button button--primary" href="news.php">Новости</a>
                <a class="button button--ghost" href="data.php">Данные и сервисы</a>
            </div>
            <nav class="hero__quick-links" aria-label="Быстрые ссылки главной страницы">
                <?php foreach ($site['quick_links'] as $link): ?>
                    <a href="<?= h($link['href']) ?>">
                        <span><?= h($link['meta']) ?></span>
                        <strong><?= h($link['title']) ?></strong>
                    </a>
                <?php endforeach; ?>
            </nav>
        </div>
    </section>



    <section class="section intro" id="about">
        <div class="container intro__grid">
            <div class="intro__copy">
                <p class="section-kicker">Об институте</p>
                <h2>Фокус на геофизике Арктики</h2>
                <p>Полярный геофизический институт проводит исследования авроральных явлений, магнитосферы, ионосферы, космической погоды и высокоширотных процессов в атмосфере. На сайте собраны новости, публикации, данные наблюдений и другая информация для сотрудников, партнеров и посетителей.</p>
                <a class="text-link" href="about.php">Подробнее об институте</a>

                <dl class="facts facts--intro" aria-label="Краткая информация">
                    <?php foreach ($homeFacts as $factIndex => $fact): ?>
                        <?php $factHref = ['staff.php#units', 'staff.php#people', 'publications.php'][$factIndex] ?? ''; ?>
                        <div class="<?= $factHref !== '' ? 'facts__item facts__item--link' : 'facts__item' ?>">
                            <dt><?= h((string) $fact['value']) ?></dt>
                            <dd><?= h($fact['label']) ?></dd>
                            <?php if ($factHref !== ''): ?>
                                <a class="facts__overlay-link" href="<?= h($factHref) ?>" aria-label="<?= h($fact['label']) ?>"></a>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </dl>
            </div>

            <?php if (!empty($site['home_gallery']['items'])): ?>
                <div class="intro-photo-panel" aria-label="Фотографии площадок ПГИ">
                    <div class="home-photo-slider" data-home-photo-slider>
                        <?php foreach ($site['home_gallery']['items'] as $index => $item): ?>
                            <figure class="home-photo-slide <?= $index === 0 ? 'is-active' : '' ?>" data-home-photo-slide="<?= h((string) $index) ?>">
                                <img src="<?= h($item['image']) ?>" alt="<?= h($item['alt']) ?>" loading="lazy" decoding="async">
                                <figcaption><?= h($item['caption']) ?></figcaption>
                            </figure>
                        <?php endforeach; ?>
                    </div>
                    <div class="home-photo-dots intro-photo-dots" aria-label="Фотографии площадок ПГИ">
                        <?php foreach ($site['home_gallery']['items'] as $index => $item): ?>
                            <button
                                type="button"
                                class="<?= $index === 0 ? 'is-active' : '' ?>"
                                data-home-photo-dot="<?= h((string) $index) ?>"
                                aria-label="<?= h('Показать фото: ' . $item['caption']) ?>"
                                aria-pressed="<?= $index === 0 ? 'true' : 'false' ?>"
                            ></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <section class="section research-section" aria-labelledby="research-title">
        <div class="container">
            <div class="section-head">
                <div>
                    <p class="section-kicker">Наука</p>
                    <h2 id="research-title">Основные направления</h2>
                </div>
                <a class="text-link" href="about.php#research-directions">Все направления</a>
            </div>
            <div class="research-grid">
                <?php foreach ($site['research_areas'] as $area): ?>
                    <article class="research-card">
                        <h3><?= h($area['title']) ?></h3>
                        <p><?= h($area['text']) ?></p>
                    </article>
                <?php endforeach; ?>
            </div>
        </div>
    </section>

    <section class="section news-section" id="news">
        <div class="container">
            <div class="section-head">
                <div>
                    <p class="section-kicker">Новости</p>
                    <h2>Последние сообщения</h2>
                </div>
                <a class="text-link" href="news.php">Все новости</a>
            </div>
            <div class="news-grid home-news-grid">
                <?php foreach (array_slice($site['news'], 0, 4) as $item): ?>
                    <?php $galleryCount = count($item['gallery'] ?? []); ?>
                    <article class="news-card home-news-card">
                        <div class="news-card__media">
                            <?php if (!empty($item['image'])): ?>
                                <img class="news-card__image" src="<?= h($item['image']) ?>" alt="<?= h($item['image_alt']) ?>" loading="lazy" decoding="async">
                            <?php else: ?>
                                <div class="news-card__image-placeholder" aria-hidden="true">
                                    <span><?= h($item['tag']) ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if ($galleryCount > 1): ?>
                                <span class="news-photo-count"><?= h($galleryCount) ?> фото</span>
                            <?php endif; ?>
                        </div>
                        <div class="news-card__meta">
                            <time><?= h($item['date']) ?></time>
                            <span><?= h($item['tag']) ?></span>
                        </div>
                        <h3><?= h($item['title']) ?></h3>
                        <p><?= h($item['summary']) ?></p>
                        <a href="news-item.php?slug=<?= h($item['slug']) ?>" aria-label="Открыть новость: <?= h($item['title']) ?>">Подробнее</a>
                    </article>
                <?php endforeach; ?>
            </div>
            <?php $homePgiDataItems = array_values(array_filter($site['news'], static function (array $item): bool {
                return ($item['tag'] ?? '') === 'Журналы';
            })); ?>
            <?php if (!empty($homePgiDataItems)): ?>
                <section class="news-data-strip home-data-strip" aria-labelledby="home-data-strip-title">
                    <div>
                        <p class="section-kicker">PGI Data</p>
                        <h2 id="home-data-strip-title">Последние выпуски геофизических данных</h2>
                    </div>
                    <div class="news-data-strip__list">
                        <?php foreach (array_slice($homePgiDataItems, 0, 3) as $item): ?>
                            <a href="news-item.php?slug=<?= h($item['slug']) ?>">
                                <time><?= h($item['date']) ?></time>
                                <span><?= h($item['title']) ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
        </div>
    </section>

    <section class="section data-section" id="data">
        <div class="container data-layout">
            <div>
                <p class="section-kicker">Данные</p>
                <h2>Научные материалы и сервисы</h2>
                <p>Раздел объединяет архивы геофизических данных, модели авроральных высыпаний и прогнозы солнечной и геомагнитной активности.</p>
                <a class="text-link" href="data.php">Перейти к данным</a>
            </div>
            <ul class="service-list">
                <?php foreach ($site['data_services'] as $service): ?>
                    <li><?= h($service) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    </section>

    <section class="section contacts" id="contacts">
        <div class="container contacts__grid">
            <div>
                <p class="section-kicker">Контакты</p>
                <h2>Адреса института</h2>
                <a class="text-link" href="contacts.php">Все контакты</a>
            </div>
            <?php foreach ($site['contacts'] as $contact): ?>
                <address>
                    <strong><?= h($contact['title']) ?></strong>
                    <?php foreach ($contact['lines'] as $line): ?>
                        <span><?= h($line) ?></span>
                    <?php endforeach; ?>
                </address>
            <?php endforeach; ?>
        </div>
    </section>
</main>

<?php require __DIR__ . '/includes/footer.php'; ?>
