import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

// Register PWA Service Worker with immediate client-side active chunk caching
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then((reg) => {
      console.log('[PWA] Service Worker registered successfully:', reg.scope);
      
      // Safeguard client-side chunk pre-caching from the main thread
      if ('caches' in window) {
        const CACHE_NAME = 's1-skate-academy-v2';
        const assetsToCache = [
          '/',
          '/index.html',
          '/manifest.json',
          '/icon-192.png',
          '/icon-512.png'
        ];
        
        // Dynamically find stylesheets and module scripts generated by Vite for this build session
        document.querySelectorAll('link[rel="stylesheet"]').forEach((el) => {
          const href = el.getAttribute('href');
          if (href) assetsToCache.push(href);
        });
        document.querySelectorAll('script[type="module"]').forEach((el) => {
          const src = el.getAttribute('src');
          if (src) assetsToCache.push(src);
        });

        window.caches.open(CACHE_NAME)
          .then((cache) => {
            console.log('[PWA] Force-caching compiled bundle files directly from document:', assetsToCache);
            return cache.addAll(assetsToCache);
          })
          .catch((err) => {
            console.warn('[PWA] Optional client-side pre-caching bypassed:', err);
          });
      }
    })
    .catch((err) => {
      console.warn('[PWA] Service Worker registration failed:', err);
    });
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
