<template>
  <!-- Full-window drag & drop backdrop -->
  <Teleport to="body">
    <Transition name="fade">
      <div
        v-if="isDragging && !draftMode"
        class="fixed inset-0 z-[9999] bg-white/60"
        @dragover.prevent
        @dragleave="onDragLeave"
        @drop.prevent="onDrop"
      >
        <!-- Content centered relative to main content area (offset from sidebar) -->
        <div
          class="absolute inset-y-0 right-0 flex items-center justify-center transition-[left] duration-200 ease-linear"
          :style="{ left: sidebarOffset }"
        >
          <div class="flex flex-col items-center gap-1 p-12 text-foreground">
            <i class="dku-icon-folder-open-48"></i>
            <div class="text-center">
              <p class="mt-1 font-semibold">Drag and drop files</p>
              <p>to attach to this conversation</p>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>

  <div class="shrink-0 pb-3 bg-white">
    <div class="max-w-3xl mx-auto">
      <div
        v-if="
          selectedAgents.length ||
          showLiveProgressChip ||
          (!_modeAgents && activeLLMShortName) ||
          conversationAttachments?.length
        "
        class="mb-1 flex justify-between items-center h-[32px]"
      >
        <div class="flex items-center gap-2">
          <!-- selected-agent chips (when in agent mode) -->
          <div v-if="_modeAgents">
            <!-- SINGLE selection -->
            <template v-if="selectedAgents.length === 1 && !chatDisabled">
              <Badge :class="chipClasses(selectedAgents[0])" class="text-sm my-0">
                <i class="dku-icon-ai-agent-12" />
                <span>Chat with {{ getAgentName(selectedAgents[0]) }}</span>
                <AgentStatusBadge
                  v-if="isAgentDeleted(selectedAgents[0], allAgents)"
                  status="deleted"
                  class="ml-1"
                />
                <AgentStatusBadge
                  v-else-if="!isAgentActive(selectedAgents[0], allAgents) || useDraft"
                  status="draft"
                  class="ml-1"
                />
              </Badge>
            </template>

            <!-- MULTI selection -->
            <template v-else-if="selectedAgents.length > 1">
              <Tooltip>
                <TooltipTrigger asChild>
                  <Badge class="cursor-default text-sm" :class="summaryChipClass">
                    <i class="dku-icon-ai-agent-12" />
                    <span>Chat with {{ selectedAgents.length }} agents</span>

                    <!-- draft count badge -->
                    <AgentStatusBadge
                      v-if="draftCount > 0"
                      status="draft"
                      class="ml-1"
                      :label="`${draftCount} draft${draftCount > 1 ? 's' : ''}`"
                    />

                    <!-- deleted count badge -->
                    <AgentStatusBadge
                      v-if="deletedCount > 0"
                      status="deleted"
                      class="ml-1"
                      :label="`${deletedCount} deleted${deletedCount > 1 ? 's' : ''}`"
                    />
                  </Badge>
                </TooltipTrigger>

                <TooltipContent side="top" hide-arrow class="w-[300px]">
                  <div class="space-y-1">
                    <div
                      v-for="id in selectedAgents"
                      :key="id"
                      class="flex items-center space-x-2 text-sm"
                      :class="[isAgentActive(id, allAgents) ? '' : 'opacity-60']"
                    >
                      <i :class="getAgentTypeIcon(id)" />
                      <span>{{ getAgentName(id) }}</span>
                      <AgentStatusBadge v-if="isAgentDeleted(id, allAgents)" status="deleted" />
                      <AgentStatusBadge v-else-if="!isAgentActive(id, allAgents)" status="draft" />
                    </div>
                  </div>
                </TooltipContent>
              </Tooltip>
            </template>
          </div>

          <!-- LLM badge (when in LLM mode) -->
          <div v-else-if="!_modeAgents && activeLLMShortName">
            <Badge class="text-sm my-0">
              <i class="dku-icon-llm-12" />
              <span>{{ activeLLMShortName }}</span>
            </Badge>
          </div>
          <!-- Ready attachments badge -->
          <Tooltip v-if="conversationAttachments?.length">
            <TooltipTrigger asChild>
              <Badge
                class="cursor-pointer text-sm transition-colors"
                @click="emits('openAttachmentsPanel')"
              >
                <i class="dku-icon-file-16" />
                <span
                  >{{ conversationAttachments.length }} file{{
                    conversationAttachments.length > 1 ? 's' : ''
                  }}</span
                >
              </Badge>
            </TooltipTrigger>
            <TooltipContent v-if="!attachmentsPanelOpen" side="top" hide-arrow>
              <div class="text-sm">
                <ul class="space-y-0.5">
                  <li
                    v-for="att in conversationAttachments.slice(0, 5)"
                    :key="att.id"
                    class="truncate max-w-[200px] flex items-center gap-1.5"
                  >
                    <i :class="getAttachmentIcon(att.document_name, 12)"></i>
                    {{ att.document_name }}
                  </li>
                  <li v-if="conversationAttachments.length > 5" class="text-muted-foreground">
                    +{{ conversationAttachments.length - 5 }} more...
                  </li>
                </ul>
              </div>
            </TooltipContent>
          </Tooltip>
        </div>

        <!-- live-progress chip -->
        <Button
          variant="ghost"
          @click="onOpenEventLog"
          v-if="showLiveProgressChip"
          class="ml-auto text-foreground max-w"
        >
          <i :class="[lastLiveEventInfo?.icon, 'text-primary']"></i>
          <span
            v-html="lastLiveEventInfo?.label"
            class="truncate max-w-[200px] sm:max-w-[200px] lg:max-w-[300px] lightwave"
          ></span>
        </Button>
      </div>
      <div
        v-if="
          !selectedAgents.length &&
          !showLiveProgressChip &&
          !(!_modeAgents && activeLLMShortName) &&
          !conversationAttachments?.length &&
          (exampleQuestions?.length || route.name == 'Home')
        "
        class="mb-1 flex justify-between items-center h-[32px]"
        aria-hidden="true"
      ></div>
      <input
        ref="fileInput"
        type="file"
        multiple
        class="hidden"
        @change="handleFileSelect"
        :accept="fileAccept"
      />

      <Tooltip>
        <TooltipTrigger asChild>
          <!-- Input box -->
          <Card
            class="py-2 px-3 rounded-md shadow-none focus-within:border-primary transition-colors"
            :class="{ 'bg-muted hover:bg-[#dcdcde]': chatDisabled || isUploading }"
          >
            <div class="flex flex-col space-y-2">
              <!-- File attachments preview  -->
              <div
                v-if="attachments.length > 0"
                class="w-full flex gap-2 overflow-x-auto min-w-0 no-scrollbar"
              >
                <FileAttachment
                  v-for="attachment in attachments"
                  :key="attachment.id"
                  :attachment="attachment"
                  :show-dismiss="!attachment.loading"
                  :loading="attachment.loading ?? false"
                  @remove="removeAttachment(attachment.id)"
                />
              </div>
              <Textarea
                ref="textareaRef"
                v-model="newMessage"
                :autofocus="props.autofocus"
                :placeholder="inputPlaceholder"
                :disabled="chatDisabled || hasDeletedSelected || isUploading"
                rows="4"
                class="w-full resize-none p-0 placeholder:text-sm rounded-none max-h-[35vh]"
                @keydown.enter.exact="onEnterKey"
                @compositionstart="onCompositionStart"
                @compositionend="onCompositionEnd"
              />
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <Tooltip v-if="enableDocumentUpload">
                    <TooltipTrigger asChild>
                      <span class="inline-flex">
                        <Button
                          variant="outline"
                          @click="triggerFileInput"
                          :disabled="
                            chatDisabled ||
                            hasDeletedSelected ||
                            isStreaming ||
                            isUploading ||
                            !enableDocumentUpload
                          "
                          :aria-disabled="
                            chatDisabled ||
                            hasDeletedSelected ||
                            isStreaming ||
                            isUploading ||
                            !enableDocumentUpload
                          "
                          :class="[
                            'px-2 py-1',
                            (chatDisabled ||
                              hasDeletedSelected ||
                              isStreaming ||
                              isUploading ||
                              !enableDocumentUpload) &&
                              'pointer-events-none',
                          ]"
                        >
                          <i class="dku-icon-attach-16"></i>
                        </Button>
                      </span>
                    </TooltipTrigger>
                    <TooltipContent hide-arrow>
                      <span> Add files and images </span>
                    </TooltipContent>
                  </Tooltip>

                  <UnifiedSelector
                    v-if="!disableAgentSelection"
                    v-model:selectedAgents="selectedAgents"
                    v-model:modeAgents="_modeAgents"
                    v-model:selectedLlm="selectedLlm"
                    :activeOnly="activeOnlyAgents"
                    :showExamplesToggle="showExamplesToggleInDropdown"
                    :exampleQuestions="exampleQuestions"
                    :disabled="chatDisabled || hasDeletedSelected || isStreaming"
                    :allowModeSwitching="settingsAllowModeSwitching && !modeSwitchingDisabled"
                    :modeSwitchingDisabledReason="modeSwitchingDisabledReason"
                  />
                </div>
                <div class="flex items-center">
                  <template v-if="!isStreaming">
                    <Button
                      @click="handleSend"
                      :disabled="chatDisabled || hasDeletedSelected || isUploading"
                      :class="sendButtonClasses"
                    >
                      <i class="dku-icon-arrow-right-20"></i>
                    </Button>
                  </template>
                  <template v-else>
                    <Button @click="cancelStream">
                      <i class="dku-icon-square-circle-outline-16 text-xl"></i>
                    </Button>
                  </template>
                </div>
              </div>
            </div>
          </Card>
        </TooltipTrigger>
        <TooltipContent v-if="chatDisabled" hide-arrow>
          Fill in the instructions to test the agent
        </TooltipContent>
      </Tooltip>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, watch, onMounted, onUnmounted } from 'vue'
