<script setup lang="ts">
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupLabel,
  SidebarGroupContent,
  SidebarMenu,
  SidebarMenuItem,
  SidebarMenuButton,
  SidebarHeader,
  useSidebar,
} from '@/components/ui/sidebar'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@/components/ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from '@/components/ui/alert-dialog'
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { API } from '@/Api'
import { MoreVertical, Loader2, Users, ChevronDown, ChevronRight } from 'lucide-vue-next'
import ConversationsList from './ConversationsList.vue'
import ShareAgent from './ShareAgent.vue'
import CustomSidebarHeader from '@/components/CustomSidebarHeader.vue'
import { toast } from 'vue-sonner'
import { useAgentCatalogStore } from '@/store/agentCatalogStore'
import { useAgentStore } from '@/store/agentStore'
import { isIndexing } from '@/constants/indexing'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import Button from './ui/button/Button.vue'
import { useUserStore } from '@/store/userStore'
import { storeToRefs } from 'pinia'
import { usePrefStore } from '@/store/prefStore'
import { WT1iser } from '@/lib/wt1'

defineOptions({ name: 'AgentsSidebar' })

const { open, openMobile, isMobile } = useSidebar()
const isSidebarOpen = computed(() => (isMobile.value ? openMobile.value : open.value))

const props = defineProps<{ selectedConversationId?: string | null }>()
const emit = defineEmits<{
  (e: 'selectAgent', id: string): void
  (e: 'selectConversation', p: { conversationId: string; agentIds: string[] }): void
  (e: 'conversationDeleted', id?: string): void
  (e: 'new-conversation'): void
  (e: 'view-library'): void
  (e: 'view-library-my-agents'): void
  (e: 'view-monitoring'): void
  (e: 'new-agent'): void
  (e: 'edit-agent', id: string): void
  (e: 'view-home'): void
}>()

const catalog = useAgentCatalogStore()
const agentStore = useAgentStore()
const userStore = useUserStore()
const prefStore = usePrefStore()

const { userHasFullAccess } = storeToRefs(userStore)
const userCanEdit = computed(() => userHasFullAccess.value && prefStore.uiConf?.enable_quick_agents)

// Track open state of dropdowns
const openDropdowns = ref<Record<string, boolean>>({})
//const openConversationDropdown = ref<Record<string, boolean>>({})
//const openGroupDropdown = ref(false)

/* Enterprise Agents */
const enterpriseAgents = computed(() => catalog.agents.filter((a) => a.isEnterprise))

/* All user agents (both draft and published) in one list */
const allUserAgents = computed(() => {
  const userAgents = catalog.agents
    .filter((a) => !a.isShared && !a.isEnterprise)
    .reduce((acc, agent) => {
      // For agents with both draft and active versions, only show the active one
      const existingIndex = acc.findIndex((a) => a.id === agent.id)

      if (existingIndex === -1) {
        // First time seeing this agent ID
        acc.push(agent)
      } else {
        // We've seen this agent ID before
        const existing = acc[existingIndex]

        // If we have both draft and active, keep only the active one
        if (existing.status === 'draft' && agent.status === 'active') {
          acc[existingIndex] = agent
        } else if (existing.status === 'active' && agent.status === 'draft') {
          // Keep the active one, don't replace
        } else {
          // Both same status, keep the one with more recent data
          if (agent.published_at && !existing.published_at) {
            acc[existingIndex] = agent
          }
        }
      }

      return acc
    }, [] as typeof catalog.agents)
    .map((a) => {
      const hasPublished = !!a.published_version || a.status === 'active'
      const isDraft = a.status === 'draft' && !a.published_version

      return {
        ...a,
        displayName: hasPublished && a.published_version?.name ? a.published_version.name : a.name,
        isDraft,
        hasPublished,
        hasUnpublishedChanges: a.hasUnpublishedChanges ?? false,
      }
    })
    .sort((a, b) => {
      // Sort: true drafts (never published) first, then by creation date
      if (a.isDraft !== b.isDraft) return a.isDraft ? -1 : 1
      return (b.createdAt || '').localeCompare(a.createdAt || '')
    })

  return userAgents
})

