<template>
  <!-- Thin debounced tag-search autocomplete: emits `pick` with the chosen tag
       and self-clears. Shared by the gallery's advanced tag-query builder; the
       filter bar's own inline search predates this and also folds in artists. -->
  <v-autocomplete
    v-model="selected"
    :items="items"
    :loading="loading"
    item-title="name" item-value="id"
    no-filter hide-details density="compact" variant="outlined"
    :placeholder="placeholder"
    prepend-inner-icon="mdi-tag-plus-outline"
    :aria-label="placeholder"
    @update:search="onSearch"
    @update:model-value="onPick"
  >
    <template #item="{ props: itemProps, internalItem }">
      <v-list-item v-bind="itemProps" :title="internalItem.raw.name">
        <template #subtitle>
          {{ internalItem.raw.fandom_name ? `character · ${internalItem.raw.fandom_name}` : internalItem.raw.kind }}
        </template>
      </v-list-item>
    </template>
    <template #no-data>
      <v-list-item :title="searchedOnce ? 'No tags match' : 'Type to search tags'" />
    </template>
  </v-autocomplete>
</template>

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

defineProps({ placeholder: { type: String, default: 'Add tag…' } })
const emit = defineEmits(['pick'])

const api = useApi()
const selected = ref(null)
const items = ref([])
const loading = ref(false)
const searchedOnce = ref(false)
let debounce = null

function onSearch (q) {
  if (debounce) clearTimeout(debounce)
  if (!q || !q.trim()) { items.value = []; return }
  debounce = setTimeout(async () => {
    loading.value = true
    try {
      items.value = (await api.get('/api/tags/autocomplete', { params: { q, limit: 10 } })) || []
    } catch {
      items.value = []
    } finally {
      loading.value = false
      searchedOnce.value = true
    }
  }, 250)
}

function onPick (id) {
  const tag = items.value.find((i) => i.id === id)
  selected.value = null
  items.value = []
  if (tag) emit('pick', tag)
}

onBeforeUnmount(() => { if (debounce) clearTimeout(debounce) })
</script>
