<script setup lang="ts">
import { computed } from 'vue'
import ChatInterface from '@/components/ChatInterface.vue'
import { useChatStore } from '@/store/chatStore'
import { useConversationStore } from '@/store/conversationStore'
import CustomMainHeader from '@/components/CustomMainHeader.vue'

defineProps<{
  submit: boolean
}>()

// Use the centralized chat and conversation store
const chatStore = useChatStore()
const conversationStore = useConversationStore()
// Get initial message from chat store
const initialMessage = computed(() => {
  const messages = chatStore.messages
  const result = messages.length > 0 && messages[0].role === 'user' ? messages[0].content : null
  return result
})

// When a conversation is created, update the store
function onConversationCreated(_payload: { conversationId: string }) {
  chatStore.setConversation(_payload.conversationId, chatStore.agentIds)
  conversationStore.setActiveConversation(_payload.conversationId)
}

// When a conversation is updated, update the store
function onConversationUpdated(payload: { conversationId: string; agentIds: string[] }) {
  chatStore.updateAgents(payload.agentIds)
}

// Clear initial message after it's been sent
function clearInitialMessage() {
  chatStore.setMessages([])
}
</script>

<template>
  <header class="w-full h-[58px] md:h-[4px] py-1.5 md:py-0 border-t-[4px] border-t-primary">
    <CustomMainHeader />
  </header>

  <!-- Chat interface takes remaining space -->
  <div v-if="chatStore.conversationId" class="flex-1 overflow-hidden bg-white">
    <ChatInterface
      :agentIds="chatStore.agentIds"
      :conversationId="chatStore.conversationId!"
      :activeOnlyAgents="true"
      :initialMessage="initialMessage"
      @conversationCreated="onConversationCreated"
      @conversationUpdated="onConversationUpdated"
      @initialMessageSent="clearInitialMessage"
      :submit="submit"
      placeholder="Ask Anything"
    />
  </div>
</template>
