import { useState, useEffect, useRef, useCallback } from 'react';
import { API_URL } from '../constants/defaults';

export function useNetworkStatus(intervalMs = 15000) {
  const [isOnline, setIsOnline] = useState(true);
  const queueRef = useRef([]);

  useEffect(() => {
    let mounted = true;
    const check = async () => {
      try {
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), 5000);
        // Use plain fetch for ping - it doesn't require authentication
        const res = await fetch(`${API_URL}?action=ping`, {
          method: 'GET',
          signal: controller.signal,
          headers: { 'Content-Type': 'application/json' },
        });
        clearTimeout(timeout);
        let online = false;
        if (res.ok) {
          try {
            const data = await res.json();
            online = data?.ok === true;
          } catch (_) {
            online = true; // non-JSON but reachable — assume online
          }
        }
        if (mounted) setIsOnline(online);
        // Replay queued operations when back online
        if (online && queueRef.current.length > 0) {
          const ops = [...queueRef.current];
          queueRef.current = [];
          for (const op of ops) {
            try { await op(); } catch (_) { queueRef.current.push(op); }
          }
        }
      } catch (_) {
        if (mounted) setIsOnline(false);
      }
    };
    check();
    const id = setInterval(check, intervalMs);
    return () => { mounted = false; clearInterval(id); };
  }, [intervalMs]);

  const enqueue = useCallback((operation) => {
    queueRef.current.push(operation);
  }, []);

  return { isOnline, enqueue };
}
