<template>
  <div class="glass-dropdown" ref="dropdownRef">
    <div 
      class="glass-dropdown__trigger"
      @click="toggleDropdown"
      :class="{ 'glass-dropdown__trigger--active': isOpen }"
    >
      <div class="glass-dropdown__trigger-content">
        <slot name="trigger">
          <div class="glass-dropdown__trigger-default">
            <Icon 
              v-if="icon" 
              :name="icon" 
              class="glass-dropdown__trigger-icon"
            />
            <span class="glass-dropdown__trigger-text">{{ label }}</span>
            <div class="glass-dropdown__trigger-arrow">
              <svg
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                class="glass-dropdown__arrow-svg"
                :class="{ 'glass-dropdown__arrow-svg--rotate': isOpen }"
              >
                <path
                  d="M4 6L8 10L12 6"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
            </div>
          </div>
        </slot>
      </div>
      
      <div class="glass-dropdown__trigger-glow"></div>
    </div>

    <Teleport to="body">
      <Transition name="glass-fade">
        <div
          v-if="isOpen"
          class="glass-dropdown__backdrop"
          @click="closeDropdown"
        >
          <div
            class="glass-dropdown__menu"
            :style="menuStyle"
            @click.stop
          >
            <div class="glass-dropdown__menu-inner">
              <div 
                v-if="$slots.header" 
                class="glass-dropdown__header"
              >
                <slot name="header"></slot>
              </div>
              
              <div class="glass-dropdown__items">
                <template v-if="groups.length > 0">
                  <div
                    v-for="(group, groupIndex) in groups"
                    :key="groupIndex"
                    class="glass-dropdown__group"
                  >
                    <div 
                      v-if="group.label" 
                      class="glass-dropdown__group-label"
                    >
                      {{ group.label }}
                    </div>
                    
                    <div
                      v-for="(item, itemIndex) in group.items"
                      :key="`${groupIndex}-${itemIndex}`"
                      class="glass-dropdown__item"
                      :class="{
                        'glass-dropdown__item--active': isItemActive(item),
                        'glass-dropdown__item--disabled': item.disabled,
                        'glass-dropdown__item--danger': item.variant === 'danger'
                      }"
                      @click="!item.disabled && handleItemClick(item)"
                      @mouseenter="hoveredItem = item"
                      @mouseleave="hoveredItem = null"
                    >
                      <div class="glass-dropdown__item-content">
                        <Icon 
                          v-if="item.icon" 
                          :name="item.icon" 
                          class="glass-dropdown__item-icon"
                        />
                        
                        <div class="glass-dropdown__item-text">
                          <div class="glass-dropdown__item-label">
                            {{ item.label }}
                          </div>
                          <div 
                            v-if="item.description" 
                            class="glass-dropdown__item-description"
                          >
                            {{ item.description }}
                          </div>
                        </div>
                        
                        <div 
                          v-if="item.badge" 
                          class="glass-dropdown__item-badge"
                        >
                          {{ item.badge }}
                        </div>
                        
                        <Icon 
                          v-if="item.submenu" 
                          name="chevron-right" 
                          class="glass-dropdown__item-chevron"
                        />
                      </div>
                      
                      <Transition name="submenu-slide">
                        <div
                          v-if="item.submenu && hoveredItem === item"
                          class="glass-dropdown__submenu"
                        >
                          <div
                            v-for="(subItem, subIndex) in item.submenu"
                            :key="subIndex"
                            class="glass-dropdown__submenu-item"
                            :class="{
                              'glass-dropdown__submenu-item--disabled': subItem.disabled
                            }"
                            @click.stop="!subItem.disabled && handleSubmenuClick(subItem)"
                          >
                            <Icon 
                              v-if="subItem.icon" 
                              :name="subItem.icon" 
                              class="glass-dropdown__submenu-icon"
                            />
                            <span>{{ subItem.label }}</span>
                          </div>
                        </div>
                      </Transition>
                    </div>
                    
                    <div 
                      v-if="groupIndex < groups.length - 1" 
                      class="glass-dropdown__divider"
                    ></div>
                  </div>
                </template>
                
                <div v-else class="glass-dropdown__empty">
                  <slot name="empty">
                    <p>No items available</p>
                  </slot>
                </div>
              </div>
              
              <div 
                v-if="$slots.footer" 
                class="glass-dropdown__footer"
              >
                <slot name="footer"></slot>
              </div>
            </div>
            
            <div class="glass-dropdown__menu-glow"></div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import Icon from '~/components/ui/Icon.vue'

interface DropdownItem {
  label: string
  value?: string | number
  icon?: string
  description?: string
  badge?: string | number
  variant?: 'default' | 'danger'
  disabled?: boolean
  action?: () => void
  submenu?: DropdownItem[]
}

interface DropdownGroup {
  label?: string
  items: DropdownItem[]
}

interface Props {
  label?: string
  icon?: string
  groups?: DropdownGroup[]
  items?: DropdownItem[]
  modelValue?: string | number | null
  closeOnSelect?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  label: 'Menu',
  closeOnSelect: true
})

