<template>
  <div class="relative">
    <div
      class="sprite-container bg-gray-800"
      :style="{
        width: `${maxWidth}px`,
        height: `${maxHeight}px`,
        position: 'relative',
        overflow: 'hidden'
      }"
    >
      <img
        v-for="(sprite, index) in sprites"
        :key="index"
        :src="sprite.url"
        alt="Sprite"
        :style="{
          position: 'absolute',
          left: `${sprite.offset?.x || 0}px`,
          bottom: `${sprite.offset?.y || 0}px`,
          display: currentFrame === index ? 'block' : 'none'
        }"
        @load="updateContainerSize"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { SpriteImage } from '@/application/types'
import { onMounted, onUnmounted, ref, watch } from 'vue'

const props = defineProps<{
  sprites: SpriteImage[]
  frameRate: number
}>()

const currentFrame = ref(0)
const maxWidth = ref(250)
const maxHeight = ref(250)
let animationInterval: number | null = null

function updateContainerSize(event: Event) {
  const img = event.target as HTMLImageElement
  maxWidth.value = Math.max(maxWidth.value, img.naturalWidth)
  maxHeight.value = Math.max(maxHeight.value, img.naturalHeight)
}

function updateAnimation() {
  stopAnimation()
  if (props.frameRate <= 0 || props.sprites.length === 0) {
    currentFrame.value = 0
    return
  }

  animationInterval = window.setInterval(() => {
    currentFrame.value = (currentFrame.value + 1) % props.sprites.length
  }, 1000 / props.frameRate)
}

function stopAnimation() {
  if (animationInterval) {
    clearInterval(animationInterval)
    animationInterval = null
  }
}

watch(() => props.frameRate, updateAnimation, { immediate: true })
watch(() => props.sprites, updateAnimation, { immediate: true })

onMounted(() => {
  updateAnimation()
})

onUnmounted(() => {
  stopAnimation()
})
</script>

<style scoped>
.sprite-container {
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}
</style>
