<script setup lang="ts">
const { t, locale } = useI18n()
const { api } = useApi()
const route = useRoute()

interface ExerciseDetail {
  id: number
  name: string
  body_part?: string | null
  category: string | null
  equipment: string | null
  target: string | null
  muscle_group: string | null
  secondary_muscles: string[]
  instructions: string[]
  image_url: string | null
  gif_url: string | null
  attribution: string | null
}

// L'API enveloppe la resource dans { data: {...} } → on déballe.
const { data: ex, pending } = await useAsyncData(
  `exercise-${route.params.id}`,
  () => api<{ data: ExerciseDetail }>(`/api/exercises/${route.params.id}`, { query: { locale: locale.value } })
    .then(r => r.data),
  { watch: [() => route.params.id, locale] }
)
</script>

<template>
  <div class="space-y-5">
    <UButton to="/exercises" icon="i-lucide-arrow-left" color="neutral" variant="ghost" :label="t('common.back')" />

    <div v-if="pending && !ex" class="flex justify-center py-16"><SfLogo :size="56" loader /></div>

    <template v-else-if="ex">
      <div class="rounded-2xl overflow-hidden bg-zinc-100 dark:bg-zinc-800 aspect-square max-w-sm mx-auto">
        <img v-if="ex.gif_url || ex.image_url" :src="ex.gif_url || ex.image_url || ''" :alt="ex.name" class="w-full h-full object-cover">
      </div>

      <div>
        <h1 class="text-2xl font-black tracking-tight capitalize">{{ ex.name }}</h1>
        <div class="flex flex-wrap gap-2 mt-2">
          <UBadge v-if="ex.target" color="primary" variant="soft" class="capitalize">{{ ex.target }}</UBadge>
          <UBadge v-if="ex.equipment" color="neutral" variant="soft" class="capitalize">{{ ex.equipment }}</UBadge>
          <UBadge v-if="ex.body_part || ex.category" color="neutral" variant="outline" class="capitalize">{{ ex.body_part || ex.category }}</UBadge>
        </div>
      </div>

      <div v-if="ex.secondary_muscles?.length">
        <h2 class="text-sm font-semibold text-zinc-500 mb-1">{{ t('exercises.secondaryMuscles') }}</h2>
        <p class="text-sm capitalize">{{ ex.secondary_muscles.join(', ') }}</p>
      </div>

      <div v-if="ex.instructions?.length">
        <h2 class="text-sm font-semibold text-zinc-500 mb-2">{{ t('exercises.instructions') }}</h2>
        <ol class="space-y-2">
          <li v-for="(step, i) in ex.instructions" :key="i" class="flex gap-3">
            <span class="shrink-0 size-6 rounded-full sf-flame-bg text-white text-xs font-bold flex items-center justify-center">{{ i + 1 }}</span>
            <span class="text-sm">{{ step }}</span>
          </li>
        </ol>
      </div>

      <p v-if="ex.attribution" class="text-xs text-zinc-400 pt-4">{{ ex.attribution }}</p>
    </template>
  </div>
</template>