const emit = defineEmits<{
  'update:modelValue': [value: string | number | null]
  'select': [item: DropdownItem]
  'open': []
  'close': []
}>()

const dropdownRef = ref<HTMLElement>()
const isOpen = ref(false)
const hoveredItem = ref<DropdownItem | null>(null)
const menuStyle = ref({})

const groups = computed(() => {
  if (props.groups && props.groups.length > 0) {
    return props.groups
  }
  if (props.items && props.items.length > 0) {
    return [{ items: props.items }]
  }
  return []
})

const toggleDropdown = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    emit('open')
    nextTick(() => updateMenuPosition())
  } else {
    emit('close')
    hoveredItem.value = null
  }
}

const closeDropdown = () => {
  isOpen.value = false
  hoveredItem.value = null
  emit('close')
}

const handleItemClick = (item: DropdownItem) => {
  if (item.action) {
    item.action()
  }
  
  if (item.value !== undefined) {
    emit('update:modelValue', item.value)
  }
  
  emit('select', item)
  
  if (props.closeOnSelect && !item.submenu) {
    closeDropdown()
  }
}

const handleSubmenuClick = (item: DropdownItem) => {
  if (item.action) {
    item.action()
  }
  
  emit('select', item)
  
  if (props.closeOnSelect) {
    closeDropdown()
  }
}

const isItemActive = (item: DropdownItem) => {
  return item.value !== undefined && item.value === props.modelValue
}

const updateMenuPosition = () => {
  if (!dropdownRef.value) return
  
  const rect = dropdownRef.value.getBoundingClientRect()
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  
  let top = rect.bottom + 8
  let left = rect.left
  
  // Adjust if menu would go off screen
  const menuWidth = 320 // Approximate menu width
  const menuHeight = 400 // Approximate max menu height
  
  if (left + menuWidth > windowWidth) {
    left = windowWidth - menuWidth - 16
  }
  
  if (top + menuHeight > windowHeight && rect.top > menuHeight) {
    top = rect.top - menuHeight - 8
  }
  
  menuStyle.value = {
    position: 'fixed',
    top: `${top}px`,
    left: `${left}px`,
    minWidth: `${rect.width}px`,
    zIndex: 10001
  }
}

const handleEscape = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && isOpen.value) {
    closeDropdown()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleEscape)
  window.addEventListener('resize', updateMenuPosition)
  window.addEventListener('scroll', updateMenuPosition)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleEscape)
  window.removeEventListener('resize', updateMenuPosition)
  window.removeEventListener('scroll', updateMenuPosition)
})
</script>

