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

function renderApp(rootEl: HTMLElement) {
  createRoot(rootEl).render(
    <StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </StrictMode>
  );
}

function boot() {
  const rootEl = document.getElementById("root");

  if (rootEl) {
    renderApp(rootEl);
    return;
  }

  // Root element not ready yet — poll until it exists (never gives up).
  let attempts = 0;
  const timer = window.setInterval(() => {
    const el = document.getElementById("root");
    if (el) {
      window.clearInterval(timer);
      renderApp(el);
      return;
    }
    attempts += 1;
    if (attempts > 50) {
      window.clearInterval(timer);
      // Last resort: create the node ourselves.
      const created = document.createElement("div");
      created.id = "root";
      document.body.appendChild(created);
      renderApp(created);
    }
  }, 100);
}

// Run after the DOM is ready in all cases.
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", boot, { once: true });
} else {
  boot();
}
