<template>
  <Image v-if="gameStore.getLoadedAsset(props.zoneObject.object.id)" v-bind="imageProps" />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Image, useScene } from 'phavuer'
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import { loadTexture } from '@/composables/gameComposable'
import type { AssetDataT, ZoneObject } from '@/types'
import { useGameStore } from '@/stores/gameStore'

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

const gameStore = useGameStore()
const scene = useScene()

const imageProps = computed(() => ({
  alpha: props.movingZoneObject?.id === props.zoneObject.id ? 0.5 : 1,
  tint: props.selectedZoneObject?.id === props.zoneObject.id ? 0x00ff00 : 0xffffff,
  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)
}))

loadTexture(scene, {
  key: props.zoneObject.object.id,
  data: '/assets/objects/' + props.zoneObject.object.id + '.png',
  group: 'objects',
  updatedAt: props.zoneObject.object.updatedAt,
  frameWidth: props.zoneObject.object.frameWidth,
  frameHeight: props.zoneObject.object.frameHeight
} as AssetDataT).catch((error) => {
  console.error('Error loading texture:', error)
})
</script>
