---
import StarlightPage from "@astrojs/starlight/components/StarlightPage.astro";
import AnchorHeading from "@astrojs/starlight/components/AnchorHeading.astro";
import VocabWord from "@/components/VocabWord.astro";
import markdownit from "markdown-it";
import markdownItMark from "markdown-it-mark";
import { storage } from "@/lib/storage";
import { titlecase } from "@/lib/utils";

function typeToTitle(type: string | null | undefined) {
    if (!type) return "";
    const partsOfSpeech = ["noun", "verb", "adjective", "adverb"];
    const maybePlural = partsOfSpeech.includes(type.toLowerCase()) ? "s" : "";
    return titlecase(type!) + maybePlural;
}

const md = markdownit().use(markdownItMark);

export const prerender = false;

const { tag } = Astro.params;

if (!tag) {
    return Astro.redirect("/vocabulary");
}

const allTags = await storage.getAllTags();
const currentTag = allTags.find((t) => t.name === tag);

if (!currentTag) {
    return Astro.redirect("/vocabulary");
}

const words = await storage.getWordsByTag(tag);

const wordtypes = [...new Set(words.map((word) => word.type).filter(Boolean))];
const wordsByType = wordtypes.map((type) => ({
    type: typeToTitle(type),
    words: words.filter((word) => word.type === type),
}));

const headings = wordsByType.flatMap(({ type, words }) => {
    return [
        {
            text: type,
            depth: 2,
            slug: type!.toLowerCase().replace(/\s+/g, "-"),
        },
    ].concat(
        words.map((word) => ({
            text: word.hindi,
            depth: 3,
            slug: word.hindi.toLowerCase().replace(/\s+/g, "-"),
        })),
    );
});
---

<StarlightPage
    frontmatter={{ title: "Vocabulary: " + titlecase(tag) }}
    headings={headings}
>
    {
        currentTag.description && (
            <div set:html={md.render(currentTag.description)} />
        )
    }
    {
        wordsByType.map(({ type, words }) => (
            <div class="word-type-section">
                <AnchorHeading level="3" id={type!}>
                    {type}
                </AnchorHeading>
                <ul class="part-of-speech-list">
                    {words.map((word) => (
                        <VocabWord {word} />
                    ))}
                </ul>
            </div>
        ))
    }
</StarlightPage>