import AgentStatusBadge from '@/components/AgentStatusBadge.vue'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Card } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import UnifiedSelector from './UnifiedSelector.vue'
import { isAgentActive, isAgentDeleted } from '@/composables/useAgents'
import { usePrefStore } from '@/store/prefStore'
import { useConversationStore } from '@/store/conversationStore'
import { Tooltip, TooltipTrigger, TooltipContent } from './ui/tooltip'
import { useSidebar } from './ui/sidebar'
import { SIDEBAR_WIDTH, SIDEBAR_WIDTH_ICON } from './ui/sidebar/utils'
import { API } from '@/Api'
import type { SuggestedExample } from '@/types/agent'
import type { MessageAttachment } from '@/types/messages'
import FileAttachment from './FileAttachment.vue'
import { getAttachmentIcon } from '@/lib/fileUtils'
import { toast } from 'vue-sonner'
import { UPLOAD_FAILED } from '@/constants/notifs'

const props = withDefaults(
  defineProps<{
    selectedAgents: string[]
    allAgents: any[]
    isStreaming: boolean
    chatDisabled: boolean
    hasDeletedSelected: boolean
    inputPlaceholder: string
    disableAgentSelection?: boolean
    modeAgents: boolean
    selectedLlm: string | null
    hideModeSwitching?: boolean
    disableModeSwitching?: boolean
    activeOnlyAgents?: boolean
    showLiveProgressChip?: boolean
    lastLiveEventInfo?: { label: string; icon: any }
    activeEventLogMessageId?: string | null
    openEventLogPanel?: (msg: any) => void
    hideExampleToggle?: boolean
    exampleQuestions?: SuggestedExample[]
    useDraft?: boolean
    conversationAttachments?: MessageAttachment[]
    attachmentsPanelOpen?: boolean
    autofocus?: boolean
    draftMode?: boolean
  }>(),
  {
    autofocus: true,
  }
)

const emits = defineEmits<{
  (e: 'update:selectedAgents', v: string[]): void
  (e: 'send', data: { text: string; attachments?: MessageAttachment[] }): void
  (e: 'cancel'): void
  (e: 'update:hasContent', hasContent: boolean): void
  (e: 'update:modeAgents', show: boolean): void
  (e: 'update:selectedLlm', llmId: string | null): void
  (e: 'openAttachmentsPanel'): void
}>()

const attachments = ref<MessageAttachment[]>([])
const fileInput = ref<HTMLInputElement | null>(null)
const isUploading = ref(false)

// Drag and drop state
const isDragging = ref(false)
let dragCounter = 0

const appConfig: AppConfig | null = getAppConfig()
const userId = computed(() => appConfig?.user?.login || null)

const prefStore = usePrefStore()

// Sidebar state for drag overlay positioning
const { open: sidebarOpen, isMobile } = useSidebar()
const sidebarOffset = computed(() => {
  if (isMobile.value) return '0px'
  return sidebarOpen.value ? SIDEBAR_WIDTH : SIDEBAR_WIDTH_ICON
})

// LLM name for the badge (when in LLM mode)
const activeLLMShortName = computed(() => {
  if (_modeAgents.value) return null
  const llmId = props.selectedLlm ?? prefStore.uiConf?.default_llm ?? prefStore.baseLlmid
  const llm = prefStore.aHLlms?.find((l) => l.id === llmId)
  return llm?.shortName || null
})

