import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./App.js";
import { ErrorBoundary } from "./ErrorBoundary.js";
import { installDevFetchInterceptor } from "./lib/devFetch.js";
import "./index.css";

// --------------------------------------------------------------------
// Global error capture (GRO-2094).
//
// Symptom: React root stays empty at /login — bundle parses, no console
// errors, no error boundary fallback. Some failure is being swallowed
// before it reaches React's commit phase. These listeners make sure any
// thrown error or unhandled promise rejection is at least visible in
// the console (and in the Playwright network/console log) instead of
// vanishing into the void.
// --------------------------------------------------------------------
function reportGlobalError(kind: string, payload: unknown): void {
  // eslint-disable-next-line no-console
  console.error(`[${kind}]`, payload);
}

window.addEventListener("error", (event) => {
  reportGlobalError("window.error", {
    message: event.message,
    filename: event.filename,
    lineno: event.lineno,
    colno: event.colno,
    error: event.error,
  });
});

window.addEventListener("unhandledrejection", (event) => {
  reportGlobalError("unhandledrejection", {
    reason: event.reason,
  });
});

installDevFetchInterceptor();

const root = document.getElementById("root");
if (!root) throw new Error("Root element not found");

createRoot(root).render(
  <StrictMode>
    <ErrorBoundary>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </ErrorBoundary>
  </StrictMode>
);
