<template>
  <!-- Sélecteur de destinataire(s) RÉUTILISABLE : autosuggest flou (pg_trgm via /collab/customer-search) dès la frappe.
       Pattern q-input + menu de résultats + puces (le même, éprouvé, que le composeur). v-model = tableau de COURRIELS.
       On peut aussi taper un courriel libre + Entrée (clients non fichés). -->
  <div>
    <div v-if="modelValue.length" class="rs-chips q-mb-xs">
      <q-chip v-for="(em, i) in modelValue" :key="em" dense removable size="sm" color="green-1" text-color="green-9" @remove="removeAt(i)">{{ em }}</q-chip>
    </div>
    <q-input :model-value="query" @update:model-value="onInput" dense outlined :label="label"
      autocomplete="off" name="rs-recipient" @keydown.enter.prevent="addTyped" @keydown.esc="menuOpen = false">
      <template #prepend><q-icon :name="icon" size="16px" color="grey-6" /></template>
      <template #append><q-spinner v-if="busy" size="14px" color="primary" /></template>
      <q-menu v-model="menuOpen" no-focus no-parent-event fit anchor="bottom left" self="top left" style="min-width:260px">
        <q-list dense>
          <q-item v-for="m in results" :key="m.name" clickable v-close-popup @click="pick(m)">
            <q-item-section avatar>
              <q-icon :name="m.kind === 'équipe' ? 'groups' : 'account_circle'" :color="m.kind === 'équipe' ? 'teal-6' : 'blue-6'" size="20px" />
            </q-item-section>
            <q-item-section>
              <q-item-label>
                {{ m.customer_name || m.name }}
                <q-badge v-if="m.kind === 'équipe'" color="green-1" text-color="green-9" class="q-ml-xs" label="Équipe" />
              </q-item-label>
              <q-item-label caption>{{ m.email }}{{ m.matched && m.kind !== 'équipe' ? ' · ' + m.matched : '' }}</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-menu>
    </q-input>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { HUB_URL } from 'src/config/hub'

const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  label: { type: String, default: '' },
  icon: { type: String, default: 'person' },
  team: { type: Boolean, default: true }, // inclure les membres de l'équipe (en PREMIER) — pour choisir un collègue comme destinataire
})
const emit = defineEmits(['update:modelValue'])

const query = ref('')
const results = ref([])
const busy = ref(false)
const menuOpen = ref(false)
let _t = null

function onInput (v) {
  query.value = v == null ? '' : v
  clearTimeout(_t)
  const q = String(v || '').trim()
  if (q.length < 2) { results.value = []; menuOpen.value = false; return }
  _t = setTimeout(async () => {
    busy.value = true
    try {
      const r = await fetch(`${HUB_URL}/collab/customer-search?q=${encodeURIComponent(q)}${props.team ? '&team=1' : ''}`)
      const d = r.ok ? await r.json() : {}
      results.value = (d.matches || []).filter(m => m.email)
      menuOpen.value = results.value.length > 0
    } catch (e) { results.value = []; menuOpen.value = false } finally { busy.value = false }
  }, 250)
}
function add (email) {
  const e = String(email || '').trim()
  if (e && !props.modelValue.includes(e)) emit('update:modelValue', [...props.modelValue, e])
  query.value = ''; results.value = []; menuOpen.value = false; clearTimeout(_t)
}
function pick (m) { add(m.email) }
function addTyped () { if (query.value.trim()) add(query.value.trim()) }
function removeAt (i) { const a = [...props.modelValue]; a.splice(i, 1); emit('update:modelValue', a) }
</script>

<style scoped>
.rs-chips { display: flex; flex-wrap: wrap; gap: 4px; }
</style>
