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

export const useSticky = (topMarkerRef, bottomMarkerRef) => {
  const [showStickyPrice, setShowStickyPrice] = useState(true)
  const [topIntersecting, setTopIntersecting] = useState(false)
  const [bottomIntersecting, setBottomIntersecting] = useState(false)

  const topObserver = useRef(null)
  const bottomObserver = useRef(null)

  useEffect(() => {
    setShowStickyPrice(!topIntersecting && !bottomIntersecting)
  }, [topIntersecting, bottomIntersecting])

  const observeCallback = (entries) => {
    entries.forEach((entry) => {
      if (topMarkerRef && entry.target === topMarkerRef.current) {
        setTopIntersecting(entry.isIntersecting)
      }
      if (bottomMarkerRef && entry.target === bottomMarkerRef.current) {
        setBottomIntersecting(entry.isIntersecting)
      }
    })
  }

  const stickyConnect = () => {
    if (topMarkerRef) {
      topObserver.current = new IntersectionObserver(observeCallback, {
        root: null,
        rootMargin: '0px',
        threshold: 0.2,
      })
      topObserver.current.observe(topMarkerRef.current)
    }

    if (bottomMarkerRef) {
      bottomObserver.current = new IntersectionObserver(observeCallback, {
        root: null,
        rootMargin: '0px',
        threshold: 0.999,
      })
      bottomObserver.current.observe(bottomMarkerRef.current)
    }
  }

  const stickyDisconnect = () => {
    topObserver.current.disconnect()
    bottomObserver.current.disconnect()
  }

  return {
    showStickyPrice,
    stickyConnect,
    stickyDisconnect
  }

}



