<template>
  <!-- Zone chatbot desktop — sous la carte, expand/collapse -->
  <div
    class="chatbot-placeholder shrink-0"
    :class="{ expanded: isExpanded }"
    style="border-top: 1px solid var(--nav-bg-alt); background: var(--nav-bg);"
  >
    <!-- ── HEADER (toujours visible, cliquable) ── -->
    <div
      class="chatbot-header"
      @click="toggleExpand"
      role="button"
      tabindex="0"
      :aria-expanded="isExpanded"
      aria-label="Ouvrir l'assistant chatbot"
      @keydown.enter="toggleExpand"
      @keydown.space.prevent="toggleExpand"
    >
      <!-- Icône chatbot -->
      <div
        class="shrink-0 w-7 h-7 rounded-full flex items-center justify-center"
        style="background: var(--nav-primary);"
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="color: var(--nav-text-on-primary);">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
        </svg>
      </div>

      <span class="flex-1 text-sm" style="color: var(--nav-text-muted);">
        {{ isExpanded ? 'Chatbot AEP' : 'Pose une question sur le réseau…' }}
      </span>

      <!-- Chevron -->
      <button
        type="button"
        class="chatbot-chevron"
        :aria-label="isExpanded ? 'Replier le chatbot' : 'Ouvrir le chatbot'"
        @click.stop="toggleExpand"
      >
        <svg
          width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
          :style="{ transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.3s ease' }"
        >
          <polyline points="18 15 12 9 6 15"/>
        </svg>
      </button>
    </div>

    <!-- ── ZONE ÉTENDUE ── -->
    <div class="chatbot-body">
      <div class="chatbot-body-inner" ref="messagesContainer">
        <!-- Onboarding -->
        <div v-if="messages.length === 0" class="onboarding-bubble">
          <p>Explore les 120 structures de la carte par la conversation. Je peux t'aider à trouver des collectifs, agences ou réseaux selon ta situation, ta pratique ou tes inspirations du moment.</p>
          <p class="example">Exemple : "Je cherche des acteurs de la rénovation de maisons individuelles en France, plutôt en milieu rural, avec des approches biosourcées ou low-tech."</p>
          <p style="margin-top: 8px; font-size: 0.72rem; opacity: 0.6;">Propulsé par Mistral FR - serveur européen souverain, zéro rétention.</p>
        </div>

        <!-- Messages -->
        <template v-for="(msg, i) in messages" :key="i">
          <div v-if="msg.role === 'user'" class="user-bubble">{{ msg.content }}</div>
          <div v-else class="assistant-bubble">
            <p>{{ msg.content }}</p>
            <div v-if="msg.fiches && msg.fiches.length > 0" class="fiches-list">
              <p class="fiches-title">Fiches recommandees :</p>
              <a
                v-for="fiche in msg.fiches"
                :key="fiche.id"
                :href="`/fiche/${fiche.id}`"
                class="fiche-card"
              >
                <span class="fiche-nom">{{ fiche.nom }}</span>
                <span v-if="fiche.explication" class="fiche-expl">{{ fiche.explication }}</span>
              </a>
            </div>
            <div v-if="msg.suggestedHashtags && msg.suggestedHashtags.length" style="margin-top: 8px;">
              <p style="font-size: 0.7rem; color: var(--nav-text-muted); margin-bottom: 4px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em;">Filtrer par :</p>
              <div style="display: flex; flex-wrap: wrap; gap: 4px;">
                <span
                  v-for="tag in msg.suggestedHashtags"
                  :key="tag"
                  style="
                    padding: 2px 8px; border-radius: 9999px; font-size: 0.7rem; cursor: pointer;
                    background: var(--nav-bg-alt); color: var(--nav-text); border: 1px solid var(--nav-bg-alt);
                    transition: all 0.15s;
                  "
                  @click="emit('applyHashtag', tag)"
                >{{ tag }}</span>
              </div>
            </div>
          </div>
        </template>

        <!-- Chargement -->
        <div v-if="loading" class="assistant-bubble loading-bubble">
          <span class="dot" /><span class="dot" /><span class="dot" />
        </div>

        <!-- Erreur -->
        <div v-if="errorMsg" class="error-bubble">{{ errorMsg }}</div>
      </div>

      <!-- Input -->
      <div class="chatbot-input-row" style="border-top: 1px solid var(--nav-bg-alt);">
        <input
          v-model="inputText"
          type="text"
          :disabled="loading"
          placeholder="Pose ta question…"
          class="chatbot-input"
          @keydown.enter.prevent="sendMessage"
        />
        <button
          :disabled="loading || !inputText.trim()"
          class="chatbot-send"
          aria-label="Envoyer"
          @click="sendMessage"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="color: var(--nav-text-on-primary);">
            <line x1="22" y1="2" x2="11" y2="13"/>
            <polygon points="22 2 15 22 11 13 2 9 22 2"/>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
