/**
 * Performance detection and optimization for glassmorphism effects
 * Automatically reduces effects on low-end devices
 */

// Device capability detection
export function detectDeviceCapabilities() {
  const capabilities = {
    isLowEnd: false,
    isMobile: false,
    hasReducedMotion: false,
    hardwareConcurrency: navigator.hardwareConcurrency || 2,
    deviceMemory: navigator.deviceMemory || 2,
    connection: navigator.connection || null
  };

  // Detect low-end devices
  if (capabilities.hardwareConcurrency <= 2 || capabilities.deviceMemory <= 2) {
    capabilities.isLowEnd = true;
  }

  // Check for slow network connection
  if (capabilities.connection && capabilities.connection.effectiveType) {
    const slowConnections = ['slow-2g', '2g', '3g'];
    if (slowConnections.includes(capabilities.connection.effectiveType)) {
      capabilities.isLowEnd = true;
    }
  }

  // Detect mobile devices
  capabilities.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

  // Check for reduced motion preference
  capabilities.hasReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  return capabilities;
}

// Apply performance optimizations based on device capabilities
export function applyPerformanceOptimizations() {
  const capabilities = detectDeviceCapabilities();
  const body = document.body;

  // Add CSS classes for optimization
  if (capabilities.isLowEnd) {
    body.classList.add('low-end-device');
  }

  if (capabilities.isMobile) {
    body.classList.add('mobile-device');
  }

  if (capabilities.hasReducedMotion) {
    body.classList.add('reduced-motion');
  }

  // Log performance optimization decisions
  console.log('Performance optimizations applied:', {
    isLowEnd: capabilities.isLowEnd,
    isMobile: capabilities.isMobile,
    hasReducedMotion: capabilities.hasReducedMotion,
    hardwareConcurrency: capabilities.hardwareConcurrency,
    deviceMemory: capabilities.deviceMemory
  });

  return capabilities;
}

// Monitor performance and adjust effects dynamically
export function monitorPerformance() {
  if (!window.performance || !window.performance.getEntriesByType) {
    return;
  }

  // Check for frame rate issues
  let frameCount = 0;
  let lastTime = performance.now();

  function checkFrameRate() {
    frameCount++;
    const currentTime = performance.now();
    
    if (currentTime - lastTime >= 1000) {
      const fps = frameCount;
      frameCount = 0;
      lastTime = currentTime;
      
      // If FPS is consistently low, reduce effects
      if (fps < 30) {
        document.body.classList.add('performance-degraded');
        console.warn('Low FPS detected, reducing glassmorphism effects');
      } else if (fps > 50) {
        document.body.classList.remove('performance-degraded');
      }
    }
    
    requestAnimationFrame(checkFrameRate);
  }
  
  requestAnimationFrame(checkFrameRate);
}

// Initialize performance optimizations
export function initializePerformanceOptimizations() {
  // Apply initial optimizations
  const capabilities = applyPerformanceOptimizations();
  
  // Start performance monitoring
  if (!capabilities.isLowEnd) {
    monitorPerformance();
  }
  
  // Listen for connection changes
  if (navigator.connection) {
    navigator.connection.addEventListener('change', () => {
      applyPerformanceOptimizations();
    });
  }
  
  // Listen for reduced motion changes
  const reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
  reducedMotionQuery.addEventListener('change', () => {
    applyPerformanceOptimizations();
  });
}