import { ref } from 'vue'

/** 邮箱后缀候选列表 */
export const EMAIL_SUFFIXES = ['qq.com', 'ctbu.edu.cn', '163.com']

/**
 * 根据当前输入生成邮箱自动补全候选
 * @param {string} value 输入值
 * @param {string[]} [suffixes=EMAIL_SUFFIXES] 后缀列表
 * @returns {string[]}
 */
export function buildEmailSuggestions(value, suffixes = EMAIL_SUFFIXES) {
  const input = (value || '').trim()
  if (!input) return []

  if (!input.includes('@')) {
    return suffixes.map((suffix) => `${input}@${suffix}`)
  }

  if (input.endsWith('@')) {
    return suffixes.map((suffix) => `${input}${suffix}`)
  }

  const [prefix, suffixPart] = input.split('@')
  return suffixes
    .filter((suffix) => suffix.startsWith(suffixPart))
    .map((suffix) => `${prefix}@${suffix}`)
}

/**
 * 邮箱自动补全 composable
 * @param {string[]} [suffixes=EMAIL_SUFFIXES]
 */
export function useEmailAutocomplete(suffixes = EMAIL_SUFFIXES) {
  const emailOptions = ref([])

  const handleEmailSearch = (value) => {
    emailOptions.value = buildEmailSuggestions(value, suffixes)
  }

  const clearEmailOptions = () => {
    emailOptions.value = []
  }

  return {
    emailOptions,
    handleEmailSearch,
    clearEmailOptions,
  }
}