// Whether mode switching is disabled (based on upload state)
const modeSwitchingDisabled = computed(() => {
  return (
    isUploading.value ||
    attachments.value.length > 0 ||
    !!props.disableModeSwitching ||
    conversationStore.activeConversation?.has_attachments
  )
})

// Reason why mode switching is disabled
const modeSwitchingDisabledReason = computed(() => {
  // Check admin disabled feature first (takes precedence)
  if (!settingsAllowModeSwitching.value) {
    return 'admin_disabled'
  }

  // Check upload/file reasons
  if (
    isUploading.value ||
    attachments.value.length > 0 ||
    conversationStore.activeConversation?.has_attachments
  ) {
    return 'attachments'
  }
  // Other reasons
  if (props.disableModeSwitching) {
    return 'other'
  }
  return null
})

// Show examples toggle inside the unified dropdown
const showExamplesToggleInDropdown = computed(() => {
  if (props.hideExampleToggle || conversationStore.isActiveConversationInitializing) return false
  return !props.isStreaming && conversationStore.showAgentPromptState
})
const _modeAgents = ref(props.modeAgents) // true = agents only, false = llm
watch(
  () => _modeAgents.value,
  (newVal) => {
    emits('update:modeAgents', newVal)
  }
)
watch(
  () => props.modeAgents,
  (newVal) => {
    _modeAgents.value = newVal
  }
)
import { useRoute } from 'vue-router'
import { EventName, WT1iser } from '@/lib/wt1'
import { type AppConfig, getAppConfig } from '@/lib/utils.ts'
const route = useRoute()

const conversationStore = useConversationStore()

const conversationAttachments = computed(() => props.conversationAttachments || [])
/* -------------------------------------------------------------------------------- */
const newMessage = ref('')
const isComposing = ref(false)

watch(
  () => newMessage.value,
  (newVal) => {
    emits('update:hasContent', newVal.trim().length > 0)
  },
  { immediate: true }
)
const settingsAllowModeSwitching = computed(
  () => prefStore.uiConf?.allow_chat_to_llm && !props.hideModeSwitching
)
const selectedAgents = computed({
  get: () => props.selectedAgents,
  set: (v: string[]) => emits('update:selectedAgents', v),
})
const selectedLlm = computed({
  get: () => props.selectedLlm,
  set: (v: string | null) => emits('update:selectedLlm', v),
})
const textareaRef = ref<{ focus?: () => void } | null>(null)

const enableDocumentUpload = computed(() => prefStore.uiConf?.enable_document_upload ?? true)
const extractionMode = computed(() => prefStore.uiConf?.extraction_mode ?? 'pagesScreenshots')
const fileAccept = computed(() =>
  enableDocumentUpload.value && extractionMode.value === 'pagesScreenshots'
    ? '.txt,.pdf,.docx,.png,.jpg,.jpeg,.pptx,.md'
    : '.txt,.pdf,.docx,.pptx,.md'
)

function focusInput() {
  if (!props.autofocus) return
  // If disabled, focus won’t work anyway, but safe to call
  nextTick(() => textareaRef.value?.focus?.())
}

function setMessage(text: string, opts?: { attachments?: MessageAttachment[] }) {
  newMessage.value = text
  if (opts?.attachments) {
    attachments.value = [...opts.attachments]
  }
  nextTick(() => focusInput())
}

function clearAttachments() {
  attachments.value = []
}

defineExpose({ focusInput, setMessage, clearAttachments })

/* -------------------------------------------------------------------------------- */
// Actions

async function handleFileSelect(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (!files || files.length === 0) return

  // Create temporary loading attachments immediately
  const tempAttachments: MessageAttachment[] = Array.from(files).map((file, index) => ({
    id: `temp-${Date.now()}-${index}`,
    document_name: file.name,
    size: file.size,
    type: file.type,
    loading: true,
  }))

  // Add loading attachments to show immediately
  attachments.value.push(...tempAttachments)
  const tempIds = tempAttachments.map((a) => a.id)

  // Check if there is already an active conversation. If not, create one.
  let convId = conversationStore.activeConversationId
  if (!convId) {
    try {
      // API call to create a new conversation (empty title, no messages)
      const response = await API.createConversation({
        title: '',
        agentIds: selectedAgents.value || [],
      })
      convId = response.data.id
      conversationStore.setActiveConversation(convId)
      // Optional: add to catalog store
      // conversationCatalogStore.addNewConversation(convId, selectedAgents.value || []);
    } catch (e) {
      console.error('Failed to create new conversation', e)
      // Remove temp attachments on failure
      attachments.value = attachments.value.filter((a) => !tempIds.includes(a.id))
      return
    }

    if (!convId) {
      console.error('No conversation id returned after creating new conversation')
      // Remove temp attachments on failure
      attachments.value = attachments.value.filter((a) => !tempIds.includes(a.id))
      return
    }
  }

  // Upload the documents only with convId and userId
  try {
    isUploading.value = true
    const formData = new FormData()
    formData.append('conv_id', convId)
    formData.append('user_id', userId.value || '')
    Array.from(files).forEach((file) => formData.append('files', file))
    WT1iser.uploadFiles(files.length)
    const uploadResponse = await API.uploadFiles(formData)

    // Remove temp attachments and add the real uploaded ones
    attachments.value = attachments.value.filter((a) => !tempIds.includes(a.id))
    attachments.value.push(...uploadResponse.data.attachments)

    // Flip to LLM mode and select first LLM if none is selected
    if (_modeAgents.value) {
      _modeAgents.value = false // watcher will emit update:modeAgents
      prefStore.setShowChatExamples(false)
    }
    if (!selectedLlm.value) {
      const ui: any = usePrefStore().uiConf || {}
      const baseLlmid: any = usePrefStore().baseLlmid
      const firstId = ui.default_llm || baseLlmid
      if (firstId) {
        selectedLlm.value = firstId
      }
    }
  } catch (error) {
    console.error('Upload failed:', error)
    WT1iser.error(EventName.UploadFiles, 'File upload failed')
    const err: any = error as any
    const message = err?.response?.data?.error || UPLOAD_FAILED
    toast.error(message)
    // Remove temp attachments on failure
    attachments.value = attachments.value.filter((a) => !tempIds.includes(a.id))
  } finally {
    isUploading.value = false
  }

  // Clear the input value so the same file can be selected again
  if (event.target as HTMLInputElement) {
    ;(event.target as HTMLInputElement).value = ''
  }
}

