<template>
  <div class="flex justify-center items-center h-dvh relative">
    <Game :config="gameConfig" @create="createGame">
      <Scene name="main" @preload="preloadScene">
        <Menu />
        <Hud />
        <Hotkeys />
        <Clock />
        <Map />
        <Chat />
        <ExpBar />

        <CharacterProfile />
      </Scene>
    </Game>
  </div>
</template>

<script setup lang="ts">
import config from '@/application/config'
import 'phaser'
import CharacterProfile from '@/components/game/gui/CharacterProfile.vue'
import Chat from '@/components/game/gui/Chat.vue'
import Clock from '@/components/game/gui/Clock.vue'
import ExpBar from '@/components/game/gui/ExpBar.vue'
import Hotkeys from '@/components/game/gui/Hotkeys.vue'
import Hud from '@/components/game/gui/Hud.vue'
import Menu from '@/components/game/gui/Menu.vue'
import Map from '@/components/game/map/Map.vue'
import { useSoundComposable } from '@/composables/useSoundComposable'
import { useGameStore } from '@/stores/gameStore'
import { Game, Scene } from 'phavuer'
import { onMounted } from 'vue'

const gameStore = useGameStore()
const { playSound, stopSound } = useSoundComposable()

const gameConfig = {
  name: config.name,
  width: window.innerWidth,
  height: window.innerHeight,
  type: Phaser.AUTO, // AUTO, CANVAS, WEBGL, HEADLESS
  resolution: 5,
  input: {
    windowEvents: false
  }
}

const createGame = (game: Phaser.Game) => {
  // Resize the game when the window is resized
  addEventListener('resize', () => {
    game.scale.resize(window.innerWidth, window.innerHeight)
  })

  // We don't support canvas mode, only WebGL
  if (game.renderer.type === Phaser.CANVAS) {
    gameStore.addNotification({
      title: 'Warning',
      message: 'Your browser does not support WebGL. Please use a modern browser like Chrome, Firefox, or Edge.'
    })
    gameStore.disconnectSocket()
  }

  playSound('/assets/sounds/connect.wav')
}

function preloadScene(scene: Phaser.Scene) {
  // Load the base assets into the Phaser scene
  scene.load.image('blank_tile', '/assets/map/blank_tile.png')
  scene.load.image('waypoint', '/assets/waypoint.png')
}

onMounted(() => {
  stopSound('/assets/music/intro.mp3')
})
</script>