/**
 * Vercel Web Analytics for the static React prototype.
 * Next.js apps use `import { Analytics } from "@vercel/analytics/next"` in layout;
 * this mirrors `@vercel/analytics/react` (same runtime behavior as the published package).
 *
 * NOTE: these Babel <script> tags share one global scope, so we avoid
 * top-level destructuring (e.g. `const { useEffect } = React`) which would
 * collide with the main app and throw "Identifier already declared".
 */
const ANALYTICS_SDK = "@vercel/analytics";
const ANALYTICS_VERSION = "2.0.1";

function isLocalDev() {
  const host = window.location.hostname;
  return host === "localhost" || host === "127.0.0.1";
}

function getScriptSrc(mode) {
  if (mode === "development") {
    return "https://va.vercel-scripts.com/v1/script.debug.js";
  }
  return "/_vercel/insights/script.js";
}

function injectVercelAnalytics({ mode = "auto", debug = true, disableAutoTrack = false } = {}) {
  if (window.va) {
    /* queue already initialized */
  } else {
    window.va = function va(...params) {
      if (!window.vaq) window.vaq = [];
      window.vaq.push(params);
    };
  }

  const resolvedMode =
    mode === "auto" ? (isLocalDev() ? "development" : "production") : mode;
  window.vam = resolvedMode;

  const src = getScriptSrc(resolvedMode);
  if (document.head.querySelector(`script[src="${src}"]`)) return;

  const script = document.createElement("script");
  script.src = src;
  script.defer = true;
  script.dataset.sdkn = `${ANALYTICS_SDK}/react`;
  script.dataset.sdkv = ANALYTICS_VERSION;
  if (disableAutoTrack) script.dataset.disableAutoTrack = "1";
  if (resolvedMode === "development" && debug === false) {
    script.dataset.debug = "false";
  }
  script.onerror = () => {
    const hint =
      resolvedMode === "development"
        ? "Check ad blockers, or ignore when testing off Vercel."
        : "Enable Web Analytics on the Vercel project and redeploy.";
    console.info(`[Vercel Web Analytics] Script not loaded (${src}). ${hint}`);
  };
  document.head.appendChild(script);
  console.info("[Vercel Web Analytics] inject", { mode: resolvedMode, src });
}

function Analytics({ route = null, path = null, mode = "auto" }) {
  React.useEffect(() => {
    injectVercelAnalytics({
      mode,
      disableAutoTrack: route != null,
    });
  }, [mode, route]);

  React.useEffect(() => {
    if (route == null) return;
    const pagePath =
      path || `${window.location.pathname}${window.location.hash || ""}`;
    if (typeof window.va === "function") {
      window.va("pageview", { route, path: pagePath });
    }
  }, [route, path]);

  return null;
}

window.Analytics = Analytics;
