import { gsap } from 'gsap'
import { onMounted, onBeforeUnmount, watch, unref } from 'vue'

/**
 * Infinite up/down floating animation for an element.
 *
 * @param {Ref|HTMLElement} target - element or ref to animate
 * @param {Object} opts
 * @param {number} opts.y - distance to move up/down
 * @param {number} opts.duration - duration of one cycle (up or down)
 * @param {number} opts.delay - initial delay
 * @param {string} opts.ease - GSAP easing
 */
export default (
    target,
    { y = '-3%', duration = 2, delay = 0, ease = 'power1.inOut' } = {},
) => {
    let tl = null

    const start = () => {
        const el = unref(target)
        if (!el) return

        // Kill any previous timeline
        if (tl) tl.kill()

        // Create infinite yoyo animation
        tl = gsap.to(el, {
            y: y,
            duration,
            delay,
            ease,
            yoyo: true,
            repeat: -1,
        })
    }

    const stop = () => {
        if (tl) {
            tl.kill()
            tl = null
        }
    }

    onMounted(() => {
        // If the element is a ref, wait for it to appear
        watch(
            () => unref(target),
            (el) => {
                if (el) start()
            },
            { immediate: true },
        )
    })

    onBeforeUnmount(stop)

    return { start, stop }
}
