<script setup lang="ts">
const props = defineProps<{
  modelValue: string[]
  placeholder?: string
}>()

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

const textValue = computed({
  get: () => props.modelValue.join('\n'),
  set: (val: string) => {
    const array = val.split('\n').map(s => s.trim()).filter(s => s.length > 0)
    emit('update:modelValue', array)
  }
})

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

<template>
  <div class="space-y-2">
    <div v-if="modelValue.length > 0" class="flex flex-wrap gap-2">
      <UBadge
        v-for="(item, index) in modelValue"
        :key="index"
        color="neutral"
        variant="soft"
        class="flex items-center gap-1"
      >
        {{ item }}
        <UButton
          icon="i-heroicons-x-mark"
          size="xs"
          color="neutral"
          variant="ghost"
          @click="removeTag(index)"
        />
      </UBadge>
    </div>
    <UTextarea
      :model-value="textValue"
      @update:model-value="textValue = $event"
      :placeholder="placeholder"
      :rows="4"
    />
  </div>
</template>
