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

// Garante que o elemento root exista na árvore DOM
const rootElement =
  document.getElementById('root') ||
  (() => {
    const el = document.createElement('div');
    el.id = 'root';
    document.body.appendChild(el);
    return el;
  })();

try {
  const root = createRoot(rootElement);
  root.render(
    <StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </StrictMode>,
  );
} catch (err) {
  console.error('Falha crítica na montagem do React:', err);
  rootElement.innerHTML = `
    <div style="min-height: 100vh; background: #020617; color: #f8fafc; display: flex; align-items: center; justify-content: center; font-family: sans-serif; padding: 20px;">
      <div style="background: #0f172a; border: 1px solid #334155; border-radius: 16px; max-width: 500px; width: 100%; padding: 24px; text-align: center;">
        <h2 style="color: #f59e0b; margin-top: 0; font-size: 20px;">RICARICO-FOODS</h2>
        <p style="color: #cbd5e1; font-size: 14px; line-height: 1.6;">Ocorreu uma falha ao renderizar o aplicativo. Por favor, recarregue a página.</p>
        <button onclick="window.location.reload()" style="background: #d97706; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; margin-top: 12px;">Recarregar Página</button>
      </div>
    </div>
  `;
}
