import React from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';

const rootElement = document.getElementById('root');

function Fatal({ error }) {
  return <div className="runtime-fallback"><div className="runtime-fallback-card">
    <div style={{fontWeight:900,color:'#ab9eff'}}>NaukaFlow AI</div>
    <h1>Nie udało się uruchomić interfejsu</h1>
    <p>Ten ekran jest celowy: zamiast pustej białej strony pokazuje dokładny błąd startowy.</p>
    <pre>{String(error?.stack || error?.message || error || 'Nieznany błąd')}</pre>
    <button onClick={()=>window.location.reload()}>Odśwież</button>
  </div></div>;
}

class RuntimeBoundary extends React.Component {
  constructor(props){ super(props); this.state={error:null}; }
  static getDerivedStateFromError(error){ return {error}; }
  componentDidCatch(error, info){ console.error('[NaukaFlow] React runtime error', error, info); }
  render(){ return this.state.error ? <Fatal error={this.state.error}/> : this.props.children; }
}

if (!rootElement) {
  document.body.innerHTML = '<div style="padding:24px;font-family:system-ui">NaukaFlow: brak elementu #root.</div>';
} else {
  // App is imported dynamically so module-evaluation errors are catchable.
  import('./App.jsx')
    .then(({ default: App }) => {
      createRoot(rootElement).render(<RuntimeBoundary><App/></RuntimeBoundary>);
    })
    .catch((error) => {
      console.error('[NaukaFlow] Failed to import App.jsx', error);
      createRoot(rootElement).render(<Fatal error={error}/>);
    });
}
