<template>
  <Image v-if="isTextureLoaded" v-bind="imageProps" />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Image, useScene } from 'phavuer'
import { calculateIsometricDepth, loadZoneObjectTexture, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import type { ZoneObject } from '@/types'

const props = defineProps<{
  tilemap: Phaser.Tilemaps.Tilemap
  zoneObject: ZoneObject
}>()

const scene = useScene()
const isTextureLoaded = ref(false)

const imageProps = computed(() => ({
  depth: calculateIsometricDepth(props.zoneObject.positionX, props.zoneObject.positionY, props.zoneObject.object.frameWidth, props.zoneObject.object.frameHeight),
  x: tileToWorldX(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
  y: tileToWorldY(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
  flipX: props.zoneObject.isRotated,
  texture: props.zoneObject.object.id,
  originY: Number(props.zoneObject.object.originX),
  originX: Number(props.zoneObject.object.originY)
}))

loadZoneObjectTexture(scene, props.zoneObject.object.id, props.zoneObject.object.updatedAt)
  .then((loaded) => {
    isTextureLoaded.value = loaded
  })
  .catch((error) => {
    console.error('Error loading texture:', error)
  })
</script>
