<template>
  <div class="chip-container">
    <div v-for="(chip, i) in modelValue" :key="i" class="chip">
      <span>{{ chip }}</span>
      <i class="delete-icon" @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>

<style scoped lang="scss">
@import '@/assets/scss/main.scss';

.chip-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;

  .chip {
    display: flex;
    gap: 10px;
    align-items: center;
    background-color: $cyan;
    border-radius: 5px;
    padding: 5px 10px;
    margin: 4px;

    .delete-icon {
      cursor: pointer;
      color: $white;
      font-weight: 300;
      font-family: $default;
      font-style: normal;
      &:hover {
        color: $light-gray;
      }
    }
  }
}
</style>
