// @File: src/hooks/useVisitorTracking.ts
// @Desc: Single React hook that wires visitor tracking into the app. Fires
//        a pageview on every route change and a heartbeat every 60s while
//        the tab is visible. Mount once near the router root.
import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { trackHeartbeat, trackPageview } from "@/lib/visitorTracking";

const HEARTBEAT_MS = 60_000;

export function useVisitorTracking(): void {
  const { pathname, search } = useLocation();
  const lastPathRef = useRef<string>("");

  useEffect(() => {
    // Skip admin CMS pages entirely — they shouldn't pollute visitor stats.
    if (pathname.startsWith("/admin")) {
      lastPathRef.current = pathname + search;
      return;
    }
    const full = pathname + search;
    if (lastPathRef.current === full) return;
    lastPathRef.current = full;
    void trackPageview(full);
  }, [pathname, search]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const interval = window.setInterval(() => {
      if (document.visibilityState === "visible" && !window.location.pathname.startsWith("/admin")) {
        void trackHeartbeat();
      }
    }, HEARTBEAT_MS);
    return () => window.clearInterval(interval);
  }, []);
}