<template>
  <div class="relative w-full">
    <div
      ref="deck"
      class="deck flex flex-wrap justify-center gap-4"
      :class="{ 'px-16 pb-36': playerStore.currentTrack }"
    >
      <card
        v-for="(track, i) in tracks"
        :key="track.id"
        :track="track"
        tabindex="i"
        :tab-index="i"
        :is-face-up="isCardRevealed(track.id)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useDataStore } from '~/store/data'
import { useCardStore } from '~/store/card'
import { usePlayerStore } from '~/store/player'
import { useUiStore } from '~/store/ui'
import type { Box } from '~~/types/types'

const props = defineProps<{
  box: Box
}>()

const cardStore = useCardStore()
const dataStore = useDataStore()
const playerStore = usePlayerStore()
const uiStore = useUiStore()

const deck = ref<HTMLElement | null>(null)
const tracks = computed(() => dataStore.getTracksByboxId(props.box.id))

const isCardRevealed = (trackId: number) => cardStore.isCardRevealed(trackId)

const handleClickOutside = (event: MouseEvent) => {
  // Vérifier si le clic provient d'un bouton de lecture
  const target = event.target as HTMLElement
  const isPlayButton = target.closest('.play-button')

  // Ne pas fermer si le clic provient d'un bouton de lecture
  if (isPlayButton) return

  // Vérifier si le clic est en dehors du deck
  if (deck.value && !deck.value.contains(target)) {
    uiStore.closeBox()
  }
}

onMounted(() => {
  // Ajouter le gestionnaire de clic à l'extérieur
  document.addEventListener('mousedown', handleClickOutside)
})

onUnmounted(() => {
  // Nettoyer le gestionnaire d'événement
  document.removeEventListener('mousedown', handleClickOutside)
})
</script>
