import type { Directive } from 'vue'

// v-reveal — fades + slides element up when it enters the viewport
// Usage: <div v-reveal> or <div v-reveal="{ delay: 200 }">

interface RevealOptions {
  delay?: number       // ms delay before animation starts (default 0)
  duration?: number    // ms animation duration (default 600)
  y?: number           // px to translate from (default 24)
}

const reveal: Directive<HTMLElement, RevealOptions | undefined> = {
  mounted(el, binding) {
    const { delay = 0, duration = 600, y = 24 } = binding.value ?? {}

    // Set initial invisible state
    el.style.opacity = '0'
    el.style.transform = `translateY(${y}px)`
    el.style.transition = `opacity ${duration}ms ease, transform ${duration}ms ease`
    el.style.transitionDelay = `${delay}ms`

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            el.style.opacity = '1'
            el.style.transform = 'translateY(0)'
            observer.unobserve(el)
          }
        })
      },
      { threshold: 0.12 },
    )

    observer.observe(el)
  },
}

export default reveal
