<template>
  <div class="space-y-2">
    <label class="block text-sm font-medium text-white/70 mb-1">Headers</label>
    <div
      v-for="(header, index) in headers"
      :key="index"
      class="flex items-center gap-2"
    >
      <input
        type="text"
        placeholder="Key"
        :value="header.key"
        @input="updateHeader(index, 'key', ($event.target as HTMLInputElement).value)"
        class="flex-1 bg-white/5 border border-white/20 rounded-lg px-3 py-1.5 text-white placeholder-white/50 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-500"
      />
      <input
        type="text"
        placeholder="Value"
        :value="header.value"
        @input="updateHeader(index, 'value', ($event.target as HTMLInputElement).value)"
        class="flex-1 bg-white/5 border border-white/20 rounded-lg px-3 py-1.5 text-white placeholder-white/50 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-500"
      />
      <button
        @click="removeHeader(index)"
        class="p-1.5 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded-lg transition-colors"
        title="Remove header"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>
    <button
      @click="addHeader"
      class="text-sm text-cyan-400 hover:text-cyan-300 flex items-center gap-1"
    >
      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
      </svg>
      Add Header
    </button>
  </div>
</template>

<script setup lang="ts">
interface Header {
  key: string
  value: string
}

const props = defineProps<{
  modelValue: Header[]
}>()

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

const headers = props.modelValue.length ? props.modelValue : [{ key: '', value: '' }]

const addHeader = () => {
  emit('update:modelValue', [...props.modelValue, { key: '', value: '' }])
}

const removeHeader = (index: number) => {
  const newHeaders = [...props.modelValue]
  newHeaders.splice(index, 1)
  emit('update:modelValue', newHeaders.length ? newHeaders : [{ key: '', value: '' }])
}

const updateHeader = (index: number, field: keyof Header, value: string) => {
  const newHeaders = [...props.modelValue]
  newHeaders[index] = { ...newHeaders[index], [field]: value }
  emit('update:modelValue', newHeaders)
}
</script>
