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

// Safe global mock for window.alert and window.confirm in sandboxed iframe environments
// This prevents uncaught SecurityErrors and "Script error." browser blocks when interactive dialogs are triggered
if (typeof window !== "undefined") {
  window.alert = (message: any) => {
    console.warn("[AAMS Sandboxed Alert Override]:", message);
    const event = new CustomEvent("aams-alert", { detail: String(message) });
    window.dispatchEvent(event);
  };

  window.confirm = (message: any) => {
    console.warn("[AAMS Sandboxed Confirm Override]: Synchronous confirmation is disabled for security.", message);
    window.dispatchEvent(new CustomEvent("aams-confirm", {
      detail: {
        message: String(message) + " (Synchronous action blocked for security. Please use interactive on-screen controls.)",
        onConfirm: () => {},
        isReadOnly: true
      }
    }));
    return false;
  };

  // Safe error interceptor targeting ONLY cross-origin iframe sandbox errors and generic "Script error." references
  const targetSuppress = (msg: any, src: any) => {
    const message = String(msg || "");
    const source = String(src || "");
    const isScriptError = message === "Script error." || message.indexOf("Script error") > -1;
    const isSandboxError = !source && (message === "" || message === "Script error.");
    return isScriptError || isSandboxError;
  };

  window.addEventListener("error", (event) => {
    if (targetSuppress(event.message, event.filename)) {
      console.warn("[AAMS Sandboxed Error Filtered]:", event.message);
      event.preventDefault();
      event.stopPropagation();
    }
  }, true);

  const prevOnError = window.onerror;
  window.onerror = function(message, source, lineno, colno, error) {
    if (targetSuppress(message, source)) {
      console.warn("[AAMS Sandboxed Error Filtered via onerror]:", message);
      return true; // Suppress only these generic cross-origin sandbox errors
    }
    if (prevOnError) {
      return prevOnError.apply(window, [message, source, lineno, colno, error]);
    }
    return false; // Let all other real errors bubble up normally
  };
}

import { AuthProvider } from "./contexts/AuthContext.tsx";
import { BrowserRouter } from "react-router-dom";
import AppErrorBoundary from "./components/AppErrorBoundary.tsx";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AppErrorBoundary>
      <AuthProvider>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </AuthProvider>
    </AppErrorBoundary>
  </StrictMode>,
);
