<template>
  <div class="flex flex-col-reverse mt-16">
    <molecule-box v-for="compilation in dataStore.getAllCompilations.slice().reverse()" :key="compilation.id"
      :compilation="compilation" :BoxState="boxStates[compilation.id]" @click="() => openCompilation(compilation.id)"
      :class="boxStates[compilation.id]" />
  </div>
</template>

<script setup lang="ts">
import { useDataStore } from '~/store/data'
import type { BoxState } from '~~/types/types'
import { useRouter } from 'vue-router'

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

function openCompilation(id: string) {
  if (boxStates.value[id] === 'list') {
    for (const key in boxStates.value) {
      boxStates.value[key] = (key === id) ? 'selected' : 'hide'
    }
  }
}

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>
