<template>
  <Image v-bind="imageProps" v-if="gameStore.getLoadedAsset(texture)" />
</template>

<script lang="ts" setup>
import type { MapCharacter, Sprite as SpriteT } from '@/application/types'
import { loadSpriteTextures } from '@/services/textureService'
import { useGameStore } from '@/stores/gameStore'
import { Image, useScene } from 'phavuer'
import { computed } from 'vue'

const props = defineProps<{
  mapCharacter: MapCharacter
  currentX: number
  currentY: number
}>()

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

const texture = computed(() => {
  const { rotation, characterHair } = props.mapCharacter.character
  const spriteId = characterHair?.sprite?.id
  const direction = [0, 6].includes(rotation) ? 'back' : 'front'

  return `${spriteId}-${direction}`
})

const isFlippedX = computed(() => [6, 4].includes(props.mapCharacter.character.rotation ?? 0))

const imageProps = computed(() => {
  // Get the current sprite action based on direction
  const direction = [0, 6].includes(props.mapCharacter.character.rotation ?? 0) ? 'back' : 'front'
  const spriteAction = props.mapCharacter.character.characterHair?.sprite?.spriteActions?.find((spriteAction) => spriteAction.action === direction)

  return {
    depth: 1,
    originX: Number(spriteAction?.originX) ?? 0,
    originY: Number(spriteAction?.originY) ?? 0,
    flipX: isFlippedX.value,
    texture: texture.value
    // y: props.mapCharacter.isMoving ? Math.floor(Date.now() / 250) % 2 : 0
  }
})

loadSpriteTextures(scene, props.mapCharacter.character.characterHair?.sprite as SpriteT)
  .then(() => {})
  .catch((error) => {
    console.error('Error loading texture:', error)
  })
</script>
