import { Component, type ErrorInfo, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

/**
 * Prevent an unexpected client-side exception from presenting as a completely
 * blank page in static deployments. The error is intentionally shown in-page
 * so deployment/runtime failures are diagnosable without a backend.
 */
class AppErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
  state: { error: Error | null } = { error: null };

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('[First State Budget Lab] Application render failed:', error, info.componentStack);
  }

  render() {
    if (this.state.error) {
      return (
        <main style={{ minHeight: '100vh', background: '#f8fafc', color: '#0f172a', padding: 'clamp(24px, 6vw, 72px)', fontFamily: 'system-ui, sans-serif' }}>
          <section style={{ maxWidth: 760, margin: '0 auto', background: '#fff', border: '1px solid #cbd5e1', borderRadius: 16, padding: 28, boxShadow: '0 12px 36px rgba(15,23,42,.08)' }}>
            <p style={{ color: '#0f766e', fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', fontSize: 12 }}>First State Budget Lab</p>
            <h1 style={{ fontSize: 30, lineHeight: 1.2, margin: '12px 0' }}>The application could not start</h1>
            <p style={{ lineHeight: 1.6, color: '#475569' }}>The page loaded, but the application encountered a runtime error. Reload the page once. If this continues, share the diagnostic message below with the site maintainer.</p>
            <pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', background: '#f1f5f9', borderRadius: 10, padding: 16, fontSize: 13, lineHeight: 1.5 }}>{this.state.error.message || 'Unknown application error'}</pre>
            <button onClick={() => window.location.reload()} style={{ marginTop: 8, border: 0, borderRadius: 8, padding: '11px 16px', background: '#0f2942', color: '#fff', fontWeight: 600, cursor: 'pointer' }}>Reload application</button>
          </section>
        </main>
      );
    }
    return this.props.children;
  }
}

const rootElement = document.getElementById('root');
if (!rootElement) {
  document.body.innerHTML = '<main style="font-family:system-ui,sans-serif;padding:3rem;color:#0f172a"><h1>First State Budget Lab</h1><p>Startup failed: the page is missing its application root element. Check that the deployed index.html is the project entry page.</p></main>';
} else {
  createRoot(rootElement).render(
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>,
  );
}
