<template>
  <v-card>
    <v-card-title>Treat as alias for…</v-card-title>
    <v-card-text>
      <p class="text-caption mb-2">
        Pick the existing tag the model's prediction should map to. All
        future predictions of this name will resolve to your tag.
      </p>
      <v-autocomplete
        v-model="selectedId"
        v-model:menu="menuOpen"
        :items="results"
        :item-title="(t) => t.fandom_name ? `${t.name} — ${t.fandom_name}` : t.name"
        :item-value="(t) => t.id"
        :loading="loading"
        label="Canonical tag"
        no-filter clearable density="compact"
        @update:search="onSearch"
        @keydown.enter.capture="onEnter"
      />
    </v-card-text>
    <v-card-actions>
      <v-spacer />
      <v-btn @click="$emit('cancel')">Cancel</v-btn>
      <v-btn
        color="primary" rounded="pill" :disabled="!selectedId"
        @click="$emit('confirm', selectedId)"
      >Use this tag</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script setup>
import { ref } from 'vue'
import { useApi } from '../../composables/useApi.js'
import { useAcceptOnEnter } from '../../composables/useAcceptOnEnter.js'

const props = defineProps({ category: { type: String, required: true } })
const emit = defineEmits(['confirm', 'cancel'])

const api = useApi()
const results = ref([])
const loading = ref(false)
const selectedId = ref(null)
let debounce = null

// Enter on the closed dropdown confirms the selection instead of re-opening it.
const { menuOpen, onEnter } = useAcceptOnEnter(() => {
  if (selectedId.value != null) emit('confirm', selectedId.value)
})

function onSearch(q) {
  if (debounce) clearTimeout(debounce)
  debounce = setTimeout(async () => {
    const query = (q || '').trim()
    if (!query) { results.value = []; return }
    loading.value = true
    try {
      // Scope the autocomplete to the prediction's category where it
      // maps to a tag kind. Only 'character' surfaces as both a
      // suggestion category and a tag kind now ('artist' + 'copyright'
      // retired); other categories search unscoped.
      const kind = props.category === 'character' ? 'character' : null
      const params = { q: query, limit: 20 }
      if (kind) params.kind = kind
      results.value = await api.get('/api/tags/autocomplete', { params })
    } finally {
      loading.value = false
    }
  }, 200)
}
</script>
