import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { logger } from './services/logger'
import { storageQuotaManager } from './services/storageQuotaManager'

// One-time build refresh to avoid stale caches and CDN artifacts - optimized for FCP
const BUILD_ID = (window as any).__BUILD_ID__ as string | undefined;
if (BUILD_ID) {
  const PREV_BUILD_ID = localStorage.getItem('BUILD_ID');
  if (PREV_BUILD_ID !== BUILD_ID) {
    const success = storageQuotaManager.setItem(
      'BUILD_ID',
      BUILD_ID,
      'LOW' // Build ID is low priority - build metadata
    );
    if (!success) {
      logger.debug('main', 'Failed to save BUILD_ID (quota exceeded)');
    }
    // Defer cache clearing to not block initial render
    requestIdleCallback(() => {
      (async () => {
        try {
          if ('serviceWorker' in navigator) {
            const regs = await navigator.serviceWorker.getRegistrations();
            await Promise.all(regs.map((r) => r.unregister()));
          }
          if ('caches' in window) {
            const names = await caches.keys();
            await Promise.all(names.map((n) => caches.delete(n)));
          }
        } catch (e) {
          logger.warn('build', 'Build refresh failed', e);
        }
        // Only reload if this is not the initial page load
        if (document.readyState === 'complete' && performance.navigation.type === 1) {
          window.location.replace(window.location.pathname);
        }
      })();
    }, { timeout: 5000 });
  }
}

// Suppress console security warnings (but allow all application logs)
(() => {
  const originalConsoleLog = console.log;
  const originalConsoleWarn = console.warn;
  
  // Track if we've already suppressed each warning type
  const suppressed = {
    securityWarning: false,
    audioContext: false
  };
  
  // Allow developers to bypass all filtering
  (window as any).__allowAllLogs = false;
  
  console.log = function(...args) {
    if ((window as any).__allowAllLogs) {
      return originalConsoleLog.apply(console, args);
    }
    
    const firstArg = args[0];
    // Only block the exact Chrome DevTools security warning, and only once
    if (typeof firstArg === 'string' && 
        !suppressed.securityWarning &&
        (firstArg.startsWith('%cWarning!') || 
         (firstArg.includes('This is a browser feature intended for developers') && 
          firstArg.includes('self-XSS')))) {
      suppressed.securityWarning = true;
      return; // Skip security warning (first occurrence only)
    }
    return originalConsoleLog.apply(console, args);
  };
  
  console.warn = function(...args) {
    if ((window as any).__allowAllLogs) {
      return originalConsoleWarn.apply(console, args);
    }
    
    const firstArg = args[0];
    // Only block AudioContext warning once
    if (typeof firstArg === 'string' && 
        !suppressed.audioContext && 
        firstArg.includes('AudioContext')) {
      suppressed.audioContext = true;
      return; // Skip audio context warning (first occurrence only)
    }
    return originalConsoleWarn.apply(console, args);
  };
})();

const container = document.getElementById('root')!;
const root = createRoot(container);
root.render(<App />);

// Defer all non-critical operations to improve TTI
requestIdleCallback(() => {
  // Service Worker registration - deferred to not block interactivity
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
      .register('/sw.js')
      .then((reg) => logger.info('service-worker', 'Service Worker registered', { registration: reg }))
      .catch((err) => logger.warn('service-worker', 'Service Worker registration failed', err));
  }
}, { timeout: 10000 });

// Further defer notification service to improve TTI
requestIdleCallback(() => {
  // Notification service initialization - heavily deferred
  import('@/services/notificationService').then(({ notificationService }) => {
    void notificationService.getPermissionState();
    
    // Auto-request notification permission on mobile only
    const isMobileDevice = /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
    if (isMobileDevice && 'Notification' in window) {
      if (Notification.permission === 'default') {
        setTimeout(() => {
          void notificationService.requestPermission();
        }, 1000);
      }
    }
  });
}, { timeout: 15000 });
