<script setup lang="ts">
import { computed } from 'vue'
import VueMarkdown from 'vue-markdown-render'
import { useTypewriter } from '@/lib/composables/useTypewriter'

const props = defineProps<{
  messageContent: string
  senderType: number
  messageId: number
  onType?: () => void
}>()

const seenMessages = new Set<number>()

const safeContent = computed(() => props.messageContent ?? '')
const shouldAnimate = computed(
  () => (props.senderType === 2 || props.senderType === 3) && !seenMessages.has(props.messageId)
)

const { displayedText, animate } = useTypewriter(20)

// Start animation when content changes
if (shouldAnimate.value) {
  animate(safeContent.value, props.onType)
}

const finalMessage = computed(() => {
  if (!shouldAnimate.value) return safeContent.value
  if (displayedText.value === safeContent.value) {
    seenMessages.add(props.messageId)
  }
  return displayedText.value
})
</script>

<template>
  <div
    dir="auto"
    :class="[
      'babylai:rounded-2xl babylai:p-4',
      senderType === 1
        ? 'babylai:bg-primary-500 babylai:text-black-white-50 babylai:max-w-[220px]'
        : 'babylai:bg-card',
    ]"
  >
    <VueMarkdown
      :source="finalMessage"
      :options="{ html: false }"
      class="babylai:m-0 babylai:leading-snug babylai:text-sm babylai:font-sans babylai:wrap-break-word"
    />
  </div>
</template>
