<template>
    <div v-if="!root" class="lenis" ref="wrapper">
        <div ref="content">
            <slot />
        </div>
    </div>

    <slot v-else />
</template>

<script setup>
import Lenis from 'lenis'
import Tempus from 'tempus'
import { onBeforeUnmount, onMounted, provide, ref, shallowRef } from 'vue'

const { root, instance, options } = defineProps({
    root: {
        type: Boolean,
        default: () => false,
    },
    instance: { type: String },
    options: {
        type: Object,
        default: () => ({
            duration: 1.2,
        }),
    },
})

const lenis = shallowRef()
const wrapper = ref()
const content = ref()
const removeRaf = ref()

// Provide instance for useLenis composable
const instanceKey = `lenis${instance ? `-${instance}` : ''}`
provide(instanceKey, lenis)

// Initialize with Tempus
const initLenis = () => {
    if (lenis.value) return

    lenis.value = new Lenis({
        ...options,
        ...(!root
            ? {
                  wrapper: wrapper.value,
                  content: content.value,
                  eventsTarget: wrapper.value,
              }
            : {}),
    })

    removeRaf.value = Tempus.add((time) => {
        lenis.value.raf(time)
    })
}

onMounted(() => {
    if (!lenis.value) {
        initLenis()
    }
})
// Kill lenis before unmount
onBeforeUnmount(() => {
    lenis.value?.destroy()
    removeRaf.value?.()
})
</script>
