<script setup lang="ts">
import { ref, nextTick } from 'vue'
import type { AcceptanceCriterion } from '@/api/types'
import ACItem from './ACItem.vue'
import { VueDraggable } from 'vue-draggable-plus'

const props = defineProps<{ modelValue: AcceptanceCriterion[] }>()
const emit = defineEmits<{ 'update:modelValue': [value: AcceptanceCriterion[]] }>()

const rootRef = ref<HTMLElement | null>(null)

function updateAC(index: number, ac: AcceptanceCriterion) {
  const updated = [...props.modelValue]
  updated[index] = ac
  emit('update:modelValue', updated)
}

function removeAC(index: number) {
  const updated = props.modelValue.filter((_, i) => i !== index)
  emit('update:modelValue', updated)
  // Focus previous AC after removal
  nextTick(() => focusAC(Math.max(0, index - 1)))
}

async function addAC() {
  emit('update:modelValue', [
    ...props.modelValue,
    { text: '', checked: false, realized_in: [] },
  ])
  await nextTick()
  focusAC(props.modelValue.length - 1)
}

function insertACAfter(index: number) {
  const updated = [...props.modelValue]
  updated.splice(index + 1, 0, { text: '', checked: false, realized_in: [] })
  emit('update:modelValue', updated)
  nextTick(() => focusAC(index + 1))
}

function focusAC(index: number) {
  const items = rootRef.value?.querySelectorAll('[data-ac-input]') ?? []
  const el = items[index] as HTMLInputElement | undefined
  el?.focus()
}

function onDragUpdate(acs: AcceptanceCriterion[]) {
  emit('update:modelValue', acs)
}
</script>

<template>
  <div ref="rootRef" class="mt-3">
    <div class="border-t border-border-light/60 dark:border-slate-800 pt-3">
      <span class="text-[10px] font-medium text-slate-400 uppercase tracking-wider">Acceptance Criteria</span>
    </div>

    <template v-if="modelValue.length > 0">
      <VueDraggable
        :model-value="modelValue"
        handle=".ac-drag-handle"
        :animation="150"
        ghost-class="ac-ghost"
        class="mt-2 space-y-0.5"
        @update:model-value="onDragUpdate"
      >
        <ACItem
          v-for="(ac, i) in modelValue"
          :key="i"
          :model-value="ac"
          :index="i"
          @update:model-value="updateAC(i, $event)"
          @remove="removeAC(i)"
          @insert-after="insertACAfter(i)"
          @focus-next="focusAC(i + 1)"
          @focus-prev="focusAC(i - 1)"
        />
      </VueDraggable>
    </template>
    <div v-else class="mt-2 py-2">
      <span class="text-sm text-slate-400 dark:text-slate-600 italic">No acceptance criteria defined.</span>
    </div>

    <!-- Ghost placeholder to add new AC -->
    <div
      class="flex items-start gap-2 mt-1 cursor-pointer group opacity-40 hover:opacity-70 transition-opacity"
      @click="addAC"
    >
      <input
        type="checkbox"
        disabled
        class="mt-1 rounded border-border-light dark:border-slate-600"
      />
      <span class="text-sm text-slate-400 dark:text-slate-600 italic">Add criterion...</span>
    </div>
  </div>
</template>
