<script setup lang="ts">
import { computed } from 'vue';
import MarkdownIt from 'markdown-it'

const props = defineProps<{
    text: string;
    sent: boolean;
}>();

// Initialize Markdown parser
const md = new MarkdownIt({
    breaks: true,       // 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(/^#{1,3}\s(.*)$/gm, '#### $1')
}

// Compute parsed content
const parsedText = computed((): string => {
    const cleaned = cleanMarkdown(props.text || '')
    return md.render(cleaned)
})
</script>

<template>
    <q-chat-message
        :sent="props.sent"
        :text="[text]"
        :bg-color="!sent ? 'secondary' : 'accent'"
        class="bubble"
        :class="sent ? 'user' : 'ai'"
    >
        <div v-html="parsedText"></div>
    </q-chat-message>
</template>

<style scoped>
.bubble {
    margin: 8px;
    border-radius: 12px;
    line-height: 1.5;
    word-break: break-word;
    white-space: pre-wrap;
    overflow-wrap: anywhere;
}

.user {
    align-self: flex-end;
}

.ai {
    align-self: flex-start;
}
</style>