function triggerFileInput() {
  fileInput.value?.click()
}

function removeAttachment(key: string) {
  const idx = attachments.value.findIndex(
    (a: any) => a?.document_path === key || a?.path === key || a?.id === key
  )
  if (idx === -1) return
  const [attachment] = attachments.value.splice(idx, 1)

  const a: any = attachment as any
  const path = a?.document_path || a?.path
  if (path) {
    API.deleteUploadedAttachment(path).catch((e: any) => {
      console.warn('Failed to delete uploaded attachment on server:', e)
    })
  }

  if (attachments.value.length === 0 && !conversationStore.activeConversation?.has_attachments) {
    if (conversationStore.activeConversationId) {
      conversationStore.updateHasAttachments(conversationStore.activeConversationId, false)
      if (!settingsAllowModeSwitching.value) {
        _modeAgents.value = true
      }
    }
  }
}

/* -------------------------------------------------------------------------------- */
// Drag and drop handlers
function onWindowDragEnter(e: DragEvent) {
  // Only show backdrop if dragging files and upload is enabled
  if (
    !enableDocumentUpload.value ||
    props.chatDisabled ||
    props.hasDeletedSelected ||
    props.draftMode
  )
    return
  if (e.dataTransfer?.types.includes('Files')) {
    dragCounter++
    isDragging.value = true
  }
}

function onWindowDragLeave(_e: DragEvent) {
  dragCounter--
  if (dragCounter <= 0) {
    dragCounter = 0
    isDragging.value = false
  }
}

function onDragLeave(e: DragEvent) {
  // Only hide if leaving the backdrop itself (not entering a child)
  if (e.currentTarget === e.target) {
    dragCounter = 0
    isDragging.value = false
  }
}

function onDrop(e: DragEvent) {
  dragCounter = 0
  isDragging.value = false

  const files = e.dataTransfer?.files
  if (!files || files.length === 0) return

  // Filter files by accepted types
  const acceptedExtensions = fileAccept.value.split(',').map((ext) => ext.trim().toLowerCase())
  const validFiles: File[] = []

  Array.from(files).forEach((file) => {
    const ext = '.' + file.name.split('.').pop()?.toLowerCase()
    if (acceptedExtensions.includes(ext)) {
      validFiles.push(file)
    }
  })

  if (validFiles.length === 0) {
    toast.error('No valid files to upload. Accepted formats: ' + fileAccept.value)
    return
  }

  // Create a synthetic event to reuse handleFileSelect
  const dataTransfer = new DataTransfer()
  validFiles.forEach((file) => dataTransfer.items.add(file))

  const syntheticEvent = {
    target: { files: dataTransfer.files, value: '' },
  } as unknown as Event

  handleFileSelect(syntheticEvent)
}

function onWindowDrop(e: DragEvent) {
  // Prevent default browser behavior for drops outside our drop zone
  e.preventDefault()
  dragCounter = 0
  isDragging.value = false
}

onMounted(() => {
  window.addEventListener('dragenter', onWindowDragEnter)
  window.addEventListener('dragleave', onWindowDragLeave)
  window.addEventListener('dragover', (e) => e.preventDefault())
  window.addEventListener('drop', onWindowDrop)
})

onUnmounted(() => {
  window.removeEventListener('dragenter', onWindowDragEnter)
  window.removeEventListener('dragleave', onWindowDragLeave)
  window.removeEventListener('dragover', (e) => e.preventDefault())
  window.removeEventListener('drop', onWindowDrop)
})

