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

// Global Fetch Interceptor for Security Shield (درع الحماية) Alerts
const originalFetch = window.fetch;
Object.defineProperty(window, 'fetch', {
  configurable: true,
  writable: true,
  value: async (...args: Parameters<typeof originalFetch>) => {
    const response = await originalFetch(...args);
    
    // Clone the response so we can read the JSON without consuming the original stream
    if (response.headers.get('content-type')?.includes('application/json')) {
      try {
        const clone = response.clone();
        const data = await clone.json();
        if (data && typeof data.error === 'string' && data.error.includes('درع الحماية')) {
          window.dispatchEvent(new CustomEvent('security-shield-alert', { detail: data.error }));
        }
      } catch (e) {
        // Ignore JSON parse errors for clone
      }
    }
    
    return response;
  }
});

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

