import React from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { router } from './router';
import '../../css/app.css';
import { initializeTheme } from '@/hooks/use-appearance';
import { ToastProvider } from './components/ToastHost';

initializeTheme();
const rootEl = document.getElementById('root')!;

// Register a minimal service worker for background sync (best-effort)
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/guest-sw.js').catch(() => {});
  navigator.serviceWorker.addEventListener('message', (evt) => {
    if (evt.data?.type === 'sync-queue') {
      import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
    }
  });
  // Also attempt to process queue on load and when going online
  import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
  window.addEventListener('online', () => {
    import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
  });
}
createRoot(rootEl).render(
  <React.StrictMode>
    <ToastProvider>
      <RouterProvider router={router} />
    </ToastProvider>
  </React.StrictMode>
);
