import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import './index.css'
import App from './App.jsx'

// Pre-load Google Maps SDK script globally with strict English locale & auth failure interception
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;
if (typeof window !== 'undefined') {
  window.gm_authFailure = () => {
    console.warn('[GoogleMaps] Authentication failed. Triggering application fallback.');
    window.dispatchEvent(new CustomEvent('google-maps-auth-failure'));
  };
}
if (GOOGLE_MAPS_API_KEY && typeof window !== 'undefined') {
  const expectedSrc = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=places&language=en&region=IN&loading=async`;
  const existingScript = document.getElementById('google-maps-js-sdk');
  if (!existingScript || existingScript.src !== expectedSrc) {
    if (existingScript) existingScript.remove();
    const script = document.createElement('script');
    script.id = 'google-maps-js-sdk';
    script.src = expectedSrc;
    script.async = true;
    script.onerror = () => {
      window.dispatchEvent(new CustomEvent('google-maps-auth-failure'));
    };
    document.head.appendChild(script);
  }
}


const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: false,
    },
  },
});

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
);

// In development a service worker must NEVER run: it caches Vite's dev
// modules and keeps serving a stale/broken bundle across reloads (this is why
// a fixed "Invalid hook call" / "Cannot read properties of null (reading
// 'useContext')" can keep reappearing). Proactively remove any worker left
// over from a production build or an earlier session, and purge its caches.
if (import.meta.env.DEV && 'serviceWorker' in navigator) {
  navigator.serviceWorker
    .getRegistrations()
    .then((regs) => regs.forEach((reg) => reg.unregister()))
    .catch(() => {});
  if (window.caches?.keys) {
    caches.keys().then((keys) => keys.forEach((k) => caches.delete(k))).catch(() => {});
  }
}

// Register and manage the service worker ONLY in production.
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
  // When the controlling worker changes (after the user accepts an update), reload once
  // so the page runs the new bundle. Guarded so we never loop.
  let hasReloaded = false;
  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (hasReloaded) return;
    hasReloaded = true;
    window.location.reload();
  });

  // Prompt the user that a new version is ready, then activate the waiting worker on accept.
  const promptUserToUpdate = (registration) => {
    const waiting = registration.waiting;
    if (!waiting) return;
    // Non-blocking confirm; keeps behavior simple without adding UI dependencies.
    const accepted = window.confirm('A new version of Rasoi Origins is available. Reload to update?');
    if (accepted) {
      waiting.postMessage({ type: 'SKIP_WAITING' });
    }
  };

  const registerSW = () => {
    navigator.serviceWorker.register('/sw.js')
      .then((registration) => {
        // A worker is already waiting from a previous visit.
        if (registration.waiting) {
          promptUserToUpdate(registration);
        }
        // A new worker started installing — prompt once it finishes installing.
        registration.addEventListener('updatefound', () => {
          const installing = registration.installing;
          if (!installing) return;
          installing.addEventListener('statechange', () => {
            if (installing.state === 'installed' && navigator.serviceWorker.controller) {
              promptUserToUpdate(registration);
            }
          });
        });
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  };

  if (document.readyState === 'complete') {
    registerSW();
  } else {
    window.addEventListener('load', registerSW);
  }
}
