<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-6xl mx-auto px-4">
      <!-- Navigation de retour -->
      <div class="mb-6">
        <button
          @click="$router.go(-1)"
          class="flex items-center hover:text-black transition-colors" style="color: #6b7280"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
          </svg>
          Retour à la liste
        </button>
      </div>

      <!-- Titre du texte -->
      <div v-if="textData" class="text-center mb-8">
        <h1 class="text-4xl font-bold text-black mb-2">
          {{ textData.metadata.titre_fr }}
        </h1>
        <h2 class="text-2xl" style="color: #6b7280">
          {{ textData.metadata.titre_pt }}
        </h2>
      </div>

      <!-- Lecteur audio -->
      <AudioPlayer
        v-if="textData && textData.hasAudio"
        :audio-src="audioSrc"
        class="mb-8"
      />

      <!-- Affichage du texte -->
      <TextDisplay
        v-if="textData"
        :patois-text="textData.patoisText"
        :french-text="textData.frenchText"
        :metadata="textData.metadata"
      />

      <!-- Actions supplémentaires -->
      <div v-if="textData" class="mt-8 flex justify-center space-x-4">
        <button
          @click="goToRandomText"
          class="btn-secondary"
        >
          Texte au hasard
        </button>
        <button
          @click="shareText"
          class="btn-secondary"
        >
          Partager
        </button>
      </div>

      <!-- Chargement -->
      <div v-if="loading" class="flex justify-center items-center py-20">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-black"></div>
      </div>

      <!-- Erreur -->
      <div v-if="error" class="text-center py-20">
        <svg class="mx-auto h-12 w-12 text-red-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"/>
        </svg>
        <h3 class="text-lg font-medium text-gray-900 mb-2">Erreur de chargement</h3>
        <p class="text-gray-500 mb-4">{{ error }}</p>
        <button
          @click="loadText"
          class="btn-primary"
        >
          Réessayer
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { textService } from '../services/textService.js'
import AudioPlayer from '../components/AudioPlayer.vue'
import TextDisplay from '../components/TextDisplay.vue'

export default {
  name: 'TextReader',
  components: {
    AudioPlayer,
    TextDisplay
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()

    const textData = ref(null)
    const loading = ref(true)
    const error = ref(null)

    const audioSrc = computed(() => {
      if (!textData.value || !textData.value.hasAudio) return null
      // Le chemin vers le fichier audio sera construit dynamiquement
      return `/texts/${props.id}/audio.mp3`
    })

    const loadText = async () => {
      loading.value = true
      error.value = null

      try {
        const text = await textService.loadText(props.id)
        textData.value = text
      } catch (err) {
        error.value = err.message
        console.error('Erreur lors du chargement du texte:', err)
      } finally {
        loading.value = false
      }
    }

    const goToRandomText = async () => {
      try {
        const randomText = await textService.getRandomText()
        router.push(`/texte/${randomText.id}`)
      } catch (err) {
        router.push('/au-hasard')
      }
    }

    const shareText = async () => {
      const url = window.location.href
      const title = textData.value?.metadata?.titre_fr || 'Texte en patois'

      if (navigator.share) {
        try {
          await navigator.share({
            title: title,
            url: url
          })
        } catch (err) {
          // Fallback pour la copie dans le presse-papier
          copyToClipboard(url)
        }
      } else {
        copyToClipboard(url)
      }
    }

    const copyToClipboard = async (text) => {
      try {
        await navigator.clipboard.writeText(text)
        // Ici vous pourriez ajouter une notification de succès
      } catch (err) {
        console.error('Erreur lors de la copie:', err)
      }
    }

    // Recharger le texte quand l'ID change
    watch(() => props.id, () => {
      loadText()
    }, { immediate: true })

    onMounted(() => {
      loadText()
    })

    return {
      textData,
      loading,
      error,
      audioSrc,
      loadText,
      goToRandomText,
      shareText
    }
  }
}
</script>