/* Active agents shared with me */
const sharedActiveAgents = computed(() =>
  catalog.agents
    .filter((a) => a.status === 'active' && a.isShared && a.published_at)
    .map((a) => ({
      ...a,
      name: a.published_version?.name || a.name,
    }))
)

/* Favorite Agents */
const favoriteAgents = computed(() => {
  const favoriteIds = prefStore.favoriteAgents
  return catalog.agents
    .filter((a) => favoriteIds[a.id] && a.status !== 'draft')
    .map((a) => ({
      ...a,
      displayName: a.published_version?.name || a.name,
    }))
    .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''))
})

const router = useRouter()
const route = useRoute()

const convRef = ref<InstanceType<typeof ConversationsList> | null>(null)
defineExpose({
  refreshConversations: () => convRef.value?.fetchConversations(),
  updateConversationTitle: (id: string, t: string) => convRef.value?.updateConversationTitle(id, t),
})

/* Click handlers */
function handleSelectEnterprise(a: any) {
  WT1iser.selectAgent('enterprise')
  emit('selectAgent', a.id)
  // Navigate to homepage with the selected agent
  router.push({ name: 'Home' })
  if (isMobile.value) openMobile.value = false
}

function handleSelectAgent(a: any) {
  if (a.isDraft && userCanEdit.value) {
    WT1iser.selectAgent('draft')
    // Draft agents always go to edit page
    emit('edit-agent', a.id)
    router.push({ name: 'EditAgent', params: { id: a.id } })
  } else {
    WT1iser.selectAgent('published')
    // Published agents go to homepage
    emit('selectAgent', a.id)
    // Navigate to homepage with the selected agent
    router.push({ name: 'Home' })
  }
  if (isMobile.value) openMobile.value = false
}

function handleSelectShared(a: any) {
  emit('selectAgent', a.id)
  // Navigate to homepage with the selected agent
  router.push({ name: 'Home' })
  if (isMobile.value) openMobile.value = false
}

function handlePlus() {
  WT1iser.createAgent()
  if (userCanEdit.value) {
    emit('new-agent')
    router.push({ name: 'NewAgent', query: { new: Date.now().toString() } })
  } else {
    // Navigate to AgentLibrary with query parameter to force My Agents tab
    router.push({ name: 'AgentLibrary', query: { tab: 'myAgents' } })
  }
  if (isMobile.value) openMobile.value = false
}

// Handle new conversation button click
function handleNewConversation() {
  emit('new-conversation')
  WT1iser.newConversation()
  // Navigate to conversations page
  router.push({ name: 'Home' })
  if (isMobile.value) openMobile.value = false
}

// Handle view library button click
function handleViewLibrary() {
  WT1iser.viewAgentLibrary()
  emit('view-library')
  // Navigate to agent library page
  router.push({ name: 'AgentLibrary' })
  if (isMobile.value) openMobile.value = false
}

// Handle monitoring (dashboard) button click
function handleMonitoring() {
  WT1iser.viewMonitoring()
  emit('view-monitoring')
  // Navigate to dashboard page
  router.push({ name: 'Dashboard' })
  if (isMobile.value) openMobile.value = false
}

/* Delete agent */
const deleteDialogOpen = ref(false)
const agentToDelete = ref<string | null>(null)
const showShareDialog = ref(false)
const shareAgentId = ref<string | null>(null)
const shareAgentName = ref<string | undefined>(undefined)
function confirmDelete(id: string) {
  agentToDelete.value = id
  deleteDialogOpen.value = true
}