interface FicheReco {
  id: number | string
  nom: string
  explication?: string
}

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  fiches?: FicheReco[]
  suggestedHashtags?: string[]
}

const emit = defineEmits<{
  'highlightOrgs': [ids: (number | string)[]]
  'applyHashtag': [tag: string]
}>()

const isExpanded = ref(false)
const messages = ref<ChatMessage[]>([])
const inputText = ref('')
const loading = ref(false)
const errorMsg = ref('')
const messagesContainer = ref<HTMLElement | null>(null)

// Detection hashtags depuis la question posee
const HASHTAG_KEYWORDS: Record<string, string[]> = {
  '#reemploi-structurel': ['reemploi', 'materiaux recuperes', 'deconstruction', 'reemploi structurel'],
  '#reemploi-second-oeuvre': ['revetement', 'second oeuvre', 'reemploi'],
  '#biosource-geosource': ['biosource', 'geosource', 'paille', 'terre', 'chanvre', 'lin', 'biosource'],
  '#low-tech-experimentation': ['low-tech', 'low tech', 'technique simple', 'autonomie', 'lowtech'],
  '#chantier-ecole': ['formation', 'chantier ecole', 'chantier-ecole', 'apprendre', 'auto-construction', 'autoconstruction'],
  '#sobriete-energetique': ['sobriete', 'energie', 'renovation energetique', 'isolation', 'chauffage', 'economie energie'],
  '#mal-logement-precarite': ['mal-logement', 'precarite', 'sans-abri', 'logement social', 'squat', 'mal logement'],
  '#tiers-lieux-friches': ['friche', 'tiers-lieu', 'tiers lieu', 'espace intermediaire', 'temporaire', 'reconversion'],
  '#accompagnement-cooperatif': ['cooperative', 'accompagnement', 'cooperation', 'collectif', 'mutualisation'],
  '#transition-energetique-territoriale': ['territoire', 'transition', 'energetique', 'local', 'region', 'transition energetique'],
  '#communs-fonciers': ['communs', 'foncier', 'anti-speculatif', 'community land trust', 'commun foncier'],
  '#hack-juridique': ['juridique', 'montage', 'structure legale', 'sci', 'cooperative', 'statut'],
  '#retrofit-strates': ['retrofit', 'renovation lourde', 'sur-isolation', 'rehaussement'],
  '#phytoconstruction': ['plantes', 'vegetal', 'arbre', 'construction vivante', 'phyto'],
}

function detectHashtagsFromQuery(query: string): string[] {
  const q = query.toLowerCase()
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
  const detected: string[] = []
  for (const [hashtag, keywords] of Object.entries(HASHTAG_KEYWORDS)) {
    if (keywords.some(kw => q.includes(kw))) {
      detected.push(hashtag)
    }
  }
  return detected.slice(0, 3)
}

function toggleExpand() {
  isExpanded.value = !isExpanded.value
}

async function sendMessage() {
  const question = inputText.value.trim()
  if (!question || loading.value) return

  inputText.value = ''
  errorMsg.value = ''
  messages.value.push({ role: 'user', content: question })
  loading.value = true

  await nextTick()
  scrollToBottom()

  try {
    const res = await $fetch<{
      reponse_texte: string
      fiches_recommandees: { id: number | string; nom: string; explication: string }[]
    }>('/api/chatbot', {
      method: 'POST',
      body: { question },
    })

    const suggestedHashtags = detectHashtagsFromQuery(question)
    const assistantMsg: ChatMessage = {
      role: 'assistant',
      content: res.reponse_texte,
      fiches: res.fiches_recommandees || [],
      suggestedHashtags: suggestedHashtags.length ? suggestedHashtags : undefined,
    }
    messages.value.push(assistantMsg)

    if (assistantMsg.fiches && assistantMsg.fiches.length > 0) {
      emit('highlightOrgs', assistantMsg.fiches.map((f) => f.id))
    }
  } catch (e: any) {
    const status = e?.statusCode ?? e?.status
    if (status === 429) {
      errorMsg.value = 'Limite de 10 questions par jour atteinte. Reviens demain.'
    } else if (status === 503) {
      errorMsg.value = 'Le budget IA mensuel est épuisé. Soutiens NAV sur Liberapay pour continuer.'
    } else {
      errorMsg.value = 'Une erreur est survenue. Réessaie dans quelques instants.'
    }
  } finally {
    loading.value = false
    await nextTick()
    scrollToBottom()
  }
}

