<template>
  <div class="relative group/input" ref="containerRef">
    <input 
      :name="name" 
      type="text" 
      class="peer w-full bg-transparent border-b border-white/20 py-2 text-white font-serif text-lg focus:border-art-accent outline-none transition-colors placeholder-transparent" 
      :placeholder="placeholder"
      :value="modelValue"
      @input="handleInput"
      @focus="showDropdown = true"
      @blur="handleBlur"
      autocomplete="off"
    >
    <label 
      class="absolute left-0 top-2 text-white/30 text-xs font-mono transition-all peer-focus:-top-4 peer-focus:text-art-accent peer-autofill:-top-4 peer-autofill:text-art-accent pointer-events-none"
      :class="modelValue ? '-top-4 text-white/50' : ''"
    >{{ label }}</label>

    <!-- Autocomplete Dropdown -->
    <div v-if="showDropdown && suggestions.length > 0" class="absolute z-[9999] left-0 right-0 top-full mt-1 bg-[#1a1a1a] border border-white/10 shadow-lg max-h-48 overflow-y-auto rounded-b-md">
      <div 
        v-for="(suggestion, index) in suggestions" 
        :key="index"
        class="px-4 py-2 text-sm text-white/70 hover:bg-art-accent hover:text-black cursor-pointer transition-colors font-mono"
        @mousedown.prevent="selectSuggestion(suggestion)"
      >
        {{ suggestion }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { fetchEmailSuffixes, type EmailSuffix } from '../../services/api'

const props = defineProps<{
  name: string
  label: string
  placeholder?: string
  modelValue: string
}>()

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

const showDropdown = ref(false)
const emailSuffixes = ref<string[]>([])
const containerRef = ref<HTMLElement | null>(null)

// Load suffixes from API
onMounted(async () => {
  try {
    const suffixes = await fetchEmailSuffixes()
    emailSuffixes.value = suffixes.map(s => s.suffix)
  } catch (e) {
    // Fallback defaults if API fails
    emailSuffixes.value = ['@gmail.com', '@163.com', '@qq.com', '@outlook.com']
  }
})

const handleInput = (e: Event) => {
  const val = (e.target as HTMLInputElement).value
  emit('update:modelValue', val)
  showDropdown.value = true
}

const handleBlur = () => {
  // Delay hiding to allow click event on dropdown to fire
  setTimeout(() => {
    showDropdown.value = false
  }, 200)
}

const suggestions = computed(() => {
  if (!props.modelValue || props.modelValue.includes('@')) return []
  return emailSuffixes.value.map(suffix => `${props.modelValue}${suffix}`)
})

const selectSuggestion = (val: string) => {
  emit('update:modelValue', val)
  showDropdown.value = false
}
</script>
