---
import MainSection from '@components/blocks/MainSection.astro'
import BlogCategory from '@components/blog/BlogCategory.astro'
import BaseLayout from '@layouts/BaseLayout.astro'
import type { CollectionEntry } from 'astro:content'
import { getCollection } from 'astro:content'
import { SITE } from '../../config'
import { timeago } from '../../support/time'

const postMap: Map<string, CollectionEntry<'posts'>[]> = (await getCollection('posts')).sort(
    (a: CollectionEntry<'posts'>, b: CollectionEntry<'posts'>) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
).reduce((acc, obj) => {
    let posts = acc.get(obj.data.category)
    if (!posts) {
        posts = []
    }
    posts.push(obj)

    acc.set(obj.data.category, posts)

    return acc
}, new Map<string, CollectionEntry<'posts'>[]>())

const categories = await getCollection('categories')
const description = 'Каждаю новость для вам мы раскладываем по категориям'
const URL = Astro.url.href
---

<BaseLayout
    title="All Categories"
    description={description}
    structuredData={{
        '@context': 'https://schema.org',
        '@type': 'WebPage',
        'inLanguage': 'ru-RU',
        '@id': URL,
        'url': URL,
        'name': `All Categories - ${SITE.title}`,
        'description': description,
        'isPartOf': {
            '@type': 'WebSite',
            'url': SITE.url,
            'name': SITE.title,
            'description': SITE.description,
        },
    }}

>
    <MainSection title="Категории" subTitle={description} />

    <section class="mx-auto px-4 py-10 sm:px-6 lg:px-8 lg:pt-10 lg:py-14 2xl:max-w-full">
        <div class="grid sm:grid-cols-2 lg:grid-cols-3 items-center gap-6 md:gap-10">
            {
                categories.map(c => (
                    <BlogCategory
                        slug={c.slug}
                        title={c.data.title}
                        description={c.data.description}
                        count={postMap.get(c.slug)?.length ?? 0}
                        publishDate={timeago(postMap.get(c.slug)?.[0]?.data?.pubDate)}
                    />
                ))
            }
        </div>
    </section>
</BaseLayout>
