/**
 * Offline Detection Utility
 * Action 3.5.1.2: Add offline detection utility
 *
 * Provides utilities to detect online/offline state using navigator.onLine API
 * and network status events
 */

/**
 * Check if the browser is currently online
 * @returns True if online, false if offline
 */
export function isOnline(): boolean {
  if (typeof navigator === 'undefined') {
    // Server-side rendering - assume online
    return true;
  }
  return navigator.onLine;
}

/**
 * Check if the browser is currently offline
 * @returns True if offline, false if online
 */
export function isOffline(): boolean {
  return !isOnline();
}

/**
 * Subscribe to online/offline state changes
 * @param callback Function to call when online state changes
 * @returns Cleanup function to unsubscribe
 */
export function subscribeToOnlineStatus(
  callback: (isOnline: boolean) => void,
): () => void {
  if (typeof window === 'undefined') {
    // Server-side rendering - no-op
    return () => {};
  }

  const handleOnline = () => callback(true);
  const handleOffline = () => callback(false);

  window.addEventListener('online', handleOnline);
  window.addEventListener('offline', handleOffline);

  // Return cleanup function
  return () => {
    window.removeEventListener('online', handleOnline);
    window.removeEventListener('offline', handleOffline);
  };
}

/**
 * Get current network connection information (if available)
 * @returns Network information or null if not available
 */
export function getNetworkInfo(): {
  effectiveType?: string;
  downlink?: number;
  rtt?: number;
  saveData?: boolean;
} | null {
  if (typeof navigator === 'undefined') {
    return null;
  }

  const connection =
    (navigator as any).connection ||
    (navigator as any).mozConnection ||
    (navigator as any).webkitConnection;

  if (!connection) {
    return null;
  }

  return {
    effectiveType: connection.effectiveType,
    downlink: connection.downlink,
    rtt: connection.rtt,
    saveData: connection.saveData,
  };
}

/**
 * Check if the connection is slow based on effective type
 * @returns True if connection is slow (2g or slower), false otherwise
 */
export function isSlowConnection(): boolean {
  const networkInfo = getNetworkInfo();
  if (!networkInfo?.effectiveType) {
    return false;
  }

  const slowTypes = ['2g', 'slow-2g'];
  return slowTypes.includes(networkInfo.effectiveType.toLowerCase());
}
