<template>
  <div class="flex flex-col-reverse mt-16">
    <box v-for="compilation in dataStore.getAllCompilations.slice()" :key="compilation.id" :compilation="compilation"
      :BoxState="boxStates[compilation.id]" @click="() => openCompilation(compilation.id)"
      :class="boxStates[compilation.id]" class="text-center">
      <button @click="playerStore.playCompilation(compilation.id)" v-if="boxStates[compilation.id] === 'selected'"
        class="relative z-40 rounded-full size-24 bottom-1/2 text-2xl">
        {{ !playerStore.isPaused && playerStore.currentTrack?.compilationId === compilation.id ? 'II' : '▶' }}
      </button>
      <deck :compilation="compilation" class="box-page" v-if="boxStates[compilation.id] === 'selected'" />
    </box>
  </div>
</template>

<script setup lang="ts">
import { useDataStore } from '~/store/data'
import type { BoxState } from '~~/types/types'
import { usePlayerStore } from '~/store/player'

const dataStore = useDataStore()
const boxStates = ref<Record<string, BoxState>>({})
const playerStore = usePlayerStore()

function openCompilation(id: string) {
  if (boxStates.value[id] === 'list') {
    for (const key in boxStates.value) {
      boxStates.value[key] = (key === id) ? 'selected' : 'hide'
    }
    // Scroll to the top smoothly
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });

    navigateTo(`/box/${id}`)
  }
}

function closeCompilation(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    for (const key in boxStates.value) {
      boxStates.value[key] = 'list'
    }
  }
}

onMounted(async () => {
  const dataStore = await useDataStore()
  await dataStore.loadData()

  dataStore.getAllCompilations.forEach(c => {
    if (!(c.id in boxStates.value)) boxStates.value[c.id] = 'hide'
  })

  window.addEventListener('keydown', closeCompilation)

  setTimeout(() => {
    dataStore.getAllCompilations.forEach(c => {
      boxStates.value[c.id] = 'list'
    })
  }, 333)
})
</script>
