import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';

// --------------------------------------------------------------------------------
// 🌐 TRANSPARENT FETCH INTERCEPTOR FOR EXTERNAL DEPLOYMENTS (Vercel, Local, etc.)
// --------------------------------------------------------------------------------
// When the app is running on Vercel (or any host other than our Cloud Run backend container),
// we redirect all relative requests starting with '/api/' to our full-stack Cloud Run instance
// so that database connections (Supabase), emails (Nodemailer), and APIs function seamlessly!
try {
  const originalFetch = window.fetch;
  if (originalFetch) {
    Object.defineProperty(window, 'fetch', {
      configurable: true,
      writable: true,
      value: async function (input: RequestInfo | URL, init?: RequestInit) {
        let url = '';
        if (typeof input === 'string') {
          url = input;
        } else if (input instanceof URL) {
          url = input.toString();
        } else {
          url = input.url;
        }

        if (url.startsWith('/api/')) {
          const currentOrigin = window.location.origin;
          // Check if we are running in the cloud container (e.g. *.run.app) or on local port 3000
          const isLocalOrContainer = currentOrigin.includes('3000') || currentOrigin.includes('run.app');
          
          if (!isLocalOrContainer) {
            // Directs API calls to our fully operational backend container on Cloud Run!
            const backendHost = 'https://ais-dev-mpu7uexuimjwmj5n6knmp7-973831959842.asia-southeast1.run.app';
            url = `${backendHost}${url}`;
          }
        }

        if (typeof input === 'string' || input instanceof URL) {
          return originalFetch(url, init);
        } else {
          try {
            const newRequest = new Request(url, input);
            return originalFetch(newRequest, init);
          } catch {
            return originalFetch(url, init);
          }
        }
      }
    });
  }
} catch (error) {
  console.warn('[Fetch Interceptor] Unable to instrument global window.fetch safely:', error);
}
// --------------------------------------------------------------------------------

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