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

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { Image, useScene, refObj } from 'phavuer'
import type { Sprite as SpriteT, ZoneCharacter } from '@/types'
import { loadSpriteTextures } from '@/composables/gameComposable'
import { useGameStore } from '@/stores/gameStore'

const props = defineProps<{
  zoneCharacter: ZoneCharacter
  currentX: number
  currentY: number
}>()

const gameStore = useGameStore()
const scene = useScene()
const hairImage = refObj<Phaser.GameObjects.Image>()
const baseY = ref(0)

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

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

const isFlippedX = computed(() => [6, 4].includes(props.zoneCharacter.character.rotation ?? 0))
const imageProps = computed(() => ({
  depth: 1,
  originY: [0, 6].includes(props.zoneCharacter.character.rotation ?? 0) ? 4.30 : 5.30,
  flipX: isFlippedX.value,
  texture: texture.value
}))

// Watch for movement changes and animate hair
watch(() => props.zoneCharacter.isMoving, (isMoving) => {
  if (!hairImage.value) return

  if (isMoving) {
    // Start bounce animation
    scene.tweens.add({
      targets: hairImage.value,
      x: { from: 0, to: 1 },
      y: { from: 0, to: 1},
      duration: 500,
      yoyo: false,
      repeat: -1,
      ease: 'Linear'
    })
  } else {
    // Stop all tweens on this hair image
    scene.tweens.killTweensOf(hairImage.value)
    // Reset position
    hairImage.value.setY(0)
  }
})

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