"use client";

import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { isMonitoringEnabled } from "@/config/monitoring";
import {
  detectClientTypeFromUa,
  getDeviceDisplayName,
  getOrCreateDeviceId,
} from "@/lib/devicePresence";

const HEARTBEAT_INTERVAL_MS = 30_000;
const POOR_RTT_MS = 3_000;

async function measurePingRtt(): Promise<number | null> {
  const start = performance.now();
  try {
    const res = await clientAuthFetch(
      `${NEXT_PUBLIC_API_URL}/device-presence/ping`,
      { method: "GET", cache: "no-store" }
    );
    if (!res.ok) return null;
    return Math.round(performance.now() - start);
  } catch {
    return null;
  }
}

function resolveConnectionQuality(
  navigatorOnline: boolean,
  rttMs: number | null
): "good" | "poor" | "offline" {
  if (!navigatorOnline) return "offline";
  if (rttMs == null || rttMs >= POOR_RTT_MS) return "poor";
  return "good";
}

export default function DevicePresenceReporter() {
  const pathname = usePathname();
  const { status } = useSession();
  const inFlightRef = useRef(false);
  const lastPathRef = useRef<string | null>(null);

  useEffect(() => {
    if (!isMonitoringEnabled || status !== "authenticated") return;

    const sendHeartbeat = async (activityBump: boolean) => {
      if (inFlightRef.current) return;
      inFlightRef.current = true;
      try {
        const navOnline =
          typeof navigator !== "undefined" ? navigator.onLine : true;
        const rttMs = await measurePingRtt();
        const connectionQuality = resolveConnectionQuality(navOnline, rttMs);

        const response = await clientAuthFetch(
          `${NEXT_PUBLIC_API_URL}/device-presence/heartbeat`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              deviceId: getOrCreateDeviceId(),
              displayName: getDeviceDisplayName() || undefined,
              currentPath: pathname,
              rttMs,
              connectionQuality,
              navigatorOnline: navOnline,
              clientType: detectClientTypeFromUa(),
              userAgent:
                typeof navigator !== "undefined"
                  ? navigator.userAgent
                  : undefined,
              activityBump,
            }),
          }
        );
        if (response.status === 401 || response.status === 403) return;
      } catch {
        // silent — monitor page will show offline via missed heartbeats
      } finally {
        inFlightRef.current = false;
      }
    };

    const pathChanged = lastPathRef.current !== pathname;
    lastPathRef.current = pathname;
    void sendHeartbeat(pathChanged);

    const intervalId = window.setInterval(() => {
      void sendHeartbeat(false);
    }, HEARTBEAT_INTERVAL_MS);

    const onOnline = () => void sendHeartbeat(true);
    const onOffline = () => void sendHeartbeat(false);
    window.addEventListener("online", onOnline);
    window.addEventListener("offline", onOffline);

    return () => {
      window.clearInterval(intervalId);
      window.removeEventListener("online", onOnline);
      window.removeEventListener("offline", onOffline);
    };
  }, [pathname, status]);

  return null;
}