function handleSend() {
  if (
    !props.isStreaming &&
    !isUploading.value &&
    (newMessage.value.trim() || attachments.value.length > 0)
  ) {
    const messageToSend = newMessage.value.trim()

    WT1iser.askQuestion(
      !isAgentActive(selectedAgents.value[0], props.allAgents) || props.useDraft,
      _modeAgents.value,
      selectedAgents.value?.length || 0,
      attachments.value.length
    )
    emits('send', {
      text: messageToSend,
      attachments: [...attachments.value],
    })

    // Reset state after sending
    newMessage.value = ''
    attachments.value = []
  }
}
function onEnterKey(e: KeyboardEvent) {
  // Don't send if user is in the middle of IME composition (e.g., typing Japanese)
  if (isComposing.value) {
    return
  }

  const canSend =
    !props.isStreaming &&
    !isUploading.value &&
    !props.chatDisabled &&
    !props.hasDeletedSelected &&
    (hasContentToSend.value || attachments.value.length > 0)

  if (canSend) {
    const messageToSend = newMessage.value.trim()

    WT1iser.askQuestion(
      !isAgentActive(selectedAgents.value[0], props.allAgents) || props.useDraft,
      _modeAgents.value,
      selectedAgents.value?.length || 0,
      attachments.value.length
    )
    e.preventDefault()
    emits('send', {
      text: messageToSend,
      attachments: [...attachments.value],
    })

    // Reset state after sending
    newMessage.value = ''
    attachments.value = []
  }
}

function onCompositionStart() {
  isComposing.value = true
}

function onCompositionEnd() {
  isComposing.value = false
}

function cancelStream() {
  emits('cancel')
}
function onOpenEventLog() {
  if (props.openEventLogPanel) {
    WT1iser.messageViewEventLog()
    props.openEventLogPanel({ id: null })
  }
}

/* -------------------------------------------------------------------------------- */
// Helpers
function getAgentName(id: string) {
  let agent: any
  if (Array.isArray(props.allAgents)) {
    const agents = props.allAgents.filter((a: any) => a.id === id)
    if (agents.length > 1) {
      if (props.useDraft) {
        agent = agents.find((a: any) => a.status === 'draft')
      } else {
        agent = agents.find((a: any) => a.status === 'active')
      }
    } else {
      agent = agents[0]
    }
  } else {
    // Fallback in case a Map is provided
    agent = (props.allAgents as any)?.get?.(id)
  }
  return agent?.name ?? id
}

function getAgentTypeIcon(id: string) {
  let agent: any
  if (Array.isArray(props.allAgents)) {
    agent = props.allAgents.find((a: any) => a.id === id)
  } else {
    // Fallback in case a Map is provided
    agent = (props.allAgents as any)?.get?.(id)
  }
  if (agent?.isEnterprise) return 'dku-icon-briefcase-16'
  if (agent?.isShared) return 'dku-icon-share-16'
  return 'dku-icon-user-16'
}

function chipClasses(id: string) {
  if (isAgentDeleted(id, props.allAgents)) return ''
  return isAgentActive(id, props.allAgents) && !props.useDraft ? '' : 'bg-[#D4D4D8] text-foreground'
}

/* -------------------------------------------------------------------------------- */
// Counts & classes
const deletedCount = computed(
  () => selectedAgents.value.filter((id) => isAgentDeleted(id, props.allAgents)).length
)
const draftCount = computed(
  () =>
    selectedAgents.value.filter(
      (id) => !isAgentDeleted(id, props.allAgents) && !isAgentActive(id, props.allAgents)
    ).length
)
const summaryChipClass = computed(() => 'bg-primary text-primary-foreground')

/* -------------------------------------------------------------------------------- */
// Send button state
const hasContentToSend = computed(() => {
  return newMessage.value.trim().length > 0 || attachments.value.length > 0
})

const sendButtonClasses = computed(() => {
  if (hasContentToSend.value) {
    return 'px-2 bg-primary text-white hover:bg-primary-hover active:bg-primary-selected'
  }
  return 'px-2 hover:bg-primary-foreground bg-primary-foreground text-muted-foreground'
})
</script>

<style scoped>
/* Drag and drop fade transition */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
<style>
[data-state='open'] .chevron-icon {
  transform: rotate(180deg);
}
</style>
