<script setup lang="ts">
import lottie, { type AnimationItem } from 'lottie-web'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'

const props = withDefaults(
  defineProps<{
    src?: string
    loop?: boolean
    sizeClass?: string
  }>(),
  {
    src: '/lottie/heart.json',
    loop: true,
    sizeClass: 'h-20 w-20',
  },
)

const host = ref<HTMLDivElement | null>(null)
let anim: AnimationItem | null = null

async function tryLoad() {
  if (!host.value || !props.src) return
  try {
    const res = await fetch(props.src, { method: 'GET' })
    if (!res.ok) return
    const data = await res.json()
    anim?.destroy()
    anim = lottie.loadAnimation({
      container: host.value,
      renderer: 'svg',
      loop: props.loop,
      autoplay: true,
      animationData: data,
    })
  } catch {
    /* optional asset */
  }
}

onMounted(() => {
  void tryLoad()
})

watch(
  () => props.src,
  () => {
    void tryLoad()
  },
)

onBeforeUnmount(() => {
  anim?.destroy()
  anim = null
})
</script>

<template>
  <div
    ref="host"
    class="[&_svg]:!h-full [&_svg]:!w-full"
    :class="sizeClass"
    aria-hidden="true"
  />
</template>
