import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App.tsx';
import { ErrorBoundary } from './components/ErrorBoundary';
import './index.css';
import { logger } from './lib/logger';
import { initSentry } from './lib/sentry';

initSentry();

// Clear stale-chunk reload guard on successful app boot
sessionStorage.removeItem('clx_chunk_reload_attempted');

async function registerServiceWorker() {
  if (!('serviceWorker' in navigator)) return;
  try {
    await navigator.serviceWorker.register('/sw.js', { scope: '/' });
  } catch {
    // SW não disponível (HTTP, restrição de browser, etc.) — app funciona sem ele
  }
}

void registerServiceWorker();

function revealAppShell() {
  document.documentElement.classList.add('clx-app-ready');
}

function renderBootstrapFallback(reason: string) {
  revealAppShell();
  const root = document.getElementById('root');
  if (!root || root.childElementCount > 0 || root.textContent?.trim()) return;

  const container = document.createElement('div');
  container.setAttribute(
    'style',
    'min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;background:#f8fafc;font-family:Inter,system-ui,sans-serif;'
  );

  const card = document.createElement('div');
  card.setAttribute(
    'style',
    'width:100%;max-width:560px;border:1px solid #dbe3ef;border-radius:20px;background:#ffffff;padding:24px;color:#0f172a;'
  );

  const title = document.createElement('h1');
  title.textContent = 'Não foi possível iniciar o ClinNexus';
  title.setAttribute('style', 'margin:0 0 12px;font-size:20px;line-height:1.2;');

  const detail = document.createElement('p');
  detail.textContent = reason;
  detail.setAttribute('style', 'margin:0 0 8px;font-size:14px;line-height:1.5;color:#334155;');

  const hint = document.createElement('p');
  hint.textContent = 'Recarregue a página. Se persistir, limpe os dados do site e desative extensões para este domínio.';
  hint.setAttribute('style', 'margin:0;font-size:13px;line-height:1.5;color:#475569;');

  card.append(title, detail, hint);
  container.appendChild(card);
  root.replaceChildren(container);
}

function installBootstrapGuards() {
  window.addEventListener('error', (event) => {
    if (!document.documentElement.classList.contains('clx-app-ready')) {
      renderBootstrapFallback(event.message || 'Erro ao carregar arquivos da aplicação.');
    }
  });

  window.addEventListener('unhandledrejection', (event) => {
    if (!document.documentElement.classList.contains('clx-app-ready')) {
      const reason =
        event.reason instanceof Error
          ? event.reason.message
          : typeof event.reason === 'string'
            ? event.reason
            : 'Falha inesperada durante a inicialização.';
      renderBootstrapFallback(reason);
    }
  });
}

installBootstrapGuards();

function revealAppWhenStylesAreReady() {
  const maxAttempts = 120;
  let attempts = 0;

  const reveal = () => {
    const cssReady = getComputedStyle(document.documentElement)
      .getPropertyValue('--clx-css-ready')
      .trim() === '1';

    if (cssReady) {
      revealAppShell();
      return;
    }

    attempts += 1;
    if (attempts < maxAttempts) {
      requestAnimationFrame(reveal);
    } else {
      renderBootstrapFallback('A aplicação excedeu o tempo esperado de inicialização.');
    }
  };

  requestAnimationFrame(reveal);
}

const rootEl = document.getElementById('root');
if (!rootEl) {
  revealAppShell();
  document.body.innerHTML = '<div style="padding:24px;font-family:system-ui;">Erro: elemento #root não encontrado. Abra o site via <strong>http://localhost:3000</strong> após rodar <code>npm run dev</code>.</div>';
} else {
  try {
    createRoot(rootEl).render(
      <StrictMode>
        <ErrorBoundary>
          <BrowserRouter>
            <App />
          </BrowserRouter>
        </ErrorBoundary>
      </StrictMode>,
    );
    revealAppWhenStylesAreReady();
  } catch (err) {
    revealAppShell();
    const msg = err instanceof Error ? err.message : String(err);
    const container = document.createElement('div');
    container.setAttribute('style', 'padding:24px;font-family:system-ui;max-width:560px;margin:0 auto;');
    const title = document.createElement('h2');
    title.textContent = 'Erro ao iniciar';
    const detail = document.createElement('p');
    detail.textContent = msg;
    const hint = document.createElement('p');
    hint.textContent = 'Abra o Console (F12) para mais detalhes.';
    container.append(title, detail, hint);
    rootEl.replaceChildren(container);
    logger.error('ClinNexus bootstrap error:', err);
  }
}
