"use client";

import { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { prepareMarketingVisitor } from "@/lib/marketing-visitor";
import { getGoogleAnalyticsIdentifiers } from "@/lib/google-analytics-client-id";
import {
  MARKETING_SESSION_MS,
  normalizeMarketingLandingPath,
  prepareMarketingAttribution,
} from "@/lib/marketing-attribution";

const inFlight = new Set<string>();
const sentViews = new Map<string, number>();

async function trackLandingView(pathname: string) {
  const visitorId = prepareMarketingVisitor();
  const attribution = prepareMarketingAttribution(visitorId);
  const measurementId = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID?.trim() ?? "";
  const analytics = await getGoogleAnalyticsIdentifiers(measurementId);
  // Only approved attribution fields enter storage, never arbitrary URL queries.
  const pageKey = `marketing-view:v2:${visitorId}:${pathname}:${JSON.stringify(attribution)}`;
  let lastSent = sentViews.get(pageKey) ?? 0;
  try {
    lastSent = Number(window.sessionStorage.getItem(pageKey)) || lastSent;
  } catch { /* In-memory deduplication remains available. */ }
  if (inFlight.has(pageKey) || Date.now() - lastSent < MARKETING_SESSION_MS) return;

  inFlight.add(pageKey);
  try {
    const response = await fetch("/api/marketing/track", {
      body: JSON.stringify({
        gaClientId: analytics.clientId,
        gaSessionId: analytics.sessionId,
        landingPath: pathname,
        ...attribution,
        screenHeight: window.screen.height,
        screenWidth: window.screen.width,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone ?? "",
        visitorId,
        viewportHeight: window.innerHeight,
        viewportWidth: window.innerWidth,
      }),
      headers: { "Content-Type": "application/json" },
      keepalive: true,
      redirect: "error",
      method: "POST",
    });
    const result = response.ok ? await response.json() : null;
    if (!result?.ok) return;
    const sentAt = Date.now();
    sentViews.set(pageKey, sentAt);
    try {
      window.sessionStorage.setItem(pageKey, String(sentAt));
    } catch { /* Navigation must work with storage disabled. */ }
  } catch {
    // Do not mark blocked or failed requests as tracked; a later visit can retry.
  } finally {
    inFlight.delete(pageKey);
  }
}

export function MarketingFunnelTracker() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (["localhost", "127.0.0.1"].includes(window.location.hostname)) return;
    const publicPath = normalizeMarketingLandingPath(window.location.pathname + window.location.search);
    if (publicPath) void trackLandingView(publicPath);
  }, [pathname, searchParams]);

  return null;
}
