<script setup lang="ts">
import type { Testimonial, PersonalityType } from '~/types/testimonial'

interface Props {
  testimonials: Testimonial[]
  initialIndex?: number
}

const props = withDefaults(defineProps<Props>(), {
  initialIndex: 0,
})

const emit = defineEmits<{
  complete: []
}>()

const { t } = useI18n()

// État du dialogue actuel
const currentIndex = ref(props.initialIndex)
const currentTestimonial = computed(() => props.testimonials[currentIndex.value])
const totalCount = computed(() => props.testimonials.length)

// Typewriter
const currentText = computed(() => currentTestimonial.value?.text ?? '')
const { displayedText, isTyping, accelerate, skip, start } = useTypewriter(currentText, {
  speed: 35,
  speedMultiplier: 5,
})

// Démarrer au montage et quand le témoignage change
watch(currentIndex, () => {
  nextTick(() => start())
})

onMounted(() => {
  start()
})

// Navigation
function goToPrevious() {
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

function goToNext() {
  if (isTyping.value) {
    skip()
    return
  }

  if (currentIndex.value < totalCount.value - 1) {
    currentIndex.value++
  } else {
    emit('complete')
  }
}

// Interaction clavier
function handleKeydown(e: KeyboardEvent) {
  switch (e.key) {
    case 'ArrowLeft':
      e.preventDefault()
      goToPrevious()
      break
    case 'ArrowRight':
      e.preventDefault()
      goToNext()
      break
    case ' ':
    case 'Enter':
      e.preventDefault()
      if (isTyping.value) {
        accelerate()
      } else {
        goToNext()
      }
      break
  }
}

// Interaction clic sur la bulle
function handleBubbleClick() {
  if (isTyping.value) {
    accelerate()
  } else {
    goToNext()
  }
}

// Styles selon personnalité
const personalityConfig: Record<PersonalityType, { bubble: string; accent: string }> = {
  sage: {
    bubble: 'bg-emerald-500/10 border-emerald-500',
    accent: 'border-r-emerald-500/20',
  },
  sarcastique: {
    bubble: 'bg-purple-500/10 border-purple-500',
    accent: 'border-r-purple-500/20',
  },
  enthousiaste: {
    bubble: 'bg-amber-500/10 border-amber-500',
    accent: 'border-r-amber-500/20',
  },
  professionnel: {
    bubble: 'bg-sky-500/10 border-sky-500',
    accent: 'border-r-sky-500/20',
  },
}

const currentStyle = computed(() =>
  personalityConfig[currentTestimonial.value?.personality ?? 'professionnel']
)

const initials = computed(() => {
  const names = currentTestimonial.value?.name?.split(' ') ?? []
  return names.map(n => n[0]).join('').toUpperCase().slice(0, 2)
})
</script>

<template>
  <div
    class="dialogue-pnj focus:outline-none"
    tabindex="0"
    role="article"
    :aria-label="currentTestimonial?.text"
    @keydown="handleKeydown"
  >
    <Transition name="dialogue" mode="out-in">
      <div :key="currentIndex" class="flex flex-col md:flex-row items-start gap-6">
        <!-- Avatar PNJ -->
        <div class="flex-shrink-0 self-center md:self-start">
          <div
            class="w-24 h-24 md:w-32 md:h-32 rounded-full overflow-hidden ring-4 ring-sky-dark shadow-lg shadow-sky-500/10"
          >
            <img
              v-if="currentTestimonial?.avatar"
              :src="currentTestimonial.avatar"
              :alt="currentTestimonial.name"
              class="w-full h-full object-cover"
            >
            <div
              v-else
              class="w-full h-full flex items-center justify-center bg-sky-dark text-2xl font-bold text-sky-400"
            >
              {{ initials }}
            </div>
          </div>

          <!-- Info PNJ sous l'avatar -->
          <div class="mt-3 text-center">
            <p class="font-semibold text-white text-sm">
              {{ currentTestimonial?.name }}
            </p>
            <p class="text-xs text-gray-400">
              {{ currentTestimonial?.role }}
            </p>
            <p v-if="currentTestimonial?.company" class="text-xs text-gray-500">
              @ {{ currentTestimonial.company }}
            </p>
          </div>
        </div>

        <!-- Bulle de dialogue -->
        <div class="flex-1 w-full">
          <div
            class="relative p-6 rounded-xl border-l-4 cursor-pointer transition-all hover:shadow-lg"
            :class="currentStyle.bubble"
            aria-live="polite"
            @click="handleBubbleClick"
          >
            <!-- Triangle de la bulle (desktop) -->
            <div
              class="hidden md:block absolute left-0 top-10 w-0 h-0 -translate-x-full border-t-8 border-r-8 border-b-8 border-transparent"
              :class="currentStyle.accent"
            />

            <!-- Texte avec typewriter -->
            <p
              class="font-narrative text-lg md:text-xl leading-relaxed text-gray-200 min-h-[5rem]"
              :class="{ 'italic': currentTestimonial?.personality === 'sarcastique' }"
            >
              "{{ displayedText }}"<span
                v-if="isTyping"
                class="inline-block w-0.5 h-5 bg-sky-400 ml-1 animate-blink align-middle"
              />
            </p>

            <!-- Indicateur pour continuer -->
            <Transition name="fade">
              <div
                v-if="!isTyping"
                class="mt-4 text-sm text-gray-500 animate-pulse select-none"
              >
                {{ t('testimonials.click_to_continue') }}
              </div>
            </Transition>
          </div>

          <!-- Lien projet si existant -->
          <NuxtLink
            v-if="currentTestimonial?.project"
            :to="`/projets/${currentTestimonial.project.slug}`"
            class="inline-flex items-center gap-2 mt-4 text-sm text-sky-400 hover:text-sky-300 transition-colors"
          >
            <span>📁</span>
            <span>{{ currentTestimonial.project.title }}</span>
            <span class="transition-transform group-hover:translate-x-1">→</span>
          </NuxtLink>
        </div>
      </div>
    </Transition>

    <!-- Navigation et indicateur -->
    <div class="flex items-center justify-between mt-8 pt-6 border-t border-sky-dark/50">
      <!-- Bouton précédent -->
      <button
        type="button"
        :disabled="currentIndex === 0"
        class="px-4 py-2 text-gray-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
        @click.stop="goToPrevious"
      >
        ← {{ t('testimonials.previous') }}
      </button>

      <!-- Indicateur position -->
      <div class="flex items-center gap-2">
        <button
          v-for="(_, idx) in testimonials"
          :key="idx"
          type="button"
          class="w-2.5 h-2.5 rounded-full transition-all"
          :class="idx === currentIndex ? 'bg-sky-400 scale-125' : 'bg-sky-dark hover:bg-sky-dark/70'"
          :aria-label="`${t('testimonials.go_to')} ${idx + 1}`"
          @click.stop="currentIndex = idx"
        />
      </div>

      <!-- Bouton suivant -->
      <button
        type="button"
        class="px-4 py-2 text-gray-400 hover:text-white transition-colors"
        @click.stop="goToNext"
      >
        {{ currentIndex === totalCount - 1 ? t('testimonials.finish') : t('testimonials.next') }} →
      </button>
    </div>

    <!-- Instructions clavier -->
    <p class="mt-4 text-xs text-gray-600 text-center">
      {{ t('testimonials.keyboard_hint') }}
    </p>
  </div>
</template>

<style scoped>
.animate-blink {
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.dialogue-enter-active,
.dialogue-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.dialogue-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.dialogue-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@media (prefers-reduced-motion: reduce) {
  .animate-blink {
    animation: none;
    opacity: 1;
  }

  .dialogue-enter-active,
  .dialogue-leave-active,
  .fade-enter-active,
  .fade-leave-active {
    transition: none;
  }
}
</style>