function openShareDialog(id: string, name: string) {
  shareAgentId.value = id
  shareAgentName.value = name
  showShareDialog.value = true
}
async function doDelete() {
  if (!agentToDelete.value) return
  WT1iser.deleteAgent('') //TODO add agent type
  try {
    await API.deleteAgent(agentToDelete.value)
    toast.success('Agent deleted')
    catalog.removeAgent(agentToDelete.value)

    // Remove from favorites if it exists
    if (prefStore.favoriteAgents[agentToDelete.value]) {
      prefStore.toggleFavoriteAgent(agentToDelete.value, false)
    }

    emit('conversationDeleted', agentToDelete.value)
    // if we're editing OR creating that same agent, kick back to Home
    const { name, params } = router.currentRoute.value
    if (
      (name === 'EditAgent' && params.id === agentToDelete.value) ||
      (name === 'NewAgent' && agentStore.draft.id === agentToDelete.value)
    ) {
      emit('view-home')
      router.push({ name: 'Home' })
    }
  } catch {
    toast.error('Failed to delete agent')
  } finally {
    deleteDialogOpen.value = false
    agentToDelete.value = null
  }
}

function onAgentSaved(e: any) {
  if (e instanceof CustomEvent && e.detail) {
    const { id, name, status, hasUnpublishedChanges, indexing } = e.detail
    catalog.updateAgent({
      id,
      name,
      status,
      hasUnpublishedChanges,
      indexing: indexing || { status: '' },
      project_key: e.detail.project_key || '', // in case project_key is sent
    })
  }
}

function onDocsUpdated(e: any) {
  if (e instanceof CustomEvent && e.detail) {
    const { agentId, indexing } = e.detail
    catalog.updateAgent({ id: agentId, indexing })
  }
}

// Initialize with saved state to avoid animation on load
const getInitialExpandedState = () => {
  const saved = localStorage.getItem('sidebarExpandedGroups')
  if (saved) {
    try {
      return JSON.parse(saved)
    } catch (e) {
      console.error('Failed to load sidebar state:', e)
    }
  }
  // Default state if no saved state
  return {
    agents: true,
    enterprise: true,
    myAgents: true,
    shared: true,
    conversations: true,
    favorites: true,
  }
}

const expandedGroups = ref(getInitialExpandedState())

// Add refs after line 76
const sidebarContent = ref<InstanceType<typeof SidebarContent> | null>(null)
const hasScrolled = ref(false)

// Add function before line 230
const handleScroll = () => {
  if (sidebarContent.value?.$el) {
    hasScrolled.value = sidebarContent.value.$el.scrollTop > 0
  }
}

onMounted(() => {
  catalog.load()
  window.addEventListener('agent-saved', onAgentSaved)
  window.addEventListener('docs-updated', onDocsUpdated)
  window.addEventListener('request-delete-agent', onRequestDelete as EventListener)
  if (sidebarContent.value?.$el) {
    sidebarContent.value.$el.addEventListener('scroll', handleScroll)
  }
})

watch(
  expandedGroups,
  (newValue) => {
    localStorage.setItem('sidebarExpandedGroups', JSON.stringify(newValue))
  },
  { deep: true }
)

function toggleGroup(group: keyof typeof expandedGroups.value) {
  WT1iser.viewAgentGroup(group.toString())
  expandedGroups.value[group] = !expandedGroups.value[group]
}

// Handle conversation selection without closing the group
function handleConversationSelect(payload: { conversationId: string; agentIds: string[] }) {
  emit('selectConversation', payload)
  // Navigate to conversations page with the selected conversation
  router.push({ name: 'Conversations' })
  // Close mobile sidebar when conversation is selected
  if (isMobile.value) openMobile.value = false
  // Don't toggle the conversations group here
}

onBeforeUnmount(() => {
  window.removeEventListener('agent-saved', onAgentSaved)
  window.removeEventListener('docs-updated', onDocsUpdated)
  window.removeEventListener('request-delete-agent', onRequestDelete as EventListener)
  if (sidebarContent.value?.$el) {
    sidebarContent.value.$el.removeEventListener('scroll', handleScroll)
  }
})

function onRequestDelete(e: CustomEvent<{ id: string }>) {
  if (e && (e as any).detail?.id) {
    confirmDelete((e as any).detail.id)
  }
}

