'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

type Fbq = (...args: unknown[]) => void;
type Ttq = { page?: () => void };

// The storefront navigates client-side, so the pixels' own snippets only see
// the first page. This sends a PageView to Meta and TikTok on every later
// route change. GA4 needs nothing here: its "page changes based on browser
// history events" enhanced measurement (on by default) already counts them,
// and a manual call would double-count. GTM: add a "History Change" trigger.
// If a pixel hasn't loaded yet (they load lazily), its own snippet will send
// the PageView for whatever page is open when it does.
export default function TrackingRouteChange({ fb, tiktok }: { fb: boolean; tiktok: boolean }) {
  const pathname = usePathname();
  const first = useRef(true);

  useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    const w = window as unknown as { fbq?: Fbq; ttq?: Ttq };
    if (fb) w.fbq?.('track', 'PageView');
    if (tiktok) w.ttq?.page?.();
  }, [pathname, fb, tiktok]);

  return null;
}
