import { useEffect, useRef, useCallback } from "react";
import { useJamClient } from "../context/JamClientContext";
import { ALERT_NAMES } from "../helpers/globals";
import { updateUdpReachable } from "../helpers/rest";

// Assumes context.JK, context.jamClient, and jQuery are globally available
// You may want to pass these as parameters or import them as needed

export function useStun(app) {
  const jamClient = useJamClient();
  const udpBlockedRef = useRef(null);

  // Syncs the UDP blocked state and optionally calls a callback when changed
  const sync = useCallback(async (changed) => {

    const result = await jamClient.NetworkTestResult();

    if (result) {
      if (
        udpBlockedRef.current === null ||
        result.remote_udp_blocked !== udpBlockedRef.current
      ) {
        // Log the result
        if (result.remote_udp_blocked) {
          console.debug("NO STUN: " + JSON.stringify(result));
        } else {
          console.debug("STUN capable: " + JSON.stringify(result));
        }

        udpBlockedRef.current = result.remote_udp_blocked;

        if (changed) changed(result.remote_udp_blocked);
      }
    }

    return udpBlockedRef.current;
  }, [jamClient]);

  // Handles STUN events and updates the server
  useEffect(() => {
    function handleStunEvent() {
      console.debug("handling stun event...");
      sync((blocked) => {
        if (app?.clientId) {
          updateUdpReachable({
            client_id: app.clientId,
            udp_reachable: !blocked,
          });
        }
      });
    }

    // Register event listener
    if (window?.JK?.onBackendEvent && ALERT_NAMES?.STUN_EVENT) {
      window.JK.onBackendEvent(
        ALERT_NAMES.STUN_EVENT,
        "everywhere",
        handleStunEvent
      );
    }

    // Cleanup (if your event system supports it)
    return () => {
      // No built-in way to remove the event in the original code
      // Add cleanup logic here if available
    };
  }, [app, sync]);

  // Optionally, return sync or udpBlockedRef if needed by the component
  return { sync, udpBlockedRef };
}
