<script setup lang="ts">
import DialoguePhrase from './dialogue-phrase.vue';
import type { Message } from '../types/dialogue-message';
import { useAuthStore } from 'src/stores/auth-store';
import { watch, nextTick, onMounted } from 'vue';

const authStore = useAuthStore();
const currentUser = authStore.user;
const emitUser = defineEmits(['sendRole', 'sendEmail']);

const sendUser = () => {
    emitUser('sendEmail', currentUser.email)
    emitUser('sendRole', currentUser.role)
}

onMounted(() => {
    sendUser();
})

const props = defineProps<{
    messages: Message[];
}>();

watch(props.messages, async () => {
    await nextTick(() => {
        const chatBody = document.querySelector('.chat-body');
        if (chatBody) chatBody.scrollTop = chatBody.scrollHeight;
    });
});
</script>

<template>
    <q-infinite-scroll>
        <template
            v-for="(msg, index) in messages"
            :key="index"
        >
            <DialoguePhrase
                v-if="!msg.isThinking"
                :text="msg.text"
                :sent="msg.sent"
                :name="msg.sent ? currentUser.firstName :
                    $t('chatbot.chat_header')"
                :class="['chat-message', msg.sent ? 'user' : 'ai']"
            />
            <!-- 💭 Thinking bubble -->
            <div
                v-else
                class="chat-message ai flex items-center q-px-md q-py-sm"
            >
                <q-spinner-dots
                    size="20px"
                    color="primary"
                />
                <span class="q-ml-sm text-grey-7">{{ $t('chatbot.chat_thinking') }}</span>
            </div>
        </template>
    </q-infinite-scroll>
</template>