import {useCallback} from 'react'

import {InView} from 'react-intersection-observer'

interface Props {
  children: React.ReactNode
  onImpression?: () => void
  triggerOnce?: boolean
  threshold?: number
  className?: string
}

export const TrackingPixel = ({
  children,
  onImpression,
  triggerOnce = false,
  threshold,
  className,
}: Props) => {
  const onChange = useCallback(
    (inView: boolean) => {
      if (inView) {
        onImpression?.()
      }
    },
    [onImpression]
  )

  return (
    <InView
      as="div"
      onChange={onChange}
      triggerOnce={triggerOnce}
      className={className}
      threshold={threshold}
    >
      {children}
    </InView>
  )
}
