'use client'

import { useEffect } from 'react'

function readQueryRef(): string | null {
  try {
    const url = new URL(window.location.href)
    return url.searchParams.get('ref')
  } catch {
    return null
  }
}

function setReferralCookie(code: string) {
  const normalized = code.trim().toLowerCase()
  // Accept only our invite codes (12 hex chars) to avoid storing garbage.
  if (!/^[0-9a-f]{12}$/.test(normalized)) return

  const maxAgeSeconds = 60 * 60 * 24 * 30 // 30 days
  document.cookie = `pounce_ref=${encodeURIComponent(normalized)}; Max-Age=${maxAgeSeconds}; Path=/; SameSite=Lax`
}

export default function ReferralCapture() {
  useEffect(() => {
    const ref = readQueryRef()
    if (ref) setReferralCookie(ref)
  }, [])

  return null
}

