<template>
  <Notifications />
  <BackgroundImageLoader />
  <GmPanel v-if="gameStore.character?.role === 'gm'" />
  <component :is="currentScreen" />
</template>

<script setup lang="ts">
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import Notifications from '@/components/utilities/Notifications.vue'
import BackgroundImageLoader from '@/components/utilities/BackgroundImageLoader.vue'
import GmPanel from '@/components/gameMaster/GmPanel.vue'
import Login from '@/components/screens/Login.vue'
import Characters from '@/components/screens/Characters.vue'
import Game from '@/components/screens/Game.vue'
import ZoneEditor from '@/components/screens/ZoneEditor.vue'
import { computed, watch } from 'vue'

const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()

const currentScreen = computed(() => {
  if (!gameStore.connection) return Login
  if (!gameStore.token) return Login
  if (!gameStore.character) return Characters
  if (zoneEditorStore.active) return ZoneEditor
  return Game
})

// Watch zoneEditorStore.active and empty gameStore.game.loadedAssets
watch(
  () => zoneEditorStore.active,
  () => {
    gameStore.game.loadedAssets = []
  }
)

// #209: Play sound when a button is pressed
addEventListener('click', (event) => {
  if (!(event.target instanceof HTMLButtonElement)) {
    return
  }
  const audio = new Audio('/assets/music/click-btn.mp3')
  audio.play()
})

// Watch for "G" key press and toggle the gm panel
addEventListener('keydown', (event) => {
  if (gameStore.character?.role !== 'gm') return // Only allow toggling the gm panel if the character is a gm

  // Check if no input is active or focus is on an input
  if (event.repeat || event.isComposing || event.defaultPrevented || document.activeElement?.tagName.toUpperCase() === 'INPUT' || document.activeElement?.tagName.toUpperCase() === 'TEXTAREA') return

  if (event.key === 'G') {
    gameStore.toggleGmPanel()
  }
})
</script>
