import { useIntersectionObserver } from '@vueuse/core'

export default {
    install: (app) => {
        app.directive('intersect', {
            mounted(el, binding) {
                const { stop } = useIntersectionObserver(
                    el,
                    ([{ isIntersecting }]) => {
                        binding.value?.callback?.(isIntersecting)

                        if (isIntersecting) {
                            el.classList.add('intersected')

                            if (binding.arg === 'once') {
                                stop()
                            }
                        } else {
                            el.classList.remove('intersected')
                        }
                    },
                    {
                        threshold: binding.value?.threshold || 0,
                        rootMargin: binding.value?.rootMargin || '0px',
                    },
                )
            },
        })
    },
}
