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

<script setup lang="ts">
import GmPanel from '@/components/gameMaster/GmPanel.vue'
import Characters from '@/components/screens/Characters.vue'
import Game from '@/components/screens/Game.vue'
import Loading from '@/components/screens/Loading.vue'
import Login from '@/components/screens/Login.vue'
import MapEditor from '@/components/screens/MapEditor.vue'
import BackgroundImageLoader from '@/components/utilities/BackgroundImageLoader.vue'
import Debug from '@/components/utilities/Debug.vue'
import Notifications from '@/components/utilities/Notifications.vue'
import { useGameStore } from '@/stores/gameStore'
import { useMapEditorStore } from '@/stores/mapEditorStore'
import { computed, onMounted, onUnmounted, watch } from 'vue'

const gameStore = useGameStore()
const mapEditorStore = useMapEditorStore()

const currentScreen = computed(() => {
  if (!gameStore.game.isLoaded) return Loading
  if (!gameStore.connection) return Login
  if (!gameStore.token) return Login
  if (!gameStore.character) return Characters
  if (mapEditorStore.active) return MapEditor
  return Game
})

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

// #209: Play sound when a button is pressed
/**
 * @TODO: Not all button-like elements will actually be a button, so we need to find a better way to do this
 */
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>
