"use client";
import { useEffect } from "react";
import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
declare global {
interface Window {
dataLayer?: unknown[];
gtag?: (...args: unknown[]) => void;
}
}
function trackPageView(url: string, gaMeasurementId?: string) {
if (!gaMeasurementId || !window.gtag) {
return;
}
window.gtag("event", "page_view", {
page_location: window.location.href,
page_path: url,
page_title: document.title,
});
}
type AnalyticsProps = {
clarityProjectId?: string;
gaMeasurementId?: string;
};
export default function Analytics({ clarityProjectId, gaMeasurementId }: AnalyticsProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (!pathname) {
return;
}
const query = searchParams.toString();
const url = query ? `${pathname}?${query}` : pathname;
trackPageView(url, gaMeasurementId);
}, [gaMeasurementId, pathname, searchParams]);
if (!gaMeasurementId && !clarityProjectId) {
return null;
}
return (
<>
{gaMeasurementId ? (
<>
>
) : null}
{clarityProjectId ? (
) : null}
>
);
}