<template>
  <div>
    <NuxtRouteAnnouncer />
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>

<script setup>
import { useUiStore } from '~/store/ui'
import { usePlayerStore } from '~/store/player'
import { watch, computed } from 'vue'

const ui = useUiStore()
const player = usePlayerStore()
useHead({
  bodyAttrs: {
    class: 'bg-slate-100'
  }
})

const router = useRouter()
const route = useRoute()

watch(
  () => player.currentTrack?.id,
  (id) => {
    if (!id) {
      if (route.name === 'track-id') router.replace({ path: '/' })
      return
    }
    const currentParam = Number(
      Array.isArray(route.params.id) ? route.params.id[0] : route.params.id
    )
    if (route.name === 'track-id' && currentParam === id) return
    router.replace({ name: 'track-id', params: { id } })
  },
  { flush: 'post' }
)

// Keep URL in sync with selected box: /box/:id when a box is selected, back to / when none
const selectedBoxId = computed(() => ui.getSelectedBox?.id)
watch(
  () => selectedBoxId.value,
  (id) => {
    if (import.meta.client) {
      if (!id) {
        // Back to root path without navigation to preserve UI state/animations
        if (location.pathname.startsWith('/box/')) {
          history.replaceState(null, '', '/')
        }
        return
      }
      const currentId = location.pathname.startsWith('/box/')
        ? location.pathname.split('/').pop()
        : null
      if (currentId === id) return
      requestAnimationFrame(() => {
        history.replaceState(null, '', `/box/${id}`)
      })
    }
  },
  { flush: 'post' }
)
</script>

<style>
button,
input {
  @apply px-4 py-2 m-4 rounded-md text-center font-bold;
}

input[type='email'] {
  @apply bg-slate-900 text-esyellow;
}

img {
  user-drag: none;
  user-select: none;
}
</style>
