<template>
  <div
    v-if="visible && filteredSkills.length > 0"
    class="mention-dropdown"
    :style="positionStyle"
    role="listbox"
    aria-label="技能列表"
  >
    <div class="mention-dropdown__header">
      <span class="mention-dropdown__title">技能</span>
      <span class="mention-dropdown__hint">选择或继续输入筛选</span>
    </div>
    <div class="mention-dropdown__list">
      <button
        v-for="(skill, idx) in filteredSkills"
        :id="`mention-item-${idx}`"
        :key="skill.name"
        class="mention-dropdown__item"
        :class="{ 'mention-dropdown__item--active': idx === activeIndex }"
        role="option"
        :aria-selected="idx === activeIndex"
        @click="selectSkill(skill)"
        @mouseenter="activeIndex = idx"
      >
        <span class="mention-dropdown__item-name">{{ skill.name }}</span>
        <span class="mention-dropdown__item-desc">{{ skill.description }}</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue'

interface SkillSuggestion {
  name: string
  description: string
}

interface IProps {
  visible: boolean
  query: string
  skills: SkillSuggestion[]
  position?: { left: number }
}

const props = withDefaults(defineProps<IProps>(), {
  position: () => ({ left: 0 }),
})

const emit = defineEmits<{
  select: [skill: SkillSuggestion]
  close: []
}>()

const MAX_VISIBLE_ITEMS = 8

const activeIndex = ref(0)

const filteredSkills = computed(() => {
  const q = props.query.toLowerCase()
  if (!q) return props.skills.slice(0, MAX_VISIBLE_ITEMS)
  return props.skills
    .filter(s => s.name.toLowerCase().includes(q) || s.description.toLowerCase().includes(q))
    .slice(0, MAX_VISIBLE_ITEMS)
})

const positionStyle = computed(() => ({
  position: 'absolute' as const,
  bottom: `calc(100% + 4px)`,
  left: `${props.position.left}px`,
}))

watch(() => props.query, () => {
  activeIndex.value = 0
})

function selectSkill(skill: SkillSuggestion) {
  emit('select', skill)
}

function handleKeyDown(e: KeyboardEvent) {
  if (!props.visible || filteredSkills.value.length === 0) return

  if (e.key === 'ArrowDown') {
    e.preventDefault()
    activeIndex.value = (activeIndex.value + 1) % filteredSkills.value.length
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    activeIndex.value = (activeIndex.value - 1 + filteredSkills.value.length) % filteredSkills.value.length
  } else if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    selectSkill(filteredSkills.value[activeIndex.value])
  } else if (e.key === 'Escape') {
    e.preventDefault()
    emit('close')
  }
}

// Only attach/detach listener when visible to avoid intercepting keys globally
watch(() => props.visible, (isVisible) => {
  if (isVisible) {
    document.addEventListener('keydown', handleKeyDown)
  } else {
    document.removeEventListener('keydown', handleKeyDown)
  }
}, { immediate: true })

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped>
.mention-dropdown {
  background: var(--bg-elevated);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  min-width: 280px;
  max-width: 400px;
  z-index: var(--z-dropdown);
  overflow: hidden;
}

.mention-dropdown__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-2) var(--space-3);
  border-bottom: 1px solid var(--border-color-split);
}

.mention-dropdown__title {
  font-size: var(--font-xs);
  font-weight: var(--font-weight-semibold);
  color: var(--text-tertiary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.mention-dropdown__hint {
  font-size: var(--font-xs);
  color: var(--text-placeholder);
}

.mention-dropdown__list {
  max-height: 240px;
  overflow-y: auto;
  padding: var(--space-1) 0;
}

.mention-dropdown__item {
  display: flex;
  flex-direction: column;
  gap: 2px;
  width: 100%;
  padding: var(--space-2) var(--space-3);
  border: none;
  background: transparent;
  cursor: pointer;
  text-align: left;
  transition: background var(--transition-fast);
}

.mention-dropdown__item:hover,
.mention-dropdown__item--active {
  background: var(--bg-tertiary);
}

.mention-dropdown__item-name {
  font-size: var(--font-sm);
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.mention-dropdown__item-desc {
  font-size: var(--font-xs);
  color: var(--text-tertiary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
