<template>
  <MessageShell
    :role="message.role"
    :name="spec.shell.name"
    :meta="spec.shell.meta"
    :avatar="spec.shell.avatar"
    :color="spec.shell.color"
  >
    <component
      :is="spec.component"
      v-bind="componentProps"
      v-on="componentListeners"
    />
  </MessageShell>
</template>

<script setup lang="ts">
import MessageShell from './messages/MessageShell.vue'
import { computed } from 'vue'
import { useMessageRenderer } from './helpers/useMessageRenderer'
import { useChatStore } from '@/stores/chat'
import type { IChatMessage } from '@/api/types'

interface Props {
  message: IChatMessage
}

const props = defineProps<Props>()
const spec = useMessageRenderer(props.message)
const chatStore = useChatStore()

const componentProps = computed(() => ({
  ...spec.value.props,
  ...(spec.value.type === 'error' ? { loading: chatStore.isLoading } : {}),
}))

const componentListeners = computed(() =>
  spec.value.type === 'error' ? { retry: handleRetry } : {}
)

function handleRetry(): void {
  if (chatStore.isLoading) return
  chatStore.resendLastUserMessage()
}
</script>

<style scoped>
/* Layout is handled by MessageShell; ChatMessage is now a pure dispatcher. */
</style>
