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

// Intercept all fetch requests globally
const originalFetch = window.fetch.bind(window);
try {
  Object.defineProperty(window, 'fetch', {
    value: function (input: RequestInfo | URL, init?: RequestInit) {
      let urlStr = '';
      if (typeof input === 'string') {
        urlStr = input;
      } else if (input instanceof URL) {
        urlStr = input.toString();
      } else if (input instanceof Request) {
        urlStr = input.url;
      }

      // Intercept any local relative API requests starting with /api/
      if (urlStr.startsWith('/api/') || urlStr.startsWith(window.location.origin + '/api/')) {
        const hostname = window.location.hostname;
        // Keep local sandbox / dev preview requests routing relative, prefix production deployment
        const isLocalOrSandbox = hostname === 'localhost' || hostname === '127.0.0.1' || hostname.includes('run.app');
        const apiBase = isLocalOrSandbox ? '' : 'https://api.growmoneywithus.in';
        
        if (apiBase) {
          const pathSuffix = urlStr.startsWith(window.location.origin)
            ? urlStr.slice(window.location.origin.length)
            : urlStr;
          
          const newUrl = apiBase + pathSuffix;
          
          if (typeof input === 'string') {
            return originalFetch(newUrl, init);
          } else if (input instanceof URL) {
            return originalFetch(new URL(newUrl), init);
          } else if (input instanceof Request) {
            const newRequest = new Request(newUrl, input);
            return originalFetch(newRequest, init);
          }
        }
      }
      return originalFetch(input, init);
    },
    writable: true,
    configurable: true,
    enumerable: true
  });
} catch (err) {
  console.error('Could not override window.fetch with defineProperty:', err);
}

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

