"use client";

import { usePathname } from "next/navigation";
import { GoogleAnalytics } from "@next/third-parties/google";
import MetaPixel from "@/components/MetaPixel";

/** Rutas internas que no deben medirse (panel admin y su login). */
function isPrivatePath(pathname: string | null): boolean {
  if (!pathname) return false;
  return pathname === "/admin" || pathname.startsWith("/admin/") || pathname.startsWith("/web/");
}

declare global {
  interface Window {
    [key: `ga-disable-${string}`]: boolean | undefined;
  }
}

export default function SiteAnalytics({ gaId, metaPixelId }: { gaId: string; metaPixelId: string }) {
  const pathname = usePathname();
  const isPrivate = isPrivatePath(pathname);

  // Se fija durante el render (antes de que el router haga pushState) para que GA4
  // tampoco registre navegaciones SPA hacia el admin si ya estaba cargado.
  // Es idempotente, por eso es seguro hacerlo en render.
  if (typeof window !== "undefined" && gaId) {
    // eslint-disable-next-line react-hooks/immutability
    window[`ga-disable-${gaId}`] = isPrivate;
  }

  if (isPrivate) return null;

  return (
    <>
      {gaId && <GoogleAnalytics gaId={gaId} />}
      {metaPixelId && <MetaPixel pixelId={metaPixelId} />}
    </>
  );
}
