<template>
  <section id="blog" class="BlogOverview content">
    <main>
      <ul class="category-list">
        <li>
          <NuxtLink class="inline-flex-row gap-sm side" to="/blog">
            <span class="chip" :class="{ 'dark' : route.query.category}">Alle {{ articles?.length }}</span>
          </NuxtLink>
        </li>
        <li v-for="(count, category) in allCategoriesAndCount">
          <NuxtLink class="inline-flex-row gap-sm side" :to="`?category=${category}`">
            <span class="chip" :class="{ 'dark' : category !== route.query.category}"><BlogCategory :name="category"/> {{ count }}</span>
          </NuxtLink>
        </li>
      </ul>
      <div class="grid margin-top-middle article-overview">
        <BlogCard v-for="article in firstTen" v-bind="makeBlogCard(article)"/>
      </div>
    </main>
  </section>
</template>

<script setup lang="ts">
import type { BlogCollectionItem } from '@nuxt/content'
import type { Category } from '../../components/Blog/types'

const route = useRoute()

const simpleDate = (date: Date) => {
  date.setDate(date.getDate() + 1)
  return `${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, '0')}-${date.getDate()}`
}

const { data: articles } = await useAsyncData('articles', () => queryCollection('blog')
  .where('date', '<', simpleDate(new Date()))
  .order('date', 'DESC')
  .all(),
)

const firstTen = computed(() => {
  if (route.query.category) {
    return articles.value?.filter(article => article.meta.category === route.query.category).slice(0, 10) ?? []
  }
  return articles.value?.slice(0, 10) ?? []
})

const allCategoriesAndCount = computed(() => {
  const categories = {} as Record<Category, number>
  articles.value?.forEach(article => {
    const category = article.meta.category as Category
    if (category) {
      categories[category] = (categories[category] ?? 0) + 1
    }
  })
  return categories
})

const makeBlogCard = (article: BlogCollectionItem) => ({
  title: article.title,
  description: article.description,
  image: article.thumbnail as string,
  date: article.date as string,
  excerpt: article.excerpt as any,
  link: article.path,
  tags: article.tags as string[],
  category: article.category as Category,
  author: article.author as { name: string, image: string },
})

useHead({
  link: [
    { rel: 'alternate', type: 'application/rss+xml', href: '/blog/rss.xml', title: 'blogfussel' },
  ],
})
</script>