<template>
  <div class="flex flex-col-reverse mt-16" :class="!!playerStore.currentTrack ? 'mb-36' : 'mb-16'">
    <box v-for="(box, i) in dataStore.boxes.slice()" :key="box.id" :tabindex="dataStore.boxes.length - i" :box="box"
      @click="onBoxClick(box)" class="text-center" :class="box.state" :id="box.id">
      <button @click.stop="playSelectedBox(box)" v-if="box.state === 'box-selected'"
        class="relative z-40 rounded-full size-24 bottom-1/2 text-4xl tex-bold text-esyellow backdrop-blur-sm bg-black/25">
        {{ !playerStore.isPaused && playerStore.currentTrack?.boxId === box.id ? 'I I' : '▶' }}
      </button>
      <deck :box="box" class="box-page" v-if="box.state === 'box-selected'" @click.stop />
    </box>
  </div>
</template>

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

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

function openBox(id: string) {
  uiStore.selectBox(id)
  // Scroll to the top smoothly
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

function onBoxClick(b: Box) {
  if (b.state !== 'box-selected') {
    openBox(b.id)
  }
}

function playSelectedBox(b: Box) {
  playerStore.playBox(b)
}

function KeyboardAction(e: KeyboardEvent) {
  switch (e.key) {
    case 'Escape':
      uiStore.closeBox()
      break;
    case 'ArrowUp':
      break;

    case 'Enter':
      if (document.activeElement?.id) {
        openBox(document.activeElement.id)
      }
      break;
    case 'ArrowDown':
      break;
    case 'ArrowLeft':
      break;
    case 'ArrowRight':
      break;
    default:
      break;
  }
}

onMounted(async () => {
  window.addEventListener('keydown', KeyboardAction)
})
</script>
