"use client";

import { useEffect, useRef } from "react";
import { supportRealtime } from "@/infrastructure/realtime/support-realtime";
import type { SupportActivityEvent } from "@/domain/entities/ticket";

// Used when the WebSocket isn't configured or is down, so the inbox still feels live.
const FALLBACK_POLL_MS = 6_000;

/**
 * Calls `onActivity` for every support inbox event pushed in real time, and with
 * `null` on a short polling tick whenever real time is unavailable (the caller
 * then refetches). Ticks pause while the tab is hidden and fire again on focus.
 */
export function useSupportActivity(
  onActivity: (event: SupportActivityEvent | null) => void,
  fallbackPollMs: number = FALLBACK_POLL_MS,
) {
  const handler = useRef(onActivity);
  useEffect(() => {
    handler.current = onActivity;
  });

  useEffect(() => {
    const unsubscribe = supportRealtime.subscribe((event) => handler.current(event));

    const timer = window.setInterval(() => {
      if (document.visibilityState !== "visible" || supportRealtime.isConnected) return;
      handler.current(null);
    }, fallbackPollMs);

    const onFocus = () => handler.current(null);
    window.addEventListener("focus", onFocus);

    return () => {
      unsubscribe();
      window.clearInterval(timer);
      window.removeEventListener("focus", onFocus);
    };
  }, [fallbackPollMs]);
}
