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

const props = defineProps<{
  modelValue: string
  suggestions: Array<{ label: string; value: string }>
  placeholder?: string
}>()

const emit = defineEmits(['update:modelValue', 'select'])

const isOpen = ref(false)

const filtered = computed(() => {
  if (!props.modelValue) return props.suggestions
  return props.suggestions.filter(s => s.label.toLowerCase().includes(props.modelValue.toLowerCase()) || s.value.includes(props.modelValue))
})

const select = (item: { label: string; value: string }) => {
  emit('update:modelValue', item.value)
  emit('select', item)
  isOpen.value = false
}
</script>

<template>
  <div style="position: relative; width: 100%;">
    <input
      :value="modelValue"
      type="text"
      :placeholder="placeholder || '자동완성 검색...'"
      style="width: 100%; box-sizing: border-box; padding: 4px 8px; border: 1px solid #CBD5E1; border-radius: 2px; font-size: 12px; font-weight: bold;"
      @focus="isOpen = true"
      @input="emit('update:modelValue', ($event.target as HTMLInputElement).value); isOpen = true"
    />
    <div v-if="isOpen && filtered.length > 0" style="position: absolute; top: 100%; left: 0; width: 100%; background: white; border: 1px solid #CBD5E1; box-shadow: 0 4px 8px rgba(0,0,0,0.1); z-index: 1000; max-height: 150px; overflow-y: auto;">
      <div
        v-for="item in filtered"
        :key="item.value"
        style="padding: 6px 8px; font-size: 12px; cursor: pointer; border-bottom: 1px solid #ECF0F1;"
        @click="select(item)">
        <strong>{{ item.label }}</strong> ({{ item.value }})
      </div>
    </div>
  </div>
</template>
