---
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';

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

export const prerender = false;

function titlecase(str: string) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

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: titlecase(type!) + "s",
    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>
