"use client";

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

import { customerCsrfHeader } from "@/lib/customer-csrf.client";

/**
 * Reports each portal page the signed-in customer / RM opens, so admins see real activity on
 * the dashboard feed. Renders nothing. Best effort: errors are ignored, and the server
 * de-duplicates repeat hits on the same page.
 *
 * Sends only the pathname (never the query string, which can carry tokens).
 */
export function PortalActivityTracker({ tenant }: { tenant: string }) {
  const pathname = usePathname();
  const lastSent = useRef<string | null>(null);

  useEffect(() => {
    if (!pathname || lastSent.current === pathname) return;
    lastSent.current = pathname;

    void fetch(`/customer/${tenant}/guest/track`, {
      method: "POST",
      credentials: "same-origin",
      cache: "no-store",
      keepalive: true,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        ...customerCsrfHeader(tenant),
      },
      body: JSON.stringify({ path: pathname }),
    }).catch(() => {
      // Tracking must never interfere with navigation.
    });
  }, [pathname, tenant]);

  return null;
}
