// ============================================================================
// BOOTSTRAP: index.jsx
// Inicializa o Root do React 18 e encapsula no FinanceProvider
// ============================================================================

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, errorInfo) {
    console.error("ErrorBoundary detectou erro:", error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div className="max-w-xl mx-auto my-12 p-6 rounded-xl border border-zinc-200 bg-white shadow-sm font-sans">
          <div className="flex items-center gap-2 mb-3">
            <span className="text-xl">⚠️</span>
            <h3 className="text-base font-bold text-zinc-950">Error al cargar el componente</h3>
          </div>
          <p className="text-xs text-zinc-500 mb-3">
            Ocurrió un error en la renderización de un elemento de la pantalla:
          </p>
          <pre className="p-3 rounded bg-zinc-50 border border-zinc-200 text-rose-600 text-[11px] font-mono overflow-x-auto">
            {this.state.error?.message || String(this.state.error)}
          </pre>
          <button 
            onClick={() => window.location.reload()} 
            className="mt-4 px-4 py-2 bg-zinc-900 text-white rounded-md text-xs font-semibold hover:bg-zinc-800"
          >
            Recargar Aplicación
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <ErrorBoundary>
      <window.FinanceProvider>
        <window.App />
      </window.FinanceProvider>
    </ErrorBoundary>
  );
}
