<template>
  <div class="flex justify-center items-center h-dvh relative">
    <Game :config="gameConfig" @create="createGame">
      <Scene name="main" @preload="preloadScene" @create="createScene">
        <ZoneEditor :key="JSON.stringify(`${zoneEditorStore.zone?.id}_${zoneEditorStore.zone?.createdAt}_${zoneEditorStore.zone?.updatedAt ?? ''}`)" />
      </Scene>
    </Game>
  </div>
</template>

<script setup lang="ts">
import config from '@/config'
import 'phaser'
import { Game, Scene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import ZoneEditor from '@/components/gameMaster/zoneEditor/ZoneEditor.vue'
import AwaitLoaderPlugin from 'phaser3-rex-plugins/plugins/awaitloader-plugin'
import { loadTexture } from '@/composables/gameComposable'
import type { AssetDataT } from '@/types'

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

const gameConfig = {
  name: config.name,
  width: window.innerWidth,
  height: window.innerHeight,
  type: Phaser.AUTO, // AUTO, CANVAS, WEBGL, HEADLESS
  resolution: 5,
  plugins: {
    global: [
      {
        key: 'rexAwaitLoader',
        plugin: AwaitLoaderPlugin,
        start: true
      }
    ]
  }
}

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()
  }
}

const preloadScene = async (scene: Phaser.Scene) => {
  /**
   * Load the base assets into the Phaser scene
   */
  scene.load.image('BLOCK', '/assets/zone/bt_tile.png')
  scene.load.image('TELEPORT', '/assets/zone/tp_tile.png')
  scene.load.image('blank_tile', '/assets/zone/blank_tile.png')
  scene.load.image('waypoint', '/assets/waypoint.png')

  /**
   * Because Phaser can't load tiles after the scene with map in it is created,
   * we need to load and cache all the tiles first.
   * Then load them into the scene.
   */
  scene.load.rexAwait(async function (successCallback: any) {
    const tiles: AssetDataT[] = await fetch(config.server_endpoint + '/assets/list_tiles').then((response) => response.json())
    for await (const tile of tiles) {
      await loadTexture(scene, tile)
    }

    successCallback()
  })
}

const createScene = async (scene: Phaser.Scene) => {}
</script>
