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

interface ExerciseRow { id: number, name: string, slug: string, body_part: string | null, equipment: string | null, target: string | null, image_url: string | null }
interface Facet { value: string, label: string }
interface Facets { body_parts: Facet[], equipments: Facet[], targets: Facet[], categories: Facet[] }
interface Paginated { data: ExerciseRow[], meta: { current_page: number, last_page: number, total: number } }

const search = ref('')
const bodyPart = ref<string | undefined>()
const equipment = ref<string | undefined>()
const myGear = ref(false)
const page = ref(1)

const { data: facets } = await useAsyncData('ex-facets', () => api<Facets>('/api/exercises/facets', { query: { locale: locale.value } }), { lazy: true, watch: [locale] })

// Matériel possédé (config profil) → filtre "mon matos" (plusieurs équipements, envoyés en CSV).
const myEquipmentCsv = computed(() => (auth.user?.available_equipment ?? []).join(','))
const hasMyGear = computed(() => myEquipmentCsv.value.length > 0)
const equipmentParam = computed(() => (myGear.value && hasMyGear.value) ? myEquipmentCsv.value : (equipment.value || undefined))

const query = computed(() => ({ search: search.value || undefined, body_part: bodyPart.value || undefined, equipment: equipmentParam.value, page: page.value, locale: locale.value }))
const { data, pending } = await useAsyncData<Paginated>(
  'exercises',
  () => api<Paginated>('/api/exercises', { query: query.value }),
  { watch: [query], lazy: true }
)

watch([search, bodyPart, equipment, myGear], () => { page.value = 1 })

const bodyPartOptions = computed(() => [
  { label: t('exercises.all'), value: undefined },
  ...(facets.value?.body_parts ?? []).map(b => ({ label: b.label, value: b.value }))
])
const equipmentOptions = computed(() => [
  { label: t('exercises.all'), value: undefined },
  ...(facets.value?.equipments ?? []).map(e => ({ label: e.label, value: e.value }))
])
</script>

<template>
  <div class="space-y-4">
    <h1 class="text-2xl font-black tracking-tight">{{ t('exercises.title') }}</h1>

    <div class="space-y-2">
      <div class="flex gap-2">
        <UInput
          v-model="search"
          icon="i-lucide-search"
          :placeholder="t('exercises.search')"
          size="lg"
          class="flex-1"
        />
        <USelectMenu
          v-model="bodyPart"
          :items="bodyPartOptions"
          value-key="value"
          :placeholder="t('exercises.bodyPart')"
          size="lg"
          class="w-36"
        />
      </div>
      <div class="flex gap-2 items-center">
        <USelectMenu
          v-model="equipment"
          :items="equipmentOptions"
          value-key="value"
          :placeholder="t('exercises.equipment')"
          size="lg"
          class="flex-1"
          :disabled="myGear && hasMyGear"
        />
        <UButton
          v-if="hasMyGear"
          :color="myGear ? 'primary' : 'neutral'"
          :variant="myGear ? 'solid' : 'subtle'"
          size="lg"
          icon="i-lucide-dumbbell"
          :label="t('exercises.myGear')"
          @click="myGear = !myGear"
        />
      </div>
    </div>

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

    <p v-else-if="!data?.data.length" class="text-center text-zinc-400 py-16">{{ t('exercises.noResults') }}</p>

    <div v-else class="grid grid-cols-2 sm:grid-cols-3 gap-3">
      <NuxtLink
        v-for="ex in data.data"
        :key="ex.id"
        :to="`/exercises/${ex.id}`"
        class="group rounded-xl overflow-hidden border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 hover:border-flame-400 transition-colors"
      >
        <div class="aspect-square bg-zinc-100 dark:bg-zinc-800 overflow-hidden">
          <img
            v-if="ex.image_url"
            :src="ex.image_url"
            :alt="ex.name"
            loading="lazy"
            class="w-full h-full object-cover group-hover:scale-105 transition-transform"
          >
        </div>
        <div class="p-2">
          <p class="text-sm font-semibold capitalize truncate">{{ ex.name }}</p>
          <p class="text-xs text-zinc-500 capitalize truncate">{{ ex.target }}</p>
        </div>
      </NuxtLink>
    </div>

    <div v-if="data && data.meta.last_page > 1" class="flex justify-center pt-2">
      <UPagination
        v-model:page="page"
        :total="data.meta.total"
        :items-per-page="Math.ceil(data.meta.total / data.meta.last_page)"
      />
    </div>
  </div>
</template>
