"use client";

import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";

import { shouldTrackPath } from "@/lib/analytics/traffic";

const DEDUPE_MS = 30_000;

/** Sends one page-view per route visit (deduped on quick remounts). */
export function PageViewBeacon() {
  const pathname = usePathname();
  const lastSent = useRef<{ path: string; at: number } | null>(null);

  useEffect(() => {
    if (!pathname || !shouldTrackPath(pathname)) return;

    const now = Date.now();
    if (
      lastSent.current?.path === pathname &&
      now - lastSent.current.at < DEDUPE_MS
    ) {
      return;
    }
    lastSent.current = { path: pathname, at: now };

    void fetch("/api/analytics/pageview", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ path: pathname }),
      credentials: "same-origin",
      keepalive: true,
    }).catch(() => {});
  }, [pathname]);

  return null;
}
