<template>
  <Debug />
  <Notifications />
  <BackgroundImageLoader />
  <GmPanel v-if="gameStore.character?.role === 'gm'" @open-map-editor="mapEditor.toggleActive" />
  <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 { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { useSoundComposable } from '@/composables/useSoundComposable'
import { useGameStore } from '@/stores/gameStore'
import { computed, watch } from 'vue'

const gameStore = useGameStore()

const mapEditor = useMapEditorComposable()
const { playSound } = useSoundComposable()

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 (mapEditor.active.value) return MapEditor
  return Game
})

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

// #209: Play sound when a button is pressed
addEventListener('click', (event) => {
  const classList = ['btn-cyan', 'btn-red', 'btn-indigo', 'btn-empty', 'btn-sound']
  const target = event.target as HTMLElement
  // console.log(target) // Uncomment to log the clicked element
  if (!classList.some((className) => target.classList.contains(className))) {
    return // Only play sound if the clicked element is a button
  }
  playSound('/assets/sounds/button-click.wav')
})

// 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>
