// this is a test
import SuspenseLoader from '@UI/Loaders/SuspenseLoader';
import { router } from '@app/router';
import { Suspense } from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';

import './index.css'; //TODO don't change position.... crashes... move to index.html line how we did in client...
import { Toaster } from './shadecn/components/ui/toaster';
import React from 'react';
import Providers from './Providers';
import LocalStorageSupportBridge from '@components/LocalStorageSupportBridge';
import ScreenshareIncomingModal from '@components/ScreenshareIncomingModal';

const root = ReactDOM.createRoot(document.getElementById('root')!);

// Verify icons exist and register service worker
async function initializeApp() {
  // Check if icons exist (both SVG and PNG)
  const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
  const missingIcons = [];
  
  for (const size of iconSizes) {
    // Check for PNG version
    try {
      const pngResponse = await fetch(`/icons/icon-${size}x${size}.png`, { method: 'HEAD' });
      if (!pngResponse.ok) {
        missingIcons.push(`icon-${size}x${size}.png`);
      }
    } catch {
      missingIcons.push(`icon-${size}x${size}.png`);
    }
    
    // Check for SVG version
    try {
      const svgResponse = await fetch(`/icons/icon-${size}x${size}.svg`, { method: 'HEAD' });
      if (!svgResponse.ok) {
        missingIcons.push(`icon-${size}x${size}.svg`);
      }
    } catch {
      missingIcons.push(`icon-${size}x${size}.svg`);
    }
  }
  
  // Check badge icons
  try {
    const badgePngResponse = await fetch('/icons/badge-72x72.png', { method: 'HEAD' });
    if (!badgePngResponse.ok) {
      missingIcons.push('badge-72x72.png');
    }
  } catch {
    missingIcons.push('badge-72x72.png');
  }
  
  try {
    const badgeSvgResponse = await fetch('/icons/badge-72x72.svg', { method: 'HEAD' });
    if (!badgeSvgResponse.ok) {
      missingIcons.push('badge-72x72.svg');
    }
  } catch {
    missingIcons.push('badge-72x72.svg');
  }
  
  if (missingIcons.length > 0) {
    console.warn('⚠️ Some notification icons are missing:', missingIcons);
    console.log('💡 Run "npm run setup-icons" to generate SVG icons');
    console.log('💡 Open "/icons/generate-png-icons.html" in browser to generate PNG icons');
  } else {
    console.log('✅ All notification icons (SVG & PNG) are ready');
  }

  // Register service worker for PWA push notifications
  if ('serviceWorker' in navigator) {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js', {
        scope: '/',
        updateViaCache: 'none'
      });

      console.log('✅ Service Worker registered successfully:', registration.scope);
      
      // Handle service worker updates
      registration.addEventListener('updatefound', () => {
        console.log('🔄 New service worker available');
        const newWorker = registration.installing;
        if (newWorker) {
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              console.log('🆙 New service worker installed, app will use new version on next load');
              // Optionally show a toast notification about the update
            }
          });
        }
      });
    } catch (error) {
      console.error('❌ Service Worker registration failed:', error);
    }
  }
}

document.addEventListener('DOMContentLoaded', () => {
  main();
});

async function main() {
  try {
    // Initialize icons and service worker
    await initializeApp();
    
    root.render(
      <>
        <React.StrictMode>
          <Providers>
            <Suspense fallback={<SuspenseLoader />}>
              <RouterProvider router={router} />
              <ScreenshareIncomingModal />
              <LocalStorageSupportBridge />
              <Toaster />
            </Suspense>
          </Providers>
        </React.StrictMode>
      </>
    );
  } finally {
    // Ensure the loader is removed after rendering
    document.querySelector('#loader.appy-loader')?.remove();
  }
}
