import { createRoot } from 'react-dom/client';
import App from './App';
import { i18nReady } from './i18n';
import { BugsinkErrorBoundary, initBugsink } from './lib/bugsink';
import './index.css';
import './hooks/usePlausible';

initBugsink();

const container = document.getElementById('root');
if (!container) {
  throw new Error('Root element not found');
}
const root = container;

function AppErrorFallback() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-warm-50 px-6 text-center text-warm-900 dark:bg-navy-950 dark:text-warm-100">
      <div>
        <h1 className="text-xl font-semibold">Something went wrong</h1>
        <p className="mt-2 text-sm text-warm-600 dark:text-warm-300">
          Refresh the page to try again.
        </p>
      </div>
    </div>
  );
}

function renderApp() {
  const hasPrerenderedMarkup = root.children.length > 0;

  if (hasPrerenderedMarkup) {
    root.textContent = '';
  }
  root.removeAttribute('data-prerender-path');

  createRoot(root).render(
    <BugsinkErrorBoundary fallback={<AppErrorFallback />}>
      <App />
    </BugsinkErrorBoundary>
  );
}

void i18nReady.then(renderApp);
