<template>
  <div class="flex flex-wrap items-center border-0 border-b border-solid border-gray-50">
    <div v-for="(chip, i) in modelValue" :key="i" class="flex gap-2.5 items-center bg-cyan rounded py-1.5 px-2.5 m-1">
      <span>{{ chip }}</span>
      <i class="cursor-pointer text-white font-light font-default not-italic hover:text-gray-50" @click="deleteChip(i)">X</i>
    </div>
    <input class="outline-none border-none max-w-[250px] p-1 m-1 text-white" v-model="currentInput" @keyup.enter="saveChip" @keydown.delete="backspaceDelete" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const modelValue = defineModel('modelValue', { type: Array, default: () => [] })

const currentInput = ref('')

const saveChip = () => {
  if (currentInput.value.trim() && !modelValue.value.includes(currentInput.value)) {
    modelValue.value = [...modelValue.value, currentInput.value]
    currentInput.value = ''
  }
}

const deleteChip = (index) => {
  modelValue.value = modelValue.value.filter((_, i) => i !== index)
}

const backspaceDelete = (event) => {
  if (event.key === 'Backspace' && currentInput.value === '' && modelValue.value.length > 0) {
    modelValue.value = modelValue.value.slice(0, -1)
  }
}
</script>