'use client'; import { useCallback, useEffect, useRef } from 'react'; import { getClient } from '@/core/lib/brainerce'; /** * Measurement for ONE recommendation card, shared by every design. * * const { ref, onClick } = useRecommendationCard(card); * ... * * - `ref` goes on the card's outer element. An impression is recorded once the * card has been at least 50% visible for 1 second (the SDK does the * IntersectionObserver work, once per card per page load). * - `onClick` goes on the card's link. It records a click and survives the * navigation (the request uses `keepalive`). * * A card without a `recToken` (the merchant's measurement is off, or the server has * no signing key) is simply not measured. Nothing here throws, and the SDK never * sends an event just because recommendations were fetched. */ export function useRecommendationCard(card: { recToken?: string | null; }) { const ref = useRef(null); const token = card.recToken ?? null; useEffect(() => { const el = ref.current; if (!el || !token) return; try { return getClient().observeRecommendation(el, { recToken: token }); } catch { return; } }, [token]); const onClick = useCallback(() => { if (!token) return; try { void getClient().trackRecommendationClick({ recToken: token }); } catch { // measurement must never break a click } }, [token]); return { ref, onClick }; }