<template>
  <div class="keyword-input">
    <el-tag
      v-for="(keyword, index) in modelValue"
      :key="index"
      closable
      type="info"
      size="small"
      @close="handleRemove(index)"
      class="keyword-tag"
    >
      {{ keyword }}
    </el-tag>
    <el-input
      v-model="inputValue"
      :placeholder="placeholder"
      size="small"
      @keyup.enter="handleAdd"
      @blur="handleAdd"
      class="input-field"
    />
  </div>
</template>

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

const props = defineProps<{
  modelValue: string[]
  placeholder?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
}>()

const inputValue = ref('')

const handleAdd = () => {
  const value = inputValue.value.trim()
  if (value && !props.modelValue.includes(value)) {
    emit('update:modelValue', [...props.modelValue, value])
  }
  inputValue.value = ''
}

const handleRemove = (index: number) => {
  const newValue = [...props.modelValue]
  newValue.splice(index, 1)
  emit('update:modelValue', newValue)
}
</script>

<style scoped>
.keyword-input {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px;
  padding: 8px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  min-height: 40px;
}

.keyword-input:focus-within {
  border-color: var(--el-color-primary);
}

.keyword-tag {
  margin: 0;
}

.input-field {
  width: 120px;
  flex-shrink: 0;
}

.input-field :deep(.el-input__wrapper) {
  box-shadow: none;
  padding: 0 4px;
}

.input-field :deep(.el-input__wrapper):focus-within {
  box-shadow: none;
}
</style>
