import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import {registerSW} from 'virtual:pwa-register';
import App from './App.tsx';
import './index.css';

// Guard against "Cannot set property fetch of #<Window> which has only a getter"
if (typeof window !== 'undefined') {
  try {
    const orig = typeof window.fetch === 'function' ? window.fetch.bind(window) : null;
    let activeFetch = orig;
    const getActive = () => activeFetch || orig;
    const setActive = (v: any) => { activeFetch = v; };

    let curr: any = window;
    while (curr) {
      try {
        const desc = Object.getOwnPropertyDescriptor(curr, 'fetch');
        if (desc && (desc.get || !desc.writable || !desc.set)) {
          Object.defineProperty(curr, 'fetch', {
            get: getActive,
            set: setActive,
            configurable: true,
            enumerable: true
          });
        }
      } catch {}
      try {
        curr = Object.getPrototypeOf(curr);
      } catch {
        break;
      }
    }

    if (typeof Window !== 'undefined' && Window.prototype) {
      try {
        Object.defineProperty(Window.prototype, 'fetch', {
          get: getActive,
          set: setActive,
          configurable: true,
          enumerable: true
        });
      } catch {}
    }

    try {
      Object.defineProperty(window, 'fetch', {
        get: getActive,
        set: setActive,
        configurable: true,
        enumerable: true
      });
    } catch {}
  } catch {}
}

// Register service worker for Progressive Web App (PWA) offline caching & installability
if ('serviceWorker' in navigator && typeof window !== 'undefined') {
  try {
    registerSW({ immediate: true });
  } catch (err) {
    console.debug('Service worker registration deferred:', err);
  }
}

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

