<template>
  <WidgetShell title="Contact lookup" icon="mdi-account-search-outline" :loading="loading" :editing="editing" @refresh="search" @remove="$emit('remove')">
    <v-text-field v-model="q" density="compact" placeholder="Name, organization, or email" prepend-inner-icon="mdi-magnify" hide-details @keyup.enter="search" />
    <v-list density="compact" class="py-0 mt-1">
      <v-list-item v-for="c in rows" :key="c.id" class="px-0">
        <v-list-item-title class="text-body-2">{{ name(c) }}</v-list-item-title>
        <v-list-item-subtitle class="text-caption">{{ (c.type || '').replace('_', ' ') }}<span v-if="c.email"> · {{ c.email }}</span><span v-if="c.phone"> · {{ c.phone }}</span></v-list-item-subtitle>
      </v-list-item>
      <v-list-item v-if="searched && !rows.length && !loading"><span class="quiet text-body-2">No matching contacts.</span></v-list-item>
    </v-list>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { apiRequest } from '../../services/api';
export default {
  components: { WidgetShell },
  props: { token: { type: String, required: true }, editing: { type: Boolean, default: false }, config: { type: Object, default: () => ({}) } },
  emits: ['remove'],
  data() { return { q: '', rows: [], loading: false, searched: false }; },
  methods: {
    name(c) { return c.organization || [c.first_name, c.last_name].filter(Boolean).join(' ') || 'Contact'; },
    async search() {
      this.loading = true; this.searched = true;
      try { this.rows = ((await (await apiRequest(`/api/contacts?search=${encodeURIComponent(this.q.trim())}`, this.token)).json()).contacts || []).slice(0, 8); }
      catch { this.rows = []; } finally { this.loading = false; }
    }
  }
};
</script>
