import { useCallback, useEffect, useState } from "react";
import { getConnectivity } from "../api";

const POLL_MS = 30_000;

/**
 * Real reachability, not `navigator.onLine` — which reports link state and is
 * true on a plane's captive-portal wifi with no actual internet. The manual
 * override exists so offline mode can be exercised without touching wifi.
 */
export function useConnectivity() {
  const [reachable, setReachable] = useState(true);
  const [forcedOffline, setForcedOffline] = useState(false);

  const probe = useCallback(async () => {
    try {
      setReachable(await getConnectivity());
    } catch {
      setReachable(false);
    }
  }, []);

  useEffect(() => {
    probe();
    const id = setInterval(probe, POLL_MS);
    const onUp = () => probe();
    const onDown = () => setReachable(false);
    window.addEventListener("online", onUp);
    window.addEventListener("offline", onDown);
    return () => {
      clearInterval(id);
      window.removeEventListener("online", onUp);
      window.removeEventListener("offline", onDown);
    };
  }, [probe]);

  return {
    online: reachable && !forcedOffline,
    reachable,
    forcedOffline,
    setForcedOffline,
    probe,
  };
}
