import gsap from 'gsap'

export default (timelineSetup = () => {}) => {
    const timelines = new WeakMap()
    const getTimeline = (el) => {
        if (!timelines.has(el)) {
            const tl = gsap.timeline({ paused: true })

            timelines.set(el, tl)
        }
        return timelines.get(el)
    }
    const onEnter = (el, done) => {
        const tl = getTimeline(el)

        tl.clear()
        timelineSetup?.(tl, el)

        tl.eventCallback('onReverseComplete', null)
        tl.eventCallback('onComplete', done)
        tl.play()
    }
    const onLeave = (el, done) => {
        el.style.pointerEvents = 'none'

        const tl = getTimeline(el)

        tl.eventCallback('onComplete', null)
        tl.eventCallback('onReverseComplete', done)
        tl.reverse()
    }

    return {
        onEnter,
        onLeave,
    }
}
