'use client'

import Lottie, { type LottieRefCurrentProps } from 'lottie-react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { isLottieAnimationData } from '@/lib/media/mediaGuards'

type GiftLottieOnceProps = {
    url: string
    onDone: () => void
    className?: string
}

/** 一次性 Lottie：播完即 destroy，避免長期佔用記憶體 */
export default function GiftLottieOnce({ url, onDone, className }: GiftLottieOnceProps) {
    const lottieRef = useRef<LottieRefCurrentProps>(null)
    const onDoneRef = useRef(onDone)
    const finishedRef = useRef(false)
    const [animationData, setAnimationData] = useState<object | null>(null)

    onDoneRef.current = onDone

    const destroyAndFinish = useCallback(() => {
        if (finishedRef.current) return
        finishedRef.current = true
        try {
            lottieRef.current?.destroy()
        } catch {
            /* ignore */
        }
        setAnimationData(null)
        onDoneRef.current()
    }, [])

    useEffect(() => {
        finishedRef.current = false
        setAnimationData(null)

        let cancelled = false
        fetch(url)
            .then((res) => (res.ok ? res.json() : null))
            .then((json) => {
                if (cancelled || finishedRef.current) return
                if (!isLottieAnimationData(json)) {
                    destroyAndFinish()
                    return
                }
                setAnimationData(json)
            })
            .catch(() => {
                if (!cancelled) destroyAndFinish()
            })

        return () => {
            cancelled = true
            try {
                lottieRef.current?.destroy()
            } catch {
                /* ignore */
            }
            setAnimationData(null)
        }
    }, [url, destroyAndFinish])

    if (!animationData) {
        return <div className={className} aria-hidden />
    }

    return (
        <Lottie
            lottieRef={lottieRef}
            animationData={animationData}
            loop={false}
            autoplay
            className={className ?? 'h-full w-full'}
            onComplete={destroyAndFinish}
        />
    )
}
