// Safe LocalStorage Polyfill for Sandbox/IFrame environment compatibility
const memoryStoreSafe: Record<string, string> = {};
try {
  const testKey = '__timekey_storage_test__';
  window.localStorage.setItem(testKey, 'ok');
  window.localStorage.removeItem(testKey);
} catch (e) {
  console.warn('[timeKey] Native localStorage access is restricted (common in sandboxed iframes). Deploying in-memory fallback.', e);
  
  const mockStorage: Storage = {
    length: 0,
    clear() {
      for (const k in memoryStoreSafe) {
        delete memoryStoreSafe[k];
      }
      this.length = 0;
    },
    getItem(key: string): string | null {
      return Object.prototype.hasOwnProperty.call(memoryStoreSafe, key) ? memoryStoreSafe[key] : null;
    },
    key(index: number): string | null {
      const keys = Object.keys(memoryStoreSafe);
      return keys[index] || null;
    },
    removeItem(key: string) {
      delete memoryStoreSafe[key];
      this.length = Object.keys(memoryStoreSafe).length;
    },
    setItem(key: string, value: string) {
      memoryStoreSafe[key] = String(value);
      this.length = Object.keys(memoryStoreSafe).length;
    }
  };

  try {
    Object.defineProperty(window, 'localStorage', {
      value: mockStorage,
      writable: true,
      configurable: true,
      enumerable: true
    });
  } catch (err) {
    console.warn('[timeKey] Overwrite of window.localStorage property blocked. Polyfilling Storage.prototype methods directly.');
    try {
      const originalSetItem = Storage.prototype.setItem;
      const originalGetItem = Storage.prototype.getItem;
      const originalRemoveItem = Storage.prototype.removeItem;
      const originalClear = Storage.prototype.clear;

      Storage.prototype.setItem = function(key: string, value: string) {
        try {
          originalSetItem.call(this, key, value);
        } catch (err2) {
          memoryStoreSafe[key] = String(value);
        }
      };
      Storage.prototype.getItem = function(key: string) {
        try {
          return originalGetItem.call(this, key);
        } catch (err2) {
          return Object.prototype.hasOwnProperty.call(memoryStoreSafe, key) ? memoryStoreSafe[key] : null;
        }
      };
      Storage.prototype.removeItem = function(key: string) {
        try {
          originalRemoveItem.call(this, key);
        } catch (err2) {
          delete memoryStoreSafe[key];
        }
      };
      Storage.prototype.clear = function() {
        try {
          originalClear.call(this);
        } catch (err2) {
          for (const k in memoryStoreSafe) {
            delete memoryStoreSafe[k];
          }
        }
      };
    } catch (protoErr) {
      console.error('[timeKey] Fatal: Unable to polyfill localStorage methods on Storage prototype.', protoErr);
    }
  }
}

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { GoogleOAuthProvider } from '@react-oauth/google';
import './index.css';
import './src/utils/citiesLoader';
import { App } from './App';
import { AppProvider } from './components/AppContext';
import { PublicClientApplication, Configuration } from '@azure/msal-browser';

console.info("timeKey Entry Point Loading...");

// --- Configuration ---
const DEFAULT_GOOGLE_CLIENT_ID = "92703571944-7ik1nkas0aiqm29mudbbd74fjpgrjd0n.apps.googleusercontent.com";
const MSAL_CLIENT_ID = ""; // e.g., "your-microsoft-client-id"

const msalConfig: Configuration = {
  auth: {
    clientId: MSAL_CLIENT_ID || "00000000-0000-0000-0000-000000000000",
    authority: "https://login.microsoftonline.com/common",
    redirectUri: window.location.origin,
  }
};

const msalInstance = new PublicClientApplication(msalConfig);

const MainApp: React.FC = () => {
  const [googleClientId, setGoogleClientId] = React.useState(() => {
    return localStorage.getItem('timeKey_customGoogleClientId') || 
           import.meta.env.VITE_GOOGLE_CLIENT_ID || 
           DEFAULT_GOOGLE_CLIENT_ID;
  });

  React.useEffect(() => {
    const handleIdChange = () => {
      const customId = localStorage.getItem('timeKey_customGoogleClientId');
      setGoogleClientId(customId || import.meta.env.VITE_GOOGLE_CLIENT_ID || DEFAULT_GOOGLE_CLIENT_ID);
    };

    window.addEventListener('google-client-id-changed', handleIdChange);
    window.addEventListener('storage', handleIdChange);

    return () => {
      window.removeEventListener('google-client-id-changed', handleIdChange);
      window.removeEventListener('storage', handleIdChange);
    };
  }, []);

  return (
    <GoogleOAuthProvider clientId={googleClientId}>
      <AppProvider 
        msalInstance={msalInstance} 
        googleClientId={googleClientId}
      >
        <App 
          isGoogleAuthEnabled={!!googleClientId}
          msalInstance={msalInstance}
          isMicrosoftAuthEnabled={!!MSAL_CLIENT_ID}
        />
      </AppProvider>
    </GoogleOAuthProvider>
  );
};

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <BrowserRouter>
      <MainApp />
    </BrowserRouter>
  );
}

