---
import { getCollection } from 'astro:content';
import { readItems, readSingleton } from '@directus/sdk';

import directus from '@lib/directus';
import type { Post } from '@lib/directusTypes';
import BaseLayout from '@layouts/BaseLayout.astro';
import BlogCard from '@components/blog/BlogCard.astro';
import HeaderSection from '@components/ui/sections/HeaderSection.astro';

export async function getStaticPaths() {
  const categories = await getCollection('categories');
  return categories.map((category) => ({
    params: { slug: category.slug },
    props: { category },
  }));
}

const { category } = Astro.props;

const global = await directus.request(readSingleton('site_global'));
const posts = await directus.request(
  readItems('posts', {
    filter: { published: { _eq: true } },
    fields: ['*'],
    sort: ['-published_date'],
  })
);
const categoriesPosts = posts
  .sort((a: Post, b: Post) => b.published_date.valueOf() - a.published_date.valueOf())
  .filter((b) => {
    return b.category === category.slug;
  });
---

<BaseLayout
  title={category.data.title}
  description={category.data.description}
  structuredData={{
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    inLanguage: 'en-US',
    '@id': Astro.url.href,
    url: Astro.url.href,
    name: `${category.data.title} | ${global.name}`,
    description: category.data.description,
    isPartOf: {
      url: `${global.site_url}/categories`,
      name: global.name,
      description: global.about,
    },
  }}
>
  <HeaderSection
    title={category.data.title}
    subTitle={category.data.description}
    btnExists
    btnTitle="Back to Categories"
    btnURL="/categories"
  />

  <section class="mx-auto mt-10 mb-10 max-w-[85rem] px-4 py-8 sm:px-6 lg:px-8 2xl:max-w-full">
    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
      {categoriesPosts.map((b) => <BlogCard post={b} />)}
    </div>
  </section>
</BaseLayout>