<style scoped lang="scss">
.glass-dropdown {
  position: relative;
  display: inline-block;
  
  &__trigger {
    position: relative;
    display: inline-flex;
    align-items: center;
    padding: 0.625rem 1rem;
    background: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(30px) saturate(180%);
    -webkit-backdrop-filter: blur(30px) saturate(180%);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 14px;
    cursor: pointer;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 
      0 4px 20px rgba(0, 0, 0, 0.04),
      inset 0 1px 0 rgba(255, 255, 255, 0.8);
    
    &:hover {
      background: rgba(255, 255, 255, 0.7);
      border-color: rgba(220, 38, 38, 0.3);
      transform: translateY(-2px);
      box-shadow: 
        0 8px 30px rgba(220, 38, 38, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.9);
      
      .glass-dropdown__trigger-glow {
        opacity: 1;
      }
    }
    
    &--active {
      background: rgba(255, 255, 255, 0.8);
      border-color: rgba(220, 38, 38, 0.4);
      box-shadow: 
        0 0 0 4px rgba(220, 38, 38, 0.1),
        0 8px 30px rgba(220, 38, 38, 0.15),
        inset 0 1px 0 rgba(255, 255, 255, 1);
    }
  }
  
  &__trigger-content {
    position: relative;
    z-index: 1;
  }
  
  &__trigger-default {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
  
  &__trigger-icon {
    width: 1.25rem;
    height: 1.25rem;
    color: #dc2626;
  }
  
  &__trigger-text {
    font-weight: 500;
    color: #27272a;
    font-size: 0.9375rem;
  }
  
  &__trigger-arrow {
    margin-left: 0.5rem;
  }
  
  &__arrow-svg {
    color: #dc2626;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    
    &--rotate {
      transform: rotate(180deg);
    }
  }
  
  &__trigger-glow {
    position: absolute;
    inset: -1px;
    background: linear-gradient(135deg, 
      rgba(220, 38, 38, 0.2) 0%, 
      rgba(220, 38, 38, 0) 100%);
    border-radius: 14px;
    opacity: 0;
    transition: opacity 0.4s ease;
    pointer-events: none;
  }
  
  &__backdrop {
    position: fixed;
    inset: 0;
    z-index: 10000;
    background: rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(4px);
  }
  
  &__menu {
    position: absolute;
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(40px) saturate(200%);
    -webkit-backdrop-filter: blur(40px) saturate(200%);
    border: 1px solid rgba(255, 255, 255, 0.4);
    border-radius: 20px;
    box-shadow: 
      0 20px 60px rgba(0, 0, 0, 0.15),
      0 0 0 1px rgba(220, 38, 38, 0.05),
      inset 0 1px 0 rgba(255, 255, 255, 0.9);
    overflow: hidden;
    min-width: 280px;
    max-width: 400px;
    max-height: 70vh;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 10px;
    }
    
    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 10px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: linear-gradient(180deg, 
        rgba(220, 38, 38, 0.3) 0%, 
        rgba(220, 38, 38, 0.1) 100%);
      border-radius: 10px;
      border: 2px solid rgba(255, 255, 255, 0.9);
      
      &:hover {
        background: linear-gradient(180deg, 
          rgba(220, 38, 38, 0.4) 0%, 
          rgba(220, 38, 38, 0.2) 100%);
      }
    }
  }
  
  &__menu-inner {
    position: relative;
    z-index: 1;
    padding: 0.5rem;
  }
  
  &__menu-glow {
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(
      ellipse at center,
      rgba(220, 38, 38, 0.1) 0%,
      transparent 70%
    );
    pointer-events: none;
  }
  
  &__header {
    padding: 1rem;
    border-bottom: 1px solid rgba(220, 38, 38, 0.1);
    margin-bottom: 0.5rem;
  }
  
  &__footer {
    padding: 1rem;
    border-top: 1px solid rgba(220, 38, 38, 0.1);
    margin-top: 0.5rem;
  }
  
  &__group {
    margin: 0.25rem 0;
  }
  
  &__group-label {
    padding: 0.5rem 0.75rem;
    font-size: 0.75rem;
    font-weight: 600;
    color: #dc2626;
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }
  
  &__divider {
    height: 1px;
    background: linear-gradient(90deg, 
      transparent 0%, 
      rgba(220, 38, 38, 0.2) 50%, 
      transparent 100%);
    margin: 0.5rem 0;
  }
  
  &__item {
    position: relative;
    padding: 0.625rem 0.75rem;
    margin: 0.125rem 0;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    
    &:hover:not(&--disabled) {
      background: linear-gradient(135deg, 
        rgba(220, 38, 38, 0.08) 0%, 
        rgba(220, 38, 38, 0.04) 100%);
      transform: translateX(4px);
      
      .glass-dropdown__item-icon {
        transform: scale(1.1);
      }
    }
    
    &--active {
      background: linear-gradient(135deg, 
        rgba(220, 38, 38, 0.15) 0%, 
        rgba(220, 38, 38, 0.08) 100%);
      color: #dc2626;
      font-weight: 600;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 60%;
        background: #dc2626;
        border-radius: 0 3px 3px 0;
      }
    }
    
    &--danger {
      color: #ef4444;
      
      &:hover {
        background: rgba(239, 68, 68, 0.1);
      }
    }
    
    &--disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }
  
  &__item-content {
    display: flex;
    align-items: center;
    gap: 0.75rem;
  }
  
  &__item-icon {
    width: 1.25rem;
    height: 1.25rem;
    color: #dc2626;
    flex-shrink: 0;
    transition: transform 0.3s ease;
  }
  
  &__item-text {
    flex: 1;
  }
  
  &__item-label {
    font-size: 0.9375rem;
    color: inherit;
  }
  
  &__item-description {
    font-size: 0.75rem;
    color: #71717a;
    margin-top: 0.125rem;
  }
  
  &__item-badge {
    padding: 0.125rem 0.5rem;
    background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
    color: white;
    font-size: 0.75rem;
    font-weight: 600;
    border-radius: 999px;
  }
  
  &__item-chevron {
    width: 1rem;
    height: 1rem;
    color: #71717a;
    margin-left: auto;
  }
  
  &__submenu {
    position: absolute;
    left: calc(100% + 0.5rem);
    top: 0;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(30px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    padding: 0.25rem;
    min-width: 200px;
    z-index: 10;
  }
  
  &__submenu-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.875rem;
    
    &:hover:not(&--disabled) {
      background: rgba(220, 38, 38, 0.1);
      color: #dc2626;
    }
    
    &--disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }
  
  &__submenu-icon {
    width: 1rem;
    height: 1rem;
    color: #dc2626;
  }
  
  &__empty {
    padding: 2rem;
    text-align: center;
    color: #71717a;
    font-size: 0.875rem;
  }
}

// Animations
.glass-fade-enter-active,
.glass-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.glass-fade-enter-from {
  opacity: 0;
  
  .glass-dropdown__menu {
    transform: scale(0.9) translateY(-20px);
    filter: blur(10px);
  }
}

.glass-fade-leave-to {
  opacity: 0;
  
  .glass-dropdown__menu {
    transform: scale(0.9) translateY(-20px);
    filter: blur(10px);
  }
}

.submenu-slide-enter-active,
.submenu-slide-leave-active {
  transition: all 0.2s ease;
}

.submenu-slide-enter-from {
  opacity: 0;
  transform: translateX(-10px);
}

.submenu-slide-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}
</style>