"use client";

/**
 * useTrackPageView
 * ────────────────
 * Fires a fire-and-forget POST to /api/track every time the route
 * changes, so the admin Engagement + Activity surfaces populate
 * with navigation data without every page having to opt in.
 *
 * Contract:
 *   • Dedupes on pathname — no double-fire on React re-renders.
 *   • Never awaits — rendering is never blocked on the network.
 *   • Swallows failures — tracking must never surface as a UX error.
 *
 * Mount this once, inside BrandProvider, in the authenticated shell
 * so the active brandId is captured alongside the page_view.
 */

import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { useBrand } from "@/context/brand-context";

export function useTrackPageView(): void {
  const pathname = usePathname();
  const { brand } = useBrand();
  const brandId = brand?.id || null;
  const lastPath = useRef<string>("");

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

    // Fire-and-forget — keepalive lets the request outlive the page
    // if the user clicks through to a new route immediately.
    void fetch("/api/track", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        action: "page_view",
        category: "navigation",
        path: pathname,
        brandId,
      }),
      keepalive: true,
    }).catch(() => {
      // Silently ignore — tracking is best-effort.
    });
  }, [pathname, brandId]);
}
