'use client';

import { useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import { recordAttributionEvent } from '@/lib/api';

export function AttributionTracker() {
  const searchParams = useSearchParams();
  const tracked = useRef(false);

  useEffect(() => {
    if (tracked.current) return;
    const utmSource = searchParams.get('utm_source');
    if (!utmSource) return;
    tracked.current = true;
    void recordAttributionEvent({
      event_type: 'landing',
      utm_source: utmSource,
      utm_medium: searchParams.get('utm_medium') ?? '',
      utm_campaign: searchParams.get('utm_campaign') ?? '',
      ref_id: searchParams.get('ref') ?? '',
    }).catch(() => {});
  }, [searchParams]);

  return null;
}