// Computed property to get the agent being deleted
const agentBeingDeleted = computed(() => {
  if (!agentToDelete.value) return null
  return catalog.agents.find((a) => a.id === agentToDelete.value)
})

// Computed property for the delete dialog title
const deleteDialogTitle = computed(() => {
  const agent = agentBeingDeleted.value
  if (!agent) return 'Delete Agent'

  // Get the agent name - check displayName first, then name, then fallback
  const agentName = agent.published_version?.name || agent.name
  if (agentName && agentName.trim()) {
    return `Delete ${agentName}`
  }

  return 'Delete Agent'
})
</script>

<template>
  <Sidebar collapsible="icon">
    <SidebarHeader
      class="bg-primary-alpha-light-10 border-1 border-border border-y-0"
      :class="{ 'border-b-transparent': !isSidebarOpen }"
    >
      <CustomSidebarHeader :sidebarOpen="isSidebarOpen" @view-home="$emit('view-home')" />
      <div class="flex flex-col pt-2 pb-3">
        <!-- Start new conversation Button -->
        <Tooltip v-if="!isSidebarOpen">
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              @click="handleNewConversation"
              class="justify-start p-2 mx-1 hover:bg-primary-alpha-light-30"
            >
              <i class="dku-icon-comment-add-16"></i>
              <span v-if="isSidebarOpen">Start new conversation</span>
            </Button>
          </TooltipTrigger>
          <TooltipContent :side-offset="10" hide-arrow side="right">
            <p>Start new conversation</p>
          </TooltipContent>
        </Tooltip>
        <Button
          v-else
          variant="ghost"
          @click="handleNewConversation"
          class="justify-start p-2 mx-1 hover:bg-primary-alpha-light-30"
        >
          <i class="dku-icon-comment-add-16"></i>
          <span>Start new conversation</span>
        </Button>

        <!-- Create new agent Button -->
        <Tooltip v-if="!isSidebarOpen">
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              @click="handlePlus"
              class="justify-start p-2 mx-1 hover:bg-primary-alpha-light-30"
            >
              <i class="dku-icon-plus-square-multiple-16"></i>
              <span v-if="isSidebarOpen">Create new agent</span>
            </Button>
          </TooltipTrigger>
          <TooltipContent :side-offset="10" hide-arrow side="right">
            <p>Create new agent</p>
          </TooltipContent>
        </Tooltip>
        <Button
          v-else
          variant="ghost"
          @click="handlePlus"
          class="justify-start p-2 mx-1 hover:bg-primary-alpha-light-30"
        >
          <i class="dku-icon-plus-square-multiple-16"></i>
          <span>Create new agent</span>
        </Button>

        <!-- Agents Library Button -->
        <Tooltip v-if="!isSidebarOpen">
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              @click="handleViewLibrary"
              :class="[
                'justify-start p-2 mx-1 hover:bg-primary-alpha-light-30',
                { 'bg-primary-alpha-light-20': route.name === 'AgentLibrary' },
              ]"
            >
              <i class="dku-icon-square-card-view-16"></i>
              <span v-if="isSidebarOpen">Agents Library</span>
            </Button>
          </TooltipTrigger>
          <TooltipContent :side-offset="10" hide-arrow side="right">
            <p>Agents library</p>
          </TooltipContent>
        </Tooltip>
        <Button
          v-else
          variant="ghost"
          @click="handleViewLibrary"
          :class="[
            'justify-start p-2 mx-1 hover:bg-primary-alpha-light-30',
            { 'bg-primary-alpha-light-20': route.name === 'AgentLibrary' },
          ]"
        >
          <i class="dku-icon-square-card-view-16"></i>
          <span>Agents Library</span>
        </Button>

        <!-- Monitoring (Dashboard) Button -->
        <template v-if="userCanEdit">
          <Tooltip v-if="!isSidebarOpen">
            <TooltipTrigger asChild>
              <Button
                variant="ghost"
                @click="handleMonitoring"
                :class="[
                  'justify-start p-2 mx-1 hover:bg-primary-alpha-light-30',
                  { 'bg-primary-alpha-light-20': route.name === 'Dashboard' },
                ]"
              >
                <i class="dku-icon-dashboard-16"></i>
              </Button>
            </TooltipTrigger>
            <TooltipContent :side-offset="10" hide-arrow side="right">
              <p>Monitoring</p>
            </TooltipContent>
          </Tooltip>

          <Button
            v-else
            variant="ghost"
            @click="handleMonitoring"
            :class="[
              'justify-start p-2 mx-1 hover:bg-primary-alpha-light-30',
              { 'bg-primary-alpha-light-20': route.name === 'Dashboard' },
            ]"
          >
            <i class="dku-icon-dashboard-16"></i>
            <span>Monitoring</span>
          </Button>
        </template>
      </div>
    </SidebarHeader>

    <SidebarContent
      ref="sidebarContent"
      class="flex flex-col overflow-y-auto bg-primary-alpha-light-10 border-x-1 border-b-1 border-border gap-0"
      :class="{ 'border-t-1 border-border': hasScrolled }"
    >
      <!-- Conversations at the top -->

      <div class="mx-2">
        <ConversationsList
          v-if="isSidebarOpen"
          ref="convRef"
          :selectedConversationId="props.selectedConversationId"
          :expanded="expandedGroups.conversations"
          @selectConversation="handleConversationSelect"
          @conversationDeleted="(id) => emit('conversationDeleted', id)"
          @toggleGroup="toggleGroup('conversations')"
        />
      </div>

      <!-- Agents section -->
      <div v-if="isSidebarOpen" class="mx-2">
        <SidebarGroup>
          <SidebarGroupLabel
            class="sidebar-group-label sidebar-group-label-main cursor-pointer select-none font-semibold"
            @click="toggleGroup('agents')"
          >
            <div class="flex items-center justify-between w-full transition-colors">
              <div class="flex items-center">
                <component
                  :is="expandedGroups.agents ? ChevronDown : ChevronRight"
                  class="w-3 h-3 mr-1 transition-transform duration-200"
                />
                <i class="dku-icon-ai-agent-16 mr-2"></i>Agents
              </div>
            </div>
          </SidebarGroupLabel>
          <Transition name="accordion">
            <SidebarGroupContent v-show="expandedGroups.agents" class="pl-1">
              <div>
                <!-- Favorite Agents -->
                <SidebarGroup v-if="favoriteAgents.length" class="mb-2">
                  <SidebarGroupLabel
                    class="sidebar-group-label cursor-pointer select-none"
                    @click="toggleGroup('favorites')"
                  >
                    <div class="flex items-center justify-between w-full transition-colors">
                      <div class="flex items-center font-semibold">
                        <component
                          :is="expandedGroups.favorites ? ChevronDown : ChevronRight"
                          class="w-3 h-3 mr-1 transition-transform duration-200"
                        />
                        <i class="dku-icon-star-outline-16 mr-1.5"></i>
                        Favorite Agents
                      </div>
                    </div>
                  </SidebarGroupLabel>
                  <Transition name="accordion">
                    <SidebarGroupContent v-show="expandedGroups.favorites" class="pl-1">
                      <SidebarMenu>
                        <SidebarMenuItem
                          v-for="agent in favoriteAgents"
                          :key="agent.id"
                          class="sidebar-menu-item border-l border-primary-alpha-light-60 ml-[10px]"
                        >
                          <SidebarMenuButton
                            @click="() => handleSelectAgent(agent)"
                            class="sidebar-menu-button ml-[3px]"
                          >
                            <span class="truncate" :title="agent.displayName">
                              {{ agent.displayName }}
                            </span>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </Transition>
                </SidebarGroup>
                <!-- Enterprise Agents -->
                <SidebarGroup class="mb-2">
                  <SidebarGroupLabel
                    class="sidebar-group-label cursor-pointer"
                    @click="toggleGroup('enterprise')"
                  >
                    <div class="flex items-center justify-between w-full transition-colors">
                      <div class="flex items-center font-semibold">
                        <component
                          :is="expandedGroups.enterprise ? ChevronDown : ChevronRight"
                          class="w-3 h-3 mr-1 transition-transform duration-200"
                        />
                        <i class="dku-icon-briefcase-16 mr-1.5"></i>
                        Enterprise Agents
                      </div>
                    </div>
                  </SidebarGroupLabel>
                  <Transition name="accordion">
                    <SidebarGroupContent v-show="expandedGroups.enterprise" class="pl-1">
                      <SidebarMenu>
                        <SidebarMenuItem
                          v-if="enterpriseAgents?.length"
                          v-for="agent in enterpriseAgents"
                          :key="agent.id"
                          class="sidebar-menu-item border-l border-primary-alpha-light-60 ml-[10px]"
                        >
                          <SidebarMenuButton
                            @click="() => handleSelectEnterprise(agent)"
                            class="sidebar-menu-button ml-[3px]"
                          >
                            <span class="truncate" :title="agent.name">
                              {{ agent.name }}
                            </span>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                        <SidebarMenuItem v-else class="sidebar-menu-item text-base-primary ml-4">
                          No enterprise agents available
                        </SidebarMenuItem>
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </Transition>
                </SidebarGroup>

                <!-- My Agents (all user agents) -->
                <SidebarGroup
                  v-if="prefStore.uiConf?.enable_quick_agents || allUserAgents.length"
                  class="mb-2"
                >
                  <SidebarGroupLabel
                    class="sidebar-group-label cursor-pointer select-none"
                    @click="toggleGroup('myAgents')"
                  >
                    <div class="flex items-center justify-between w-full transition-colors">
                      <div class="flex items-center font-semibold">
                        <component
                          :is="expandedGroups.myAgents ? ChevronDown : ChevronRight"
                          class="w-3 h-3 mr-1 transition-transform duration-200"
                        />
                        <i class="dku-icon-user-16 mr-1.5"></i>
                        My Agents
                      </div>
                    </div>
                  </SidebarGroupLabel>
                  <Transition name="accordion">
                    <SidebarGroupContent v-show="expandedGroups.myAgents" class="pl-1">
                      <SidebarMenu>
                        <SidebarMenuItem
                          v-if="allUserAgents?.length"
                          v-for="agent in allUserAgents"
                          :key="agent.id"
                          class="sidebar-menu-item border-l border-primary-alpha-light-60 ml-[10px]"
                        >
                          <SidebarMenuButton
                            @click="() => handleSelectAgent(agent)"
                            class="sidebar-menu-button group ml-[3px]"
                            :class="{
                              active: route.name === 'EditAgent' && route.params.id === agent.id,
                              'draft-agent': agent.isDraft,
                            }"
                          >
                            <div class="flex items-center min-w-0 flex-1">
                              <span class="truncate" :title="agent.displayName || '(unnamed)'">
                                {{ agent.displayName || '(unnamed)' }}
                              </span>

                              <!-- Status indicators -->
                              <div class="agent-status-indicator">
                                <!-- Draft icon -->
                                <Tooltip v-if="agent.isDraft">
                                  <TooltipTrigger asChild>
                                    <button class="p-1 rounded hover:bg-gray-200 transition-colors">
                                      <i class="dku-icon-custom-page-12 text-black"></i>
                                    </button>
                                  </TooltipTrigger>
                                  <TooltipContent hide-arrow>Draft</TooltipContent>
                                </Tooltip>
                                <!-- Indexing spinner -->
                                <Loader2
                                  v-if="isIndexing(agent.indexing?.status)"
                                  class="animate-spin text-gray-400"
                                />

                                <!-- Unpublished changes indicator -->
                                <Tooltip v-if="!agent.isDraft && agent.hasUnpublishedChanges">
                                  <TooltipTrigger asChild>
                                    <button
                                      @click.stop="
                                        () =>
                                          router.push({
                                            name: 'EditAgent',
                                            params: { id: agent.id },
                                          })
                                      "
                                      class="ml-[2px] p-1 rounded hover:bg-gray-200 transition-colors"
                                    >
                                      <i class="dku-icon-history-12 text-black"></i>
                                    </button>
                                  </TooltipTrigger>
                                  <TooltipContent hide-arrow
                                    >Has unpublished changes</TooltipContent
                                  >
                                </Tooltip>

                                <!-- Share count 
                        <Badge v-if="agent.shareCount > 0" class="agent-badge">
                          {{ agent.shareCount }}
                        </Badge> -->
                              </div>
                            </div>
                            <!-- Share count  -->
                            <Tooltip v-if="agent.shareCount > 0">
                              <TooltipTrigger asChild>
                                <div class="flex items-center ml-auto mr-2">
                                  <Users class="w-3 h-3 text-gray-500 mr-1" />
                                  <Badge class="agent-badge">
                                    {{ agent.shareCount }}
                                  </Badge>
                                </div>
                              </TooltipTrigger>
                              <TooltipContent>
                                Shared with {{ agent.shareCount }} user{{
                                  agent.shareCount > 1 ? 's' : ''
                                }}
                              </TooltipContent>
                            </Tooltip>
                            <DropdownMenu v-model:open="openDropdowns[agent.id]">
                              <DropdownMenuTrigger asChild>
                                <button
                                  class="sidebar-dropdown-trigger"
                                  :class="{ 'force-visible': openDropdowns[agent.id] }"
                                  @click.stop
                                >
                                  <MoreVertical class="w-3.5 h-3.5" />
                                </button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent>
                                <Tooltip>
                                  <TooltipTrigger as-child>
                                    <div>
                                      <DropdownMenuItem
                                        :disabled="!userCanEdit"
                                        @click.stop="
                                          () =>
                                            router.push({
                                              name: 'EditAgent',
                                              params: { id: agent.id },
                                            })
                                        "
                                      >
                                        <i class="dku-icon-edit-16"></i>Edit
                                      </DropdownMenuItem>
                                      <DropdownMenuItem
                                        v-if="!agent.isDraft"
                                        :disabled="!userCanEdit"
                                        @click.stop="openShareDialog(agent.id, agent.name)"
                                      >
                                        <i class="dku-icon-share-16"></i>Share
                                      </DropdownMenuItem>
                                      <DropdownMenuItem
                                        :disabled="!userCanEdit"
                                        class="text-destructive"
                                        @click.stop="() => confirmDelete(agent.id)"
                                      >
                                        <i class="dku-icon-trash-16"></i>Delete
                                      </DropdownMenuItem>
                                    </div>
                                  </TooltipTrigger>
                                  <TooltipContent v-if="!userCanEdit">
                                    <p>
                                      <template v-if="!prefStore.uiConf?.enable_quick_agents">
                                        User agent creation has been disabled by your administrator.
                                      </template>
                                      <template v-else>
                                        Your profile has been downgraded, which limits editing
                                        rights.<br />
                                        To regain editing access, please contact your administrator
                                        to request a profile upgrade.
                                      </template>
                                    </p>
                                  </TooltipContent>
                                </Tooltip>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                        <SidebarMenuItem v-else class="sidebar-menu-item text-base-primary ml-4">
                          No agents available
                        </SidebarMenuItem>
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </Transition>
                </SidebarGroup>

                <!-- Shared with me -->
                <SidebarGroup v-if="sharedActiveAgents.length" class="mb-2">
                  <SidebarGroupLabel
                    class="sidebar-group-label cursor-pointer select-none"
                    @click="toggleGroup('shared')"
                  >
                    <div class="flex items-center justify-between w-full transition-colors">
                      <div class="flex items-center">
                        <component
                          :is="expandedGroups.shared ? ChevronDown : ChevronRight"
                          class="w-3 h-3 mr-1 transition-transform duration-200"
                        />
                        <i class="dku-icon-share-16 mr-1.5"></i>
                        Shared with me
                      </div>
                    </div>
                  </SidebarGroupLabel>
                  <Transition name="accordion">
                    <SidebarGroupContent v-show="expandedGroups.shared" class="pl-1">
                      <SidebarMenu>
                        <SidebarMenuItem
                          v-for="agent in sharedActiveAgents"
                          :key="agent.id"
                          class="sidebar-menu-item border-l border-primary-alpha-light-60 ml-[10px]"
                        >
                          <SidebarMenuButton
                            @click="() => handleSelectShared(agent)"
                            class="sidebar-menu-button ml-[3px]"
                          >
                            <span class="truncate flex-1" :title="agent.name">
                              {{ agent.name }}
                            </span>
                            <Tooltip v-if="agent.shareCount > 0">
                              <TooltipTrigger asChild>
                                <div class="flex items-center ml-auto">
                                  <Users class="w-3 h-3 text-gray-500 mr-1" />
                                  <Badge class="agent-badge">
                                    {{ agent.shareCount }}
                                  </Badge>
                                </div>
                              </TooltipTrigger>
                              <TooltipContent>
                                Shared with {{ agent.shareCount }} user{{
                                  agent.shareCount > 1 ? 's' : ''
                                }}
                              </TooltipContent>
                            </Tooltip>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </Transition>
                </SidebarGroup>
              </div>
            </SidebarGroupContent>
          </Transition>
        </SidebarGroup>
      </div>
    </SidebarContent>
  </Sidebar>

  <!-- Delete Agent Dialog -->
  <AlertDialog v-model:open="deleteDialogOpen">
    <AlertDialogContent>
      <AlertDialogHeader>
        <AlertDialogTitle
          ><i class="dku-icon-trash-16 mr-2"></i>{{ deleteDialogTitle }}</AlertDialogTitle
        >
        <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
      </AlertDialogHeader>
      <AlertDialogFooter>
        <AlertDialogCancel>Cancel</AlertDialogCancel>
        <AlertDialogAction
          class="bg-destructive hover:bg-destructive/90 text-white"
          @click="doDelete"
        >
          Delete
        </AlertDialogAction>
      </AlertDialogFooter>
    </AlertDialogContent>
  </AlertDialog>

  <!-- Share Agent Dialog -->
  <ShareAgent
    v-if="shareAgentId"
    :open="showShareDialog"
    :agentId="shareAgentId"
    :agentName="shareAgentName"
    @update:open="showShareDialog = $event"
  />
