/**
 * Performance configuration for the application
 */

// Extended Navigator interface for connection API
interface NavigatorConnection {
  connection?: {
    effectiveType: string;
    downlink: number;
    rtt: number;
    saveData: boolean;
  };
  deviceMemory?: number;
}

export const performanceConfig = {
  // Cache settings
  cache: {
    // Cache TTL in milliseconds
    ttl: {
      products: 15 * 60 * 1000,     // 15 minutes
      categories: 30 * 60 * 1000,   // 30 minutes
      user: 10 * 60 * 1000,         // 10 minutes
      cart: 5 * 60 * 1000,          // 5 minutes
      orders: 60 * 60 * 1000,       // 1 hour
    },
    
    // Cache size limits
    maxSize: 10 * 1024 * 1024,      // 10MB
    maxItems: 100,
    
    // Cleanup intervals
    cleanupInterval: 5 * 60 * 1000,  // 5 minutes
  },

  // Image optimization
  images: {
    quality: {
      default: 75,
      hero: 90,
      thumbnail: 60,
    },
    
    formats: ['webp', 'jpeg'],
    
    sizes: {
      thumbnail: '(max-width: 640px) 100vw, 200px',
      card: '(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw',
      hero: '100vw',
    },
    
    blur: {
      enabled: true,
      quality: 10,
    },
  },

  // Lazy loading settings
  lazyLoading: {
    rootMargin: {
      default: '50px',
      images: '100px',
      components: '150px',
      heavy: '200px',
    },
    
    delays: {
      immediate: 0,
      fast: 100,
      normal: 200,
      slow: 500,
    },
    
    thresholds: [0, 0.25, 0.5, 0.75, 1],
  },

  // API performance
  api: {
    timeout: 10000,               // 10 seconds
    retryAttempts: 3,
    retryDelay: 1000,             // 1 second
    
    // Request batching
    batchDelay: 50,               // 50ms
    maxBatchSize: 10,
    
    // Prefetching
    prefetch: {
      enabled: true,
      delay: 2000,                // 2 seconds after page load
      priority: ['categories', 'featured-products'],
    },
  },

  // Monitoring and analytics
  monitoring: {
    enabled: process.env.NODE_ENV === 'development',
    
    metrics: {
      pageLoad: true,
      api: true,
      cache: true,
      images: true,
    },
    
    thresholds: {
      // Core Web Vitals targets
      lcp: 2500,                  // Largest Contentful Paint (ms)
      fid: 100,                   // First Input Delay (ms)
      cls: 0.1,                   // Cumulative Layout Shift
      
      // Custom metrics
      apiResponse: 1000,          // API response time (ms)
      cacheHitRate: 0.8,          // 80% cache hit rate
    },
  },

  // Feature flags for performance features
  features: {
    serviceWorker: false,         // Service worker caching
    preloadCritical: true,        // Preload critical resources
    resourceHints: true,          // DNS prefetch, preconnect
    imageOptimization: true,      // Next.js Image optimization
    bundleAnalysis: process.env.NODE_ENV === 'development',
  },

  // Progressive enhancement
  progressive: {
    // Reduce functionality on slow connections
    slowConnection: {
      reduceAnimations: true,
      lowerImageQuality: true,
      disablePreloading: true,
    },
    
    // Enhanced features for fast connections
    fastConnection: {
      enablePreloading: true,
      higherImageQuality: true,
      prefetchNextPages: true,
    },
  },
} as const;

/**
 * Get configuration based on connection speed
 */
export function getPerformanceConfig() {
  if (typeof window === 'undefined') {
    return performanceConfig;
  }

  // Detect connection speed (if available)
  const connection = (navigator as NavigatorConnection).connection;
  if (connection) {
    const isSlowConnection = connection.effectiveType === 'slow-2g' || 
                           connection.effectiveType === '2g' ||
                           connection.saveData;
    
    if (isSlowConnection) {
      return {
        ...performanceConfig,
        cache: {
          ...performanceConfig.cache,
          ttl: {
            ...performanceConfig.cache.ttl,
            // Increase cache times for slow connections
            products: 30 * 60 * 1000,
            categories: 60 * 60 * 1000,
          },
        },
        images: {
          ...performanceConfig.images,
          quality: {
            default: 60,
            hero: 75,
            thumbnail: 50,
          },
        },
        lazyLoading: {
          ...performanceConfig.lazyLoading,
          rootMargin: {
            ...performanceConfig.lazyLoading.rootMargin,
            // Load closer to viewport on slow connections
            default: '25px',
            images: '50px',
          },
        },
      };
    }
  }

  return performanceConfig;
}

/**
 * Performance monitoring utilities
 */
export const performanceUtils = {
  /**
   * Measure and log performance metrics
   */
  measurePerformance: (name: string, fn: () => void | Promise<void>) => {
    if (!performanceConfig.monitoring.enabled) {
      return typeof fn === 'function' ? fn() : fn;
    }

    const start = performance.now();
    const result = fn();
    
    if (result instanceof Promise) {
      return result.finally(() => {
        const duration = performance.now() - start;
        console.log(`⚡ ${name}: ${duration.toFixed(2)}ms`);
      });
    } else {
      const duration = performance.now() - start;
      console.log(`⚡ ${name}: ${duration.toFixed(2)}ms`);
      return result;
    }
  },

  /**
   * Check if user prefers reduced motion
   */
  prefersReducedMotion: () => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  },

  /**
   * Get connection info
   */
  getConnectionInfo: () => {
    if (typeof window === 'undefined') return null;
    
    const connection = (navigator as NavigatorConnection).connection;
    if (!connection) return null;

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

  /**
   * Check if device has limited resources
   */
  isLowEndDevice: () => {
    if (typeof window === 'undefined') return false;
    
    // Check for device memory (Chrome only)
    const deviceMemory = (navigator as NavigatorConnection).deviceMemory;
    if (deviceMemory && deviceMemory < 4) return true;
    
    // Check for hardware concurrency
    if (navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4) return true;
    
    return false;
  },
};

export default performanceConfig;