'use client';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import Script from 'next/script';

declare global {
  interface Window {
    dataLayer: unknown[];
    gtag?: (...args: unknown[]) => void;
  }
}

export function AnalyticsTracker({ gaId }: { gaId?: string }) {
  const pathname = usePathname();
  const measurementId = gaId?.trim().toUpperCase();
  const isValidId = !!measurementId && /^G-[A-Z0-9]+$/.test(measurementId);

  useEffect(() => {
    if (!isValidId || !measurementId) return;
    window.dataLayer = window.dataLayer || [];
    window.gtag = window.gtag || function gtag(...args: unknown[]) {
      window.dataLayer.push(args);
    };
    window.gtag('js', new Date());
    window.gtag('config', measurementId, { send_page_view: false });
  }, [isValidId, measurementId]);

  useEffect(() => {
    if (!isValidId || !measurementId || !window.gtag) return;
    window.gtag('event', 'page_view', {
      page_path: `${pathname}${window.location.search}`,
      page_location: window.location.href,
      page_title: document.title,
    });
  }, [isValidId, measurementId, pathname]);

  if (!isValidId || !measurementId) return null;

  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${measurementId}`}
        strategy="afterInteractive"
      />
    </>
  );
}
