<?php
// Build structured data (ItemList) for first 10
$itemListElements = [];
foreach (array_slice($articles, 0, 10) as $i => $a) {
    $itemListElements[] = [
        '@type' => 'ListItem',
        'position' => $i + 1,
        'url' => APP_URL . '/articles/' . $a['slug'],
        'name' => $a['title'],
    ];
}
// Breadcrumb
$breadcrumbs = [
    ['name' => Lang::get('home'), 'item' => APP_URL . '/'],
    ['name' => Lang::get('articles'), 'item' => APP_URL . '/articles'],
];
if (!empty($context['category'])) $breadcrumbs[] = ['name' => $context['category']['name'], 'item' => APP_URL . '/articles/category/' . $context['category']['slug']];
if (!empty($context['tag'])) $breadcrumbs[] = ['name' => '#' . $context['tag']['name'], 'item' => APP_URL . '/articles/tag/' . $context['tag']['slug']];

$structuredData = [
    [
        '@type' => 'CollectionPage',
        '@id' => APP_URL . $canonicalPath . '#webpage',
        'name' => $pageTitle,
        'description' => $pageDesc,
        'url' => APP_URL . $canonicalPath,
        'isPartOf' => ['@id' => Schema::webSiteId()],
        'inLanguage' => Lang::getLocale(),
    ],
    [
        '@type' => 'ItemList',
        'itemListElement' => $itemListElements,
    ],
    Schema::breadcrumbs($breadcrumbs),
];
$pageDescription = $pageDesc;
// preload first card image
$firstArticle = $articles[0] ?? null;
if ($firstArticle && !empty($firstArticle['featured_image'])) {
    [$relDir, $basename] = array_pad(explode('|', $firstArticle['featured_image'], 2), 2, '');
    if ($relDir && $basename) {
        $preloadImage = ArticleImagePipeline::defaultSrc($relDir, $basename);
        $preloadImageSrcset = ArticleImagePipeline::srcset($relDir, $basename);
        $preloadImageSizes = '(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw';
    }
}
require APP_ROOT . '/views/articles/_head.php';
?>
<?php require APP_ROOT . '/views/articles/_nav.php'; ?>

<main id="main-content" class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Breadcrumbs -->
    <nav class="text-xs text-gray-500 dark:text-gray-400 mb-6" aria-label="Breadcrumb">
        <ol class="flex flex-wrap items-center gap-1">
            <?php foreach ($breadcrumbs as $i => $b): ?>
                <li>
                    <?php if ($i < count($breadcrumbs) - 1): ?>
                        <a href="<?= htmlspecialchars($b['item']) ?>" class="hover:text-primary-600 dark:hover:text-primary-400"><?= htmlspecialchars($b['name']) ?></a>
                        <span class="mx-1">/</span>
                    <?php else: ?>
                        <span class="text-gray-700 dark:text-gray-300"><?= htmlspecialchars($b['name']) ?></span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ol>
    </nav>

    <header class="mb-8">
        <h1 class="text-4xl sm:text-5xl font-bold text-gray-900 dark:text-white tracking-tight">
            <?php if (!empty($context['category'])): ?>
                <?= htmlspecialchars($context['category']['name']) ?>
            <?php elseif (!empty($context['tag'])): ?>
                #<?= htmlspecialchars($context['tag']['name']) ?>
            <?php else: ?>
                <?= Lang::get('articles') ?>
            <?php endif; ?>
        </h1>
        <p class="mt-3 text-lg text-gray-600 dark:text-gray-400 max-w-2xl"><?= htmlspecialchars($pageDesc) ?></p>

        <!-- Search -->
        <form method="GET" action="<?= APP_URL ?>/articles" class="mt-6 max-w-xl">
            <div class="relative flex items-center">
                <svg class="absolute left-4 w-5 h-5 text-gray-400 dark:text-gray-500 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                <input type="search" name="q" value="<?= htmlspecialchars($q) ?>"
                    placeholder="<?= htmlspecialchars(Lang::get('search_articles')) ?>"
                    class="w-full pl-12 pr-28 py-3.5 rounded-full border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 shadow-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent outline-none transition-shadow">
                <button type="submit" class="absolute right-1.5 px-5 py-2 rounded-full bg-primary-600 hover:bg-primary-700 text-white text-sm font-medium transition-colors shadow-sm">
                    <?= Lang::get('search') ?>
                </button>
            </div>
        </form>
    </header>

    <div class="grid lg:grid-cols-[1fr_280px] gap-8 lg:gap-12">
        <div>
            <!-- Category chips -->
            <?php if (!empty($categories)): ?>
            <div class="mb-6 flex flex-wrap gap-2">
                <a href="<?= APP_URL ?>/articles" class="px-3 py-1.5 rounded-full text-sm <?= empty($context['category']) && empty($context['tag']) ? 'bg-primary-600 text-white' : 'bg-gray-200 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-700' ?> transition-colors"><?= Lang::get('all_categories') ?></a>
                <?php foreach ($categories as $cat):
                    if ((int)$cat['article_count'] === 0) continue;
                    $active = !empty($context['category']) && $context['category']['id'] === $cat['id']; ?>
                <a href="<?= APP_URL ?>/articles/category/<?= htmlspecialchars($cat['slug']) ?>"
                   class="px-3 py-1.5 rounded-full text-sm <?= $active ? 'bg-primary-600 text-white' : 'bg-gray-200 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-700' ?> transition-colors">
                    <?= htmlspecialchars($cat['name']) ?>
                    <span class="opacity-70 ml-1">(<?= (int)$cat['article_count'] ?>)</span>
                </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Grid -->
            <?php if (empty($articles)): ?>
                <div class="rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 p-12 text-center text-gray-500 dark:text-gray-400">
                    <?= Lang::get('no_articles_found') ?>
                </div>
            <?php else: ?>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($articles as $idx => $a):
                    $imgUrl = '';
                    $imgSrcset = '';
                    if (!empty($a['featured_image'])) {
                        [$relDir, $basename] = array_pad(explode('|', $a['featured_image'], 2), 2, '');
                        if ($relDir && $basename) {
                            $imgUrl = ArticleImagePipeline::defaultSrc($relDir, $basename);
                            $imgSrcset = ArticleImagePipeline::srcset($relDir, $basename);
                        }
                    }
                    $url = APP_URL . '/articles/' . $a['slug'];
                    $isFirst = $idx === 0;
                ?>
                <article class="group rounded-2xl overflow-hidden bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-lg transition-all hover:-translate-y-0.5">
                    <a href="<?= htmlspecialchars($url) ?>" class="block">
                        <div class="aspect-[16/9] bg-gray-100 dark:bg-gray-900 overflow-hidden">
                            <?php if ($imgUrl): ?>
                                <img src="<?= htmlspecialchars($imgUrl) ?>"
                                    <?php if ($imgSrcset): ?> srcset="<?= htmlspecialchars($imgSrcset) ?>" sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"<?php endif; ?>
                                    alt="<?= htmlspecialchars($a['featured_image_alt'] ?: $a['title']) ?>"
                                    width="960" height="540"
                                    <?= $isFirst ? 'fetchpriority="high" loading="eager" decoding="sync"' : 'loading="lazy" decoding="async"' ?>
                                    class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500">
                            <?php else: ?>
                                <div class="w-full h-full bg-gradient-to-br from-primary-500/10 via-primary-400/5 to-transparent dark:from-primary-500/20 dark:via-primary-500/10 flex items-center justify-center">
                                    <span class="text-4xl font-bold text-primary-600/30 dark:text-primary-400/40 tracking-tight select-none"><?= htmlspecialchars(mb_strtoupper(mb_substr($a['title'], 0, 1))) ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </a>
                    <div class="p-5">
                        <?php if (!empty($a['category_slug'])): ?>
                            <a href="<?= APP_URL ?>/articles/category/<?= htmlspecialchars($a['category_slug']) ?>"
                               class="inline-block text-xs font-semibold uppercase tracking-wide text-primary-600 dark:text-primary-400 mb-2 hover:underline">
                                <?= htmlspecialchars($a['category_name']) ?>
                            </a>
                        <?php endif; ?>
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white leading-snug mb-2">
                            <a href="<?= htmlspecialchars($url) ?>" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors"><?= htmlspecialchars($a['title']) ?></a>
                        </h2>
                        <p class="text-sm text-gray-600 dark:text-gray-400 line-clamp-3 mb-3"><?= htmlspecialchars($a['excerpt'] ?: HtmlSanitizer::excerpt($a['content'], 140)) ?></p>
                        <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                            <time datetime="<?= htmlspecialchars(date('c', strtotime($a['published_at'] ?: $a['created_at']))) ?>"><?= htmlspecialchars(date('M j, Y', strtotime($a['published_at'] ?: $a['created_at']))) ?></time>
                            <span><?= (int)$a['reading_minutes'] ?> <?= Lang::get('reading_time_min') ?></span>
                        </div>
                    </div>
                </article>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <nav class="mt-10 flex items-center justify-center gap-2" aria-label="Pagination">
                <?php
                $base = rtrim($canonicalPath, '/');
                $buildUrl = function ($p) use ($base, $q) {
                    $qs = [];
                    if ($p > 1) $qs['page'] = $p;
                    if ($q !== '') $qs['q'] = $q;
                    return APP_URL . $base . ($qs ? '?' . http_build_query($qs) : '');
                };
                ?>
                <?php if ($page > 1): ?>
                    <a href="<?= htmlspecialchars($buildUrl($page - 1)) ?>" rel="prev" class="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-sm hover:bg-gray-100 dark:hover:bg-gray-800">&larr;</a>
                <?php endif; ?>
                <span class="px-4 py-2 text-sm text-gray-600 dark:text-gray-400"><?= $page ?> / <?= $totalPages ?></span>
                <?php if ($page < $totalPages): ?>
                    <a href="<?= htmlspecialchars($buildUrl($page + 1)) ?>" rel="next" class="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-sm hover:bg-gray-100 dark:hover:bg-gray-800">&rarr;</a>
                <?php endif; ?>
            </nav>
            <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Sidebar -->
        <aside class="lg:sticky lg:top-24 lg:self-start space-y-8">
            <?php if (!empty($topTags)): ?>
            <div class="pt-6 lg:pt-0 border-t lg:border-t-0 border-gray-200 dark:border-gray-800">
                <h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>
                    <?= Lang::get('tags') ?>
                </h3>
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($topTags as $t): ?>
                    <a href="<?= APP_URL ?>/articles/tag/<?= htmlspecialchars($t['slug']) ?>"
                       class="text-xs px-3 py-1.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-primary-100 dark:hover:bg-primary-900/40 hover:text-primary-700 dark:hover:text-primary-300 border border-transparent hover:border-primary-200 dark:hover:border-primary-800 transition-colors">
                        #<?= htmlspecialchars($t['name']) ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </aside>
    </div>
</main>

<?php require APP_ROOT . '/views/articles/_footer.php'; ?>
