import { API_BASE_URL } from "@/configs";
import { useCallback, useEffect, useRef, useState } from "react";

/**
 * Pure-JS network status hook — no native modules required.
 * Pings a lightweight endpoint to determine connectivity.
 */
export function useNetworkStatus() {
  const [isConnected, setIsConnected] = useState<boolean | null>(null);
  const [isChecking, setIsChecking] = useState(true);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const checkConnection = useCallback(async () => {
    try {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), 5000);

      await fetch(API_BASE_URL, {
        method: "HEAD",
        signal: controller.signal,
      });

      clearTimeout(timeout);
      setIsConnected(true);
    } catch {
      setIsConnected(false);
    } finally {
      setIsChecking(false);
    }
  }, []);

  useEffect(() => {
    // Initial check
    checkConnection();

    // Re-check every 10 seconds
    intervalRef.current = setInterval(checkConnection, 10000);

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [checkConnection]);

  return { isConnected, isChecking };
}
