"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { apiBaseUrl, apiHeaders, apiPath } from "@/lib/api-url";

const recentViewKey = "ride-n-revive-recent-page-view";
const duplicateWindowMs = 2000;

export function WebsiteTrafficTracker() {
  const pathname = usePathname();

  useEffect(() => {
    if (!pathname || pathname.startsWith("/admin")) {
      return;
    }

    const normalizedPath = pathname !== "/" ? pathname.replace(/\/+$/, "") : pathname;
    const now = Date.now();
    const recentView = sessionStorage.getItem(recentViewKey);

    if (recentView) {
      const [recentPath, recentTimestamp] = recentView.split("|");
      const elapsedMs = now - Number(recentTimestamp);

      if (recentPath === normalizedPath && elapsedMs < duplicateWindowMs) {
        return;
      }
    }

    sessionStorage.setItem(recentViewKey, `${normalizedPath}|${now}`);

    void fetch(`${apiBaseUrl}${apiPath("/api/analytics/page-view")}`, {
      method: "POST",
      keepalive: true,
      headers: apiHeaders({
        "Content-Type": "application/json",
      }),
      body: JSON.stringify({
        pagePath: normalizedPath,
        referrer: document.referrer || undefined,
      }),
    }).catch(() => {
      // Analytics should never interrupt browsing.
    });
  }, [pathname]);

  return null;
}
