/**
 * Environment Context Capture
 * Captures browser/device information for error reports
 */

export interface EnvironmentContext {
  viewport: { width: number; height: number };
  screen: { width: number; height: number };
  memory?: { usedJSHeapSize?: number; totalJSHeapSize?: number };
  connection?: string;
  timezone: string;
  language: string;
  platform: string;
  cookiesEnabled: boolean;
  localStorage: boolean;
  sessionStorage: boolean;
}

export function captureEnvironmentContext(): EnvironmentContext {
  const context: EnvironmentContext = {
    viewport: {
      width: window.innerWidth,
      height: window.innerHeight,
    },
    screen: {
      width: window.screen.width,
      height: window.screen.height,
    },
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    language: navigator.language,
    platform: navigator.platform,
    cookiesEnabled: navigator.cookieEnabled,
    localStorage: isStorageAvailable('localStorage'),
    sessionStorage: isStorageAvailable('sessionStorage'),
  };

  // Memory info (Chrome only)
  if ('memory' in performance && (performance as any).memory) {
    const memory = (performance as any).memory;
    context.memory = {
      usedJSHeapSize: memory.usedJSHeapSize,
      totalJSHeapSize: memory.totalJSHeapSize,
    };
  }

  // Connection info
  if ('connection' in navigator) {
    context.connection = (navigator as any).connection?.effectiveType;
  }

  return context;
}

function isStorageAvailable(type: 'localStorage' | 'sessionStorage'): boolean {
  try {
    const storage = window[type];
    const test = '__storage_test__';
    storage.setItem(test, test);
    storage.removeItem(test);
    return true;
  } catch {
    return false;
  }
}
