/**
 * Posts a "watching now" heartbeat to /api/stats/heartbeat every 60s
 * while the user is actively engaged with playable content. The admin
 * dashboard's "Live Watchers" widget reads from the resulting MongoDB
 * `stats_heartbeats` collection.
 *
 * Mount at the top of any page where playback is happening (LiveTV,
 * Movies detail, Series detail) and pass the channel/title + kind. The
 * hook silently no-ops on logged-out / preview / SSR contexts.
 */
import { useEffect } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiPostHeartbeat, getToken } from "@/lib/nadiAuth";

const DEVICE_KEY = "nadiplay_device_id";

const getDeviceId = (): string => {
  try {
    const cur = localStorage.getItem(DEVICE_KEY);
    if (cur) return cur;
    const fresh =
      "dev-" +
      Math.random().toString(36).slice(2, 10) +
      "-" +
      Date.now().toString(36);
    localStorage.setItem(DEVICE_KEY, fresh);
    return fresh;
  } catch {
    return "dev-anon-" + Date.now().toString(36);
  }
};

export const useHeartbeat = (
  active: boolean,
  meta: { channel?: string; kind?: "live" | "vod" | "series" } = {},
) => {
  const { user } = useAuth();
  useEffect(() => {
    if (!active) return;
    if (!user || !getToken()) return;

    const send = () =>
      void apiPostHeartbeat({
        device_id: getDeviceId(),
        channel: meta.channel,
        kind: meta.kind ?? "live",
      }).catch(() => {
        /* network blips are fine */
      });

    // Fire immediately on mount, then every 60s
    send();
    const id = window.setInterval(send, 60_000);
    return () => window.clearInterval(id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [active, user?.id, meta.channel, meta.kind]);
};
