<template>
  <Controls v-if="tileLayer" :layer="tileLayer" :depth="0" />
</template>

<script setup lang="ts">
import config from '@/application/config'
import type { Map as MapT, UUID } from '@/application/types'
import { unduplicateArray } from '@/application/utilities'
import Controls from '@/components/utilities/Controls.vue'
import { loadMapTilesIntoScene, setLayerTiles } from '@/composables/mapComposable'
import { MapStorage } from '@/storage/storages'
import { useMapStore } from '@/stores/mapStore'
import { useScene } from 'phavuer'
import { onBeforeUnmount, shallowRef } from 'vue'

import Tileset = Phaser.Tilemaps.Tileset

const emit = defineEmits(['tileMap:create'])
const scene = useScene()
const mapStore = useMapStore()
const mapStorage = new MapStorage()

const tileMap = shallowRef<Phaser.Tilemaps.Tilemap>()
const tileLayer = shallowRef<Phaser.Tilemaps.TilemapLayer>()

function createTileMap(map: MapT) {
  const mapConfig = new Phaser.Tilemaps.MapData({
    width: map.width,
    height: map.height,
    tileWidth: config.tile_size.width,
    tileHeight: config.tile_size.height,
    orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
    format: Phaser.Tilemaps.Formats.ARRAY_2D
  })

  const newTileMap = new Phaser.Tilemaps.Tilemap(scene, mapConfig)
  emit('tileMap:create', newTileMap)
  return newTileMap
}

function createTileLayer(currentTileMap: Phaser.Tilemaps.Tilemap, mapData: any) {
  const tilesArray = unduplicateArray(mapData?.tiles.flat())

  const tilesetImages = tilesArray.map((tile: string, index: number) => {
    return currentTileMap.addTilesetImage(tile, tile, config.tile_size.width, config.tile_size.height, 1, 2, index + 1, { x: 0, y: -config.tile_size.height })
  })

  // Add blank tile
  tilesetImages.push(currentTileMap.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.width, config.tile_size.height, 1, 2, 0, { x: 0, y: -config.tile_size.height }))

  const layer = currentTileMap.createBlankLayer('tiles', tilesetImages as Tileset[], 0, config.tile_size.height) as Phaser.Tilemaps.TilemapLayer

  layer.setDepth(0)
  layer.setCullPadding(2, 2)
  return layer
}

loadMapTilesIntoScene(mapStore.mapId as UUID, scene)
  .then(() => mapStorage.get(mapStore.mapId))
  .then((mapData) => {
    if (!mapData || !mapData?.tiles) return
    tileMap.value = createTileMap(mapData)
    tileLayer.value = createTileLayer(tileMap.value, mapData)
    setLayerTiles(tileMap.value, tileLayer.value, mapData.tiles)
  })
  .catch((error) => console.error('Failed to initialize map:', error))

onBeforeUnmount(() => {
  if (!tileMap.value) return
  tileMap.value.destroyLayer('tiles')
  tileMap.value.removeAllLayers()
  tileMap.value.destroy()
})
</script>
