<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Arquivo: src/features/documents/components/DocumentTagsInput.vue
| Input de tags livres com chips editaveis e autocomplete.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
    modelValue: { type: Array, default: () => [] },
    suggestions: { type: Array, default: () => [] },
    placeholder: { type: String, default: 'Adicionar tag...' },
    maxTags: { type: Number, default: 20 }
})

const emit = defineEmits(['update:modelValue'])

const inputValue = ref('')
const inputRef = ref(null)
const showSuggestions = ref(false)

const tags = computed({
    get: () => props.modelValue || [],
    set: (val) => emit('update:modelValue', val)
})

const filteredSuggestions = computed(() => {
    const q = inputValue.value.toLowerCase().trim()
    if (!q) return []
    return props.suggestions
        .filter(s => s.toLowerCase().includes(q) && !tags.value.includes(s))
        .slice(0, 8)
})

function addTag(value) {
    const tag = String(value || '').trim().toLowerCase()
    if (!tag) return
    if (tags.value.includes(tag)) return
    if (tags.value.length >= props.maxTags) return

    tags.value = [...tags.value, tag]
    inputValue.value = ''
    showSuggestions.value = false
}

function removeTag(index) {
    const copy = [...tags.value]
    copy.splice(index, 1)
    tags.value = copy
}

function onKeydown(e) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault()
        addTag(inputValue.value)
    }
    if (e.key === 'Backspace' && !inputValue.value && tags.value.length) {
        removeTag(tags.value.length - 1)
    }
}

function onInput() {
    showSuggestions.value = inputValue.value.trim().length > 0
}

function selectSuggestion(s) {
    addTag(s)
    inputRef.value?.$el?.focus()
}
</script>

<template>
    <div class="relative">
        <div
            class="flex flex-wrap items-center gap-1.5 min-h-[2.5rem] px-2.5 py-1.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-overlay)] focus-within:border-primary focus-within:ring-1 focus-within:ring-primary/20 transition-colors"
        >
            <!-- Tags existentes -->
            <span
                v-for="(tag, idx) in tags"
                :key="tag"
                class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary"
            >
                {{ tag }}
                <i
                    class="pi pi-times text-[0.55rem] cursor-pointer opacity-60 hover:opacity-100"
                    @click="removeTag(idx)"
                />
            </span>

            <!-- Input -->
            <InputText
                ref="inputRef"
                v-model="inputValue"
                :placeholder="tags.length ? '' : placeholder"
                class="!border-0 !shadow-none !ring-0 !p-0 !min-w-[80px] flex-1 text-sm !bg-transparent"
                @keydown="onKeydown"
                @input="onInput"
                @focus="onInput"
                @blur="setTimeout(() => showSuggestions = false, 150)"
            />
        </div>

        <!-- Dropdown sugestoes -->
        <div
            v-if="showSuggestions && filteredSuggestions.length"
            class="absolute z-50 top-full left-0 right-0 mt-1 py-1 rounded-md border border-[var(--surface-border)] bg-[var(--surface-overlay)] shadow-lg max-h-[200px] overflow-y-auto"
        >
            <button
                v-for="s in filteredSuggestions"
                :key="s"
                class="w-full text-left px-3 py-1.5 text-sm hover:bg-[var(--surface-hover)] transition-colors"
                @mousedown.prevent="selectSuggestion(s)"
            >
                {{ s }}
            </button>
        </div>
    </div>
</template>
