<script setup lang="ts">
import { ref, watch } from 'vue'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'

interface Props {
  modelValue: string[] | undefined
  placeholder?: string
}
const props = withDefaults(defineProps<Props>(), { placeholder: 'Add an example…' })
const emit = defineEmits<{ (e: 'update:modelValue', v: string[]): void }>()

const list = ref<string[]>([])
const newItem = ref('')

watch(
  () => props.modelValue,
  (v) => {
    list.value = Array.isArray(v) ? [...v] : []
  },
  { immediate: true }
)

function commit() {
  const v = newItem.value.trim()
  if (!v) return
  if (!list.value.includes(v)) list.value.push(v)
  emit('update:modelValue', [...list.value])
  newItem.value = ''
}
function removeAt(i: number) {
  list.value.splice(i, 1)
  emit('update:modelValue', [...list.value])
}
</script>

<template>
  <div class="space-y-2 w-full">
    <div class="flex items-center gap-2 w-full">
      <Input
        v-model="newItem"
        :placeholder="placeholder"
        class="flex-1 admin-input"
        @keydown.enter.prevent="commit"
      />
      <Button size="sm" variant="outline" @click="commit" class="admin-btn admin-btn--secondary">
        <i class="dku-icon-plus-16 mr-1"></i>
        Add
      </Button>
    </div>

    <ul class="space-y-1 w-full">
      <li
        v-for="(q, i) in list"
        :key="i"
        class="admin-list-item flex items-center justify-between text-sm py-1 px-3 rounded w-full"
      >
        <span class="truncate">{{ q }}</span>
        <Button
          size="sm"
          variant="ghost"
          class="admin-icon--trash flex-shrink-0"
          @click="removeAt(i)"
          title="Delete question"
        >
          <i class="dku-icon-trash-16"></i>
        </Button>
      </li>
    </ul>
  </div>
</template>

<style scoped>
.admin-list-item {
  background-color: var(--admin-bg-selected);
}
</style>
