---
import { CollectionEntry } from "astro:content";
import { astroI18n, createGetStaticPaths, t } from "astro-i18n";
import { getCollection } from "astro:content";
import PageLayout from "../../../layouts/PageLayout.astro";
import { capitalize } from "../../../components/admin/util";
import PostComponent from "../../../components/PostComponent.astro";
import dayjs from "dayjs";
import { ArrowLeftOutline } from "flowbite-svelte-icons";
import { l } from "../../../util/util";
import TagComponent from "../../../components/TagComponent.astro";

export const getStaticPaths = createGetStaticPaths(async () => {
    let posts = await getCollection("announcements", (entry) => entry.id.split("/")[0] === astroI18n.locale);

    const germanPosts = await getCollection("announcements", (entry) => entry.id.split("/")[0] === "de");

    posts.sort((a, b) => dayjs(b.data.created).unix() - dayjs(a.data.created).unix());

    germanPosts.forEach((value) => {
        if (posts.find((post) => post.data.key === value.data.key)) {
            return;
        } else {
            posts.push(value);
        }
    });

    posts = posts.filter((value, index) => index < 20);

    let groupedByTags: Record<string, CollectionEntry<"announcements">[]> = {};
    posts.forEach((post) => {
        post.data.tags.forEach((tag) => {
            if (!groupedByTags[tag.toLowerCase()]) {
                groupedByTags[tag.toLowerCase()] = [];
            }
            groupedByTags[tag.toLowerCase()].push(post);
        });
    });

    return Object.keys(groupedByTags).map((tag) => ({
        params: {
            tag: tag,
        },
        props: {
            posts: groupedByTags[tag],
            tag: tag,
        },
    }));
});

interface Props {
    posts: CollectionEntry<"announcements">[];
    tag: string;
}

const { posts, tag } = Astro.props;
---

<PageLayout title={t("tag.title", { tag: capitalize(tag) })}>
    <div class="pb-2">
        <a class="flex gap-2 items-center" href={l("/ankuendigungen")}>
            <ArrowLeftOutline />
            <TagComponent tag={tag} noLink="true" transition:name={`${tag}-tag-filter`} />
        </a>
    </div>
    {
        posts.map((post, index) => (
            <div>
                <PostComponent post={post} />
            </div>
        ))
    }
</PageLayout>