</template>

<style scoped>
/* Add styling for draft agents */
.sidebar-menu-button.draft-agent {
  opacity: 0.85;
}

.sidebar-menu-button.draft-agent:hover {
  opacity: 1;
}

/* Ensure smooth scrolling for both sections */
.max-h-\[40vh\] {
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
}

.max-h-\[60vh\] {
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
}

/* Webkit browsers */
.max-h-\[40vh\]::-webkit-scrollbar,
.max-h-\[60vh\]::-webkit-scrollbar {
  width: 6px;
}

.max-h-\[40vh\]::-webkit-scrollbar-thumb,
.max-h-\[60vh\]::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 3px;
}

.max-h-\[40vh\]::-webkit-scrollbar-track,
.max-h-\[60vh\]::-webkit-scrollbar-track {
  background: transparent;
}

.secondary-nav-active {
  border-radius: var(--border-radius-default, 6px);
  background: linear-gradient(
      0deg,
      var(--alpha-30, rgba(255, 255, 255, 0.7)) 0%,
      var(--alpha-30, rgba(255, 255, 255, 0.7)) 100%
    ),
    var(--colors-primary, var(--primary));
}

/* Preserve gradient on hover instead of Tailwind hover:bg-* overriding it */
.secondary-nav-active:hover {
  background: linear-gradient(
      0deg,
      var(--alpha-30, rgba(255, 255, 255, 0.7)) 0%,
      var(--alpha-30, rgba(255, 255, 255, 0.7)) 100%
    ),
    var(--colors-primary, var(--primary));
}
</style>
