<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'

interface Props {
  threshold?: number
  rootMargin?: string
  once?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  threshold: 0.1,
  rootMargin: '0px 0px -50px 0px',
  once: true,
})

const elementRef = ref<HTMLElement | null>(null)
const isRevealed = ref(false)
let observer: IntersectionObserver | null = null

onMounted(() => {
  if (!elementRef.value) return
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          isRevealed.value = true
          if (props.once && observer) {
            observer.unobserve(entry.target)
          }
        } else if (!props.once) {
          isRevealed.value = false
        }
      })
    },
    { threshold: props.threshold, rootMargin: props.rootMargin }
  )
  observer.observe(elementRef.value)
})

onUnmounted(() => {
  observer?.disconnect()
})
</script>

<template>
  <div
    ref="elementRef"
    class="scroll-reveal"
    :class="{ revealed: isRevealed }"
  >
    <slot :revealed="isRevealed" />
  </div>
</template>
