
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { LanguageProvider } from './src/contexts/LanguageContext';

// Safe LocalStorage & SessionStorage Polyfills for Sandbox/iframe environments
try {
  const testKey = '__storage_test__';
  window.localStorage.setItem(testKey, testKey);
  window.localStorage.removeItem(testKey);
} catch (e) {
  console.warn('LocalStorage is not accessible. Using an in-memory fallback store.', e);
  const memoryStore: Record<string, string> = {};
  const localStorageMock = {
    getItem: (key: string): string | null => {
      return key in memoryStore ? memoryStore[key] : null;
    },
    setItem: (key: string, value: string): void => {
      memoryStore[key] = String(value);
    },
    removeItem: (key: string): void => {
      delete memoryStore[key];
    },
    clear: (): void => {
      for (const key in memoryStore) {
        delete memoryStore[key];
      }
    },
    key: (index: number): string | null => {
      const keys = Object.keys(memoryStore);
      return index < keys.length ? keys[index] : null;
    },
    get length(): number {
      return Object.keys(memoryStore).length;
    }
  };
  try {
    Object.defineProperty(window, 'localStorage', {
      value: localStorageMock,
      writable: true,
      configurable: true
    });
  } catch (err) {
    console.warn('Could not override window.localStorage with fallback:', err);
  }
}

try {
  const testKey = '__session_storage_test__';
  window.sessionStorage.setItem(testKey, testKey);
  window.sessionStorage.removeItem(testKey);
} catch (e) {
  console.warn('SessionStorage is not accessible. Using an in-memory fallback store.', e);
  const memoryStore: Record<string, string> = {};
  const sessionStorageMock = {
    getItem: (key: string): string | null => {
      return key in memoryStore ? memoryStore[key] : null;
    },
    setItem: (key: string, value: string): void => {
      memoryStore[key] = String(value);
    },
    removeItem: (key: string): void => {
      delete memoryStore[key];
    },
    clear: (): void => {
      for (const key in memoryStore) {
        delete memoryStore[key];
      }
    },
    key: (index: number): string | null => {
      const keys = Object.keys(memoryStore);
      return index < keys.length ? keys[index] : null;
    },
    get length(): number {
      return Object.keys(memoryStore).length;
    }
  };
  try {
    Object.defineProperty(window, 'sessionStorage', {
      value: sessionStorageMock,
      writable: true,
      configurable: true
    });
  } catch (err) {
    console.warn('Could not override window.sessionStorage with fallback:', err);
  }
}

// Automatically unregister any active service worker & clear cache storage to fix stale cache load issues (Ctrl+F5 requirement)
try {
  if ('serviceWorker' in navigator && navigator.serviceWorker) {
    navigator.serviceWorker.getRegistrations().then((registrations) => {
      for (const registration of registrations) {
        registration.unregister().then((unregistered) => {
          if (unregistered) console.log('Stale service worker unregistered successfully');
        }).catch(() => {});
      }
    }).catch(() => {});
  }
  if ('caches' in window && window.caches) {
    window.caches.keys().then((keys) => {
      for (const key of keys) {
        window.caches.delete(key);
      }
    }).catch(() => {});
  }
} catch (error) {
  console.warn('Service worker unregister / cache purge exception:', error);
}

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);

root.render(
  <React.StrictMode>
    <LanguageProvider>
      <App />
    </LanguageProvider>
  </React.StrictMode>
);
