'use client'; import { useEffect, useRef } from 'react'; import { usePathname } from 'next/navigation'; import { getClient } from '@/core/lib/brainerce'; import { useStoreInfo } from '@/core/providers/store-provider'; /** * Boots the merchant's marketing tags — GA4, Google Tag Manager, the Meta * pixel, the TikTok pixel — from whatever they connected in the Brainerce * dashboard. * * There is nothing to configure here and no environment variable to set. The * tag ids arrive inside `storeInfo.tracking`, which the backend resolves from * the merchant's connected marketplace apps: connecting the Google * app runs GA4 discovery and the measurement id shows up on its own, likewise * the Meta and TikTok pixels. Connect an app in the dashboard and this file * starts loading its tag within a minute — no redeploy, no code change. * * Loading GA4 also switches on Brainerce's server-side purchase conversion: * the SDK captures gtag's `client_id`/`session_id` and attaches them to cart * and checkout calls, which is what lets the backend send a purchase event * that lands in the right GA4 session instead of orphaning. */ export function TrackingBootstrap() { const { storeInfo } = useStoreInfo(); const pathname = usePathname(); const tracking = storeInfo?.tracking; const bootedRef = useRef(false); useEffect(() => { if (!tracking) return; getClient().initTracking(tracking); bootedRef.current = true; }, [tracking]); // App Router client-side navigation never reloads the document, so the // pixels' one-shot boot pageview is the only one they would ever record — // every page after the landing page would be invisible. Re-fire on each // path change, skipping the first run so the landing page isn't counted // twice. const lastPathRef = useRef(null); useEffect(() => { if (!bootedRef.current) return; if (lastPathRef.current === null) { lastPathRef.current = pathname; return; } if (lastPathRef.current === pathname) return; lastPathRef.current = pathname; if (typeof window === 'undefined') return; try { window.fbq?.('track', 'PageView'); (window.ttq as { page?: () => void } | undefined)?.page?.(); } catch { // Analytics must never break navigation. } }, [pathname]); return null; }