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

// Suppress unhandled Google AdSense TagError or cross-origin Script error exceptions in development or sandbox
if (typeof window !== 'undefined') {
  // Wrap window.adsbygoogle.push to catch internal AdSense exceptions
  (function() {
    let originalAdsbygoogle = (window as any).adsbygoogle || [];
    
    function wrapPush(obj: any) {
      if (obj && typeof obj.push === 'function' && !obj.push.__wrapped) {
        const originalPush = obj.push;
        obj.push = function(...args: any[]) {
          try {
            return originalPush.apply(this, args);
          } catch (e) {
            console.warn('Caught and suppressed adsbygoogle push error:', e);
          }
        };
        obj.push.__wrapped = true;
      }
    }

    wrapPush(originalAdsbygoogle);

    Object.defineProperty(window, 'adsbygoogle', {
      get() {
        return originalAdsbygoogle;
      },
      set(val) {
        originalAdsbygoogle = val;
        wrapPush(originalAdsbygoogle);
      },
      configurable: true
    });
  })();

  const isIgnorableScriptError = (msg?: string | null) => {
    if (!msg) return false;
    const lower = msg.toLowerCase();
    return (
      lower.includes('adsbygoogle') ||
      lower.includes('tagerror') ||
      lower.includes('script error') ||
      msg === 'Script error.'
    );
  };

  window.addEventListener('error', (event) => {
    if (isIgnorableScriptError(event?.message)) {
      event.preventDefault();
      event.stopPropagation();
    }
  }, true);

  const prevOnError = window.onerror;
  window.onerror = function(message, source, lineno, colno, error) {
    if (typeof message === 'string' && isIgnorableScriptError(message)) {
      return true; // suppresses "Script error." browser overlay/console noise
    }
    if (prevOnError) {
      return prevOnError.call(window, message, source, lineno, colno, error);
    }
    return false;
  };

  window.addEventListener('unhandledrejection', (event) => {
    const reasonMsg = event?.reason?.message || (typeof event?.reason === 'string' ? event.reason : '');
    if (isIgnorableScriptError(reasonMsg)) {
      event.preventDefault();
      event.stopPropagation();
    }
  });
}

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

