---
import {Aside, Badge, Icon} from '@astrojs/starlight/components';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import markdownit from 'markdown-it'
import markdownItMark from 'markdown-it-mark'
const md = markdownit().use(markdownItMark);

interface Props {
    word: {
    english: string;
    hindi: string;
    gender?: "m" | "f";
    note?: string;
    examples?: Array<{
        hindi: string;
        english: string;
        note?: string;
    }>
    see_also?: string[];
}
}

const {word}: Props = Astro.props;

const gender_lookup: Record<"m" | "f", ["note" | "tip", string]> = {
    "m": ["note", "masculine"],
    "f": ["tip", "feminine"],
};

function highlight(text: string, term: string) {
    const terms = term.split(',').map(t => t.trim()).filter(Boolean);
    const regex = new RegExp(`(${terms.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`, 'gi');
    const parts = text.split(regex);
    return md.renderInline(parts.map((part) => regex.test(part) ? `**${part}**` : part).join(''));
}
---
<li id={word.hindi} class="word-entry">
<AnchorHeading level="4" id={word.hindi} class="word-heading" style="font-weight: normal;"> 
    {word.hindi} <Icon name="right-arrow" class="icon-inline" /><span>{word.english}</span>
{word.gender && <Badge variant={gender_lookup[word.gender][0]} text={gender_lookup[word.gender][1]} class="gender-badge"/>} 
</AnchorHeading>
{word.note && 
    <div set:html={md.renderInline(word.note)}></div>
}
{ 
word.examples &&( 
    <>
    <p>For example,</p>
    <ol>
    {word.examples.map((e) => (
        <li class="word-examples">
            <p>
                <span set:html={highlight(e.hindi, word.hindi)}></span> <Icon name="right-arrow" class="icon-inline" /> <span set:html={highlight(e.english,  word.english)}></span>
            </p>
            {e.note && (
                <Aside type="note" title="Note">
                    <p set:html={highlight(e.note, word.hindi)}></p>
                </Aside>
            )}
        </li>
    ))}
    </ol>
    </> )}
    { word.see_also && (
        <p><b>See also:</b>
            { word.see_also.map((ref, i) => (
                <>
                    <span set:html={md.renderInline(ref)}></span>{ i < word.see_also!.length - 1 ? "; " : '' }
                </>
            )) }
        </p>
    )}
</li>