import { useEffect } from 'react'

import { postReferralVisits } from '../../api'

interface IReferralLogicProps {
  eventId: string | number;
}

export const ReferralLogic = (props: IReferralLogicProps) => {
  const { eventId } = props

  useEffect(() => {
    const isWindowDefined = typeof window !== 'undefined'

    if (isWindowDefined) {
      const params: URLSearchParams = new URL(`${window.location}`).searchParams
      const referralId = params.get('ttf_r') || params.get('referrer_id') || ''
      const referralValue = [eventId, '.', referralId].join('')
      const isAlreadyCounted = localStorage.getItem('referral_key') === referralValue

      if (referralId && eventId && !isAlreadyCounted) {
        (async () => {
          try {
            await postReferralVisits(`${eventId}`, referralId)
            localStorage.setItem('referral_key', referralValue)
          } catch (error) {}
        })()
      }
    }
  }, [eventId])

  return null
}
