<script
    setup
    lang="ts"
>
    import { computed } from 'vue';
    // import MarkdownIt from 'markdown-it'
    import { useAuthStore } from 'src/stores/auth-store';
    import type { Message } from 'src/modules/chatbot/models/dialogue-message.model';
    import { useI18n } from 'vue-i18n';

    const { t } = useI18n();
    const auth_store = useAuthStore();

    const { message } = defineProps<{
        message: Message;
    }>();

    const message_text = computed(() => message.text.includes('chatbot.') ? t(message.text) : message.text)

    const is_error = computed(() => message.text.includes('NO_REPLY_RECEIVED') || message.text.includes('SEND_MESSAGE_FAILED'));

    // Initialize Markdown parser
    // const md = new MarkdownIt({
    //     // breaks: false,       // Support line breaks
    //     linkify: true,      // Make URLs clickable
    //     html: false         // Prevent raw HTML injection
    // })

    // // Removes all the h1,h2,h3 to make the Md more user friendly
    // const cleanMarkdown = (markdown: string): string => {
    //     if (!markdown) return ''
    //     return markdown
    //         .replace(/\r\n/g, '\n')                         // normalize Windows line endings
    //         .replace(/([.!?])(\s+)(?=[A-Z])/g, '$1\n')      // insert line break after sentence-ending punctuation
    //         .replace(/\n{3,}/g, '\n\n')                     // squash triple+ line breaks
    //         .replace(/^#{1,3}\s(.*)$/gm, '#### $1')         // downgrade headings
    // }

    // // Compute parsed content
    // const parsedText = computed((): string => {
    //     const cleaned = cleanMarkdown(message.text || '')
    //     if (cleaned.includes('chatbot.')) {
    //         const translated_message = t(message.text);
    //         return md.render(translated_message);
    //     }
    //     return md.render(cleaned);
    // })
</script>

<template>
    <q-chat-message
        v-if="is_error"
        name="SystemBot"
        bg-color="negative"
        text-color="white"
    >
        <div class="row flex-center">
            <q-icon
                name="las la-exclamation-triangle"
                class="col-auto q-pr-xs"
                size="2em"
                color="white"
            />
            <span>{{ message_text }}</span>
        </div>
    </q-chat-message>

    <q-chat-message
        v-else
        :sent="message.sent"
        :name="message.sent ? auth_store.user?.first_name : 'TargoBot'"
        :bg-color="message.sent ? 'accent' : 'info'"
        :text-color="message.sent ? 'white' : ''"
        :text="[message_text]"
    />
</template>

<style scoped>
:deep(.q-message-name) {
    color: white;
    font-weight: bold;
}

:deep(.q-message-text) {
    white-space: pre-wrap;
}
</style>