"use client"

import { useEffect, useRef } from "react"

interface LottiePlayerProps {
  src: string
  className?: string
  loop?: boolean
  autoplay?: boolean
  style?: React.CSSProperties
}

export default function LottiePlayer({ src, className, loop = true, autoplay = true, style }: LottiePlayerProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const animRef = useRef<ReturnType<typeof import("lottie-web").default.loadAnimation> | null>(null)

  useEffect(() => {
    let cancelled = false

    import("lottie-web").then((lottie) => {
      if (cancelled || !containerRef.current) return
      animRef.current = lottie.default.loadAnimation({
        container: containerRef.current,
        renderer: "svg",
        loop,
        autoplay,
        path: src,
      })
    })

    return () => {
      cancelled = true
      animRef.current?.destroy()
    }
  }, [src, loop, autoplay])

  return <div ref={containerRef} className={className} style={style} />
}
