<template>
  <div ref="lottieContainer" class="lottie-container" />
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";

// Use dynamic import to ensure lottie only loads in browser
const lottie = import.meta.client
  ? await import("lottie-web").then((m) => m.default)
  : null;

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  loop: {
    type: Boolean,
    default: true,
  },
  autoplay: {
    type: Boolean,
    default: true,
  },
});

const lottieContainer = ref(null);
let lottieInstance = null;

const loadAnimation = () => {
  // Safety check: only run on client and if container exists
  if (!import.meta.client || !lottieContainer.value) return;

  // Destroy any existing instance first
  if (lottieInstance) {
    lottieInstance.destroy();
  }

  try {
    lottieInstance = lottie.loadAnimation({
      container: lottieContainer.value,
      renderer: "svg",
      loop: props.loop,
      autoplay: props.autoplay,
      path: props.src,
    });

    // Handle loading errors
    lottieInstance.addEventListener("DOMLoaded", () => {
      // Animation loaded successfully
    });

    lottieInstance.addEventListener("error", () => {
      console.error("Error loading Lottie animation:", props.src);
    });
  } catch (error) {
    console.error("Failed to initialize Lottie animation:", error);
  }
};

// Initialize animation when component is mounted
onMounted(() => {
  if (import.meta.client) {
    loadAnimation();
  }
});

// Clean up resources when component is unmounted
onBeforeUnmount(() => {
  if (lottieInstance) {
    lottieInstance.destroy();
    lottieInstance = null;
  }
});

// Reload animation if src changes
watch(
  () => props.src,
  () => {
    loadAnimation();
  },
);
</script>

<style scoped>
.lottie-container {
  width: 100%;
  height: 100%;
}
</style>