import { useEffect, useRef, useState } from "react"

type Options = {
  topThreshold?: number        // en üstte her zaman açık
  hideAfterDownPx?: number     // aşağı inerken gizlemek için gereken px
  revealAfterUpPx?: number     // yukarı çıkarken göstermek için gereken px (asıl istediğin)
}

export function useHideOnScroll({
  topThreshold = 12,
  hideAfterDownPx = 12,
  revealAfterUpPx = 80,  // bunu büyüttükçe daha geç gelir (örn 60-120 iyi)
}: Options = {}) {
  const [visible, setVisible] = useState(true)

  const lastY = useRef(0)
  const upAccum = useRef(0)
  const downAccum = useRef(0)
  const ticking = useRef(false)

  useEffect(() => {
    lastY.current = window.scrollY || 0

    const onScroll = () => {
      const y = window.scrollY || 0
      if (ticking.current) return
      ticking.current = true

      requestAnimationFrame(() => {
        const prev = lastY.current
        const diff = y - prev // + down, - up

        // top: her zaman göster
        if (y <= topThreshold) {
          setVisible(true)
          upAccum.current = 0
          downAccum.current = 0
          lastY.current = y
          ticking.current = false
          return
        }

        if (diff > 0) {
          // scrolling down
          downAccum.current += diff
          upAccum.current = 0

          if (downAccum.current >= hideAfterDownPx) {
            setVisible(false)
            downAccum.current = 0
          }
        } else if (diff < 0) {
          // scrolling up
          upAccum.current += Math.abs(diff)
          downAccum.current = 0

          if (upAccum.current >= revealAfterUpPx) {
            setVisible(true)
            upAccum.current = 0
          }
        }

        lastY.current = y
        ticking.current = false
      })
    }

    window.addEventListener("scroll", onScroll, { passive: true })
    return () => window.removeEventListener("scroll", onScroll)
  }, [topThreshold, hideAfterDownPx, revealAfterUpPx])

  return visible
}
