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

// Safe environmental polyfills for automated runners or test environments that lack full DOM API features
if (typeof window !== "undefined") {
  if (typeof window.scrollTo !== "function") {
    window.scrollTo = (() => {}) as any;
  }
  if (typeof (window as any).ResizeObserver === "undefined") {
    (window as any).ResizeObserver = class ResizeObserver {
      observe() {}
      unobserve() {}
      disconnect() {}
    };
  }
  if (typeof (window as any).IntersectionObserver === "undefined") {
    (window as any).IntersectionObserver = class IntersectionObserver {
      observe() {}
      unobserve() {}
      disconnect() {}
    };
  }
  if (typeof window.matchMedia !== "function") {
    window.matchMedia = ((query: string) => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: () => {},
      removeListener: () => {},
      addEventListener: () => {},
      removeEventListener: () => {},
      dispatchEvent: () => false,
    })) as any;
  }
}
if (typeof Element !== "undefined") {
  if (typeof Element.prototype.scrollIntoView !== "function") {
    Element.prototype.scrollIntoView = (() => {}) as any;
  }
}

try {
  createRoot(document.getElementById('root')!).render(
    <StrictMode>
      <App />
    </StrictMode>,
  );
} catch (error: any) {
  console.error("Initialization error captured:", error);
  if (typeof document !== "undefined") {
    const div = document.createElement("div");
    div.style.padding = "45px";
    div.style.background = "#fff5f5";
    div.style.color = "#c53030";
    div.style.fontFamily = "monospace";
    div.style.whiteSpace = "pre-wrap";
    div.style.position = "fixed";
    div.style.top = "0";
    div.style.left = "0";
    div.style.width = "100%";
    div.style.height = "100%";
    div.style.zIndex = "999999";
    div.innerHTML = `
      <div style="max-width: 800px; margin: 30px auto; padding: 24px; border: 1px solid #feb2b2; border-radius: 8px; background: white; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
        <h2 style="margin-top: 0; color: #9b2c2c;">Runtime Initialization Failed</h2>
        <p style="font-weight: bold; font-size: 16px;">${error?.message || error}</p>
        <pre style="background: #edf2f7; padding: 16px; border-radius: 4px; overflow-x: auto; font-size: 14px;">${error?.stack || 'No stack trace available'}</pre>
      </div>
    `;
    document.body.appendChild(div);
  }
}

