import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/react';
import { ErrorBoundary } from './components/ErrorBoundary.tsx';

// Strategic diagnostic boot logging
try {
  if (typeof window !== 'undefined') {
    console.group('Premium UI Core Diagnostics');
    console.log('[System] Initialization started at:', new Date().toISOString());
    console.log('[System] User Agent:', navigator.userAgent);
    console.log('[System] Environment:', (import.meta as any).env?.MODE || 'production');
    console.log('[System] Host:', window.location.host);
    console.log('[System] Path:', window.location.pathname);
    console.log('[System] Protocols:', {
      secure: window.location.protocol === 'https:',
      iframe: window.self !== window.top,
      serviceWorker: 'serviceWorker' in navigator,
      indexedDB: !!window.indexedDB,
    });
    console.groupEnd();
  }
} catch (logErr) {
  console.warn('Diagnostics setup skipped:', logErr);
}

try {
  const rootElement = document.getElementById('root');
  if (!rootElement) {
    throw new Error('Crucial DOM anchor "#root" element could not be found.');
  }

  console.log('[DOM] HTML root mount target located.');

  createRoot(rootElement).render(
    <StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
      <Analytics />
      <SpeedInsights />
    </StrictMode>,
  );

  console.log('[React] Root tree successfully rendered.');
} catch (error: any) {
  console.error('[Fatal Bootstrap Level Exception]:', error);
  // Fail-Safe fallback display directly on DOM in case React mounting itself crashes hard
  if (typeof document !== 'undefined') {
    const errorContainer = document.createElement('div');
    errorContainer.style.cssText = 'position:fixed;inset:0;background:#121212;color:#ff8a00;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;z-index:99999;';
    errorContainer.innerHTML = `
      <div style="border:1px solid #ff8a00;border-radius:24px;background:#1a1a1a;padding:40px;max-width:500px;box-shadow:0 10px 40px rgba(255,138,0,0.2);">
        <h2 style="margin:0 0 10px 0;font-size:24px;letter-spacing:1px;color:#fff;">BARBEARIA MIRANDA</h2>
        <p style="color:#a0a0a0;font-size:14px;margin-bottom:24px;">Falha catastrófica durante a inicialização do renderizador principal.</p>
        <div style="background:#000;color:#f87171;font-family:monospace;font-size:12px;padding:15px;border-radius:12px;text-align:left;overflow-x:auto;margin-bottom:24px;word-break:break-all;">
          ${error?.message || String(error)}
        </div>
        <button onclick="window.location.reload()" style="background:#ff8a00;color:#fff;border:none;padding:12px 24px;border-radius:99px;font-weight:bold;cursor:pointer;">Tentar Novamente</button>
      </div>
    `;
    document.body.appendChild(errorContainer);
  }
}
