/**
 * RefCapture — fires POST /api/referrals/touch when ?ref= is present in the URL.
 *
 * Mount `client:idle` in the root layout so it:
 *   - Never blocks paint (deferred after idle)
 *   - Never enters SSR HTML (client:idle is always client-only)
 *   - Never affects cached anon-shell pages
 */

'use client';

import { useEffect } from 'react';
import { captureCaught } from '@/lib/observability';

export function RefCapture() {
  useEffect(() => {
    const code = new URLSearchParams(location.search).get('ref');
    if (!code) return;

    // Fire-and-forget: first-touch attribution. Errors silently swallowed.
    void fetch('/api/referrals/touch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code }),
      // credentials included by default for same-origin
    }).catch((err: unknown) => {
      captureCaught(err, {
        scope: 'features.referrals.RefCapture.touch',
        severity: 'info',
      });
      // Non-fatal — attribution missed at most; do not surface to user
    });
  }, []);

  return null;
}