function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}
</script>

<style scoped>
.chatbot-placeholder {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: max-height 0.3s ease;
  max-height: 56px;
}
.chatbot-placeholder.expanded {
  max-height: 55vh;
}

.chatbot-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  cursor: pointer;
  min-height: 56px;
  flex-shrink: 0;
  user-select: none;
}
.chatbot-header:hover { background: var(--nav-surface); }

.chatbot-chevron {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--nav-text-muted);
  flex-shrink: 0;
  padding: 4px;
  border-radius: 6px;
  border: none;
  background: transparent;
  cursor: pointer;
  transition: color 0.15s, background 0.15s;
}
.chatbot-chevron:hover {
  color: var(--nav-text);
  background: var(--nav-bg-alt);
}

.chatbot-body {
  flex: 1;
  overflow: hidden;
  border-top: 1px solid var(--nav-bg-alt);
  display: none;
  flex-direction: column;
}
.chatbot-placeholder.expanded .chatbot-body {
  display: flex;
}

.chatbot-body-inner {
  flex: 1;
  overflow-y: auto;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chatbot-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  flex-shrink: 0;
}
.chatbot-input {
  flex: 1;
  padding: 8px 12px;
  border-radius: 10px;
  border: 1px solid var(--nav-bg-alt);
  background: var(--nav-surface);
  color: var(--nav-text);
  font-size: 0.8rem;
  font-family: var(--nav-font);
}
.chatbot-send {
  width: 34px;
  height: 34px;
  border-radius: 8px;
  background: var(--nav-primary);
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: opacity 0.15s;
}
.chatbot-send:disabled { opacity: 0.4; cursor: not-allowed; }

/* Messages */
.onboarding-bubble {
  background: var(--nav-bg-alt);
  border-radius: 10px;
  padding: 12px;
  font-size: 0.78rem;
  line-height: 1.6;
  color: var(--nav-text-muted);
  white-space: pre-line;
}
.onboarding-bubble p { margin-bottom: 8px; }
.onboarding-bubble ul { margin: 6px 0; padding: 0; list-style: none; }
.onboarding-bubble li { margin-bottom: 2px; }
.onboarding-bubble .example { font-style: italic; opacity: 0.8; font-size: 0.75rem; margin-top: 8px; }

.user-bubble {
  align-self: flex-end;
  max-width: 80%;
  background: var(--nav-primary);
  color: var(--nav-text-on-primary);
  border-radius: 12px 12px 4px 12px;
  padding: 8px 12px;
  font-size: 0.8rem;
  line-height: 1.5;
}

.assistant-bubble {
  align-self: flex-start;
  max-width: 92%;
  background: var(--nav-surface);
  border: 1px solid var(--nav-bg-alt);
  border-radius: 12px 12px 12px 4px;
  padding: 10px 12px;
  font-size: 0.8rem;
  line-height: 1.6;
  color: var(--nav-text);
}
.assistant-bubble p { margin: 0; }

.fiches-list { margin-top: 8px; display: flex; flex-direction: column; gap: 4px; }
.fiches-title { font-size: 0.7rem; font-weight: 600; color: var(--nav-text-muted); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
.fiche-card {
  display: block;
  background: var(--nav-bg);
  border: 1px solid var(--nav-bg-alt);
  border-radius: 6px;
  padding: 6px 10px;
  text-decoration: none;
  transition: border-color 0.15s;
}
.fiche-card:hover { border-color: var(--nav-primary); }
.fiche-nom { display: block; font-size: 0.775rem; font-weight: 600; color: var(--nav-text); }
.fiche-expl { display: block; font-size: 0.72rem; color: var(--nav-text-muted); margin-top: 1px; }

.loading-bubble { display: flex; gap: 4px; padding: 10px 14px; }
.dot {
  width: 6px; height: 6px;
  background: var(--nav-text-muted);
  border-radius: 50%;
  animation: blink 1.2s infinite ease-in-out;
}
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink {
  0%, 80%, 100% { opacity: 0.3; transform: scale(0.85); }
  40% { opacity: 1; transform: scale(1); }
}

.error-bubble {
  background: rgba(220, 50, 50, 0.07);
  border: 1px solid rgba(220, 50, 50, 0.18);
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 0.78rem;
  color: #c0392b;
  text-align: center;
}

@media (prefers-reduced-motion: reduce) {
  .chatbot-placeholder { transition: none; }
  .dot { animation: none; opacity: 0.5; }
}
</style>
