<template>
  <div class="flex flex-col h-full overflow-hidden relative" style="border-radius: 12px">
    <!-- Fixed toolbar at top -->
    <div class="shrink-0 flex justify-between bg-white px-4 py-1">
      <h2 class="text-2xl font-bold text-foreground">Test your agent</h2>
      <Button
        :disabled="!draft.id || chatDisabled"
        size="sm"
        variant="outline"
        @click="resetDraftChat"
      >
        <i class="dku-icon-arrow-circular-16"></i>
        Reset</Button
      >
    </div>
    <!-- Chat interface takes remaining space -->
    <div class="flex-1 overflow-hidden">
      <ChatInterface
        v-if="conversationId"
        :key="conversationId"
        :agentIds="[draft.id]"
        :conversationId="conversationId"
        :disableAgentSelection="true"
        :hideModelSelector="true"
        :draftMode="true"
        :modeAgents="true"
        :hideModeSwitching="true"
        :selectedLlm="null"
        :chatDisabled="chatDisabled"
        :skipInitialLoad="skipInitialLoad || skipNextLoad"
        placeholder="Ask Anything"
        :useDraft="hasUnsavedChanges()"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from 'uuid'
import { ref, watch, nextTick } from 'vue'
import ChatInterface from './ChatInterface.vue'
import { Button } from '@/components/ui/button'
import { API } from '@/Api'
import { useAgentStore } from '@/store/agentStore'
import { WT1iser } from '@/lib/wt1'

defineProps<{
  chatDisabled: boolean
  skipInitialLoad?: boolean
}>()
const agentStore = useAgentStore()

const { draft, hasUnsavedChanges } = agentStore
const conversationId = ref(uuidv4())
watch(
  () => draft.id,
  () => {
    conversationId.value = uuidv4()
  }
)

const isResetting = ref(false)
const skipNextLoad = ref(false)

async function resetDraftChat() {
  if (isResetting.value) return
  isResetting.value = true

  try {
    WT1iser.resetConversation()
    await API.deleteDraftConversation(draft.id)
  } catch (err) {
    console.error('Failed to delete draft conversation', err)
  } finally {
    skipNextLoad.value = true
    conversationId.value = uuidv4()

    await nextTick()
    skipNextLoad.value = false
    isResetting.value = false
  }
}
</script>
