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

class StartupBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
  state = { failed: false };
  static getDerivedStateFromError() { return { failed: true }; }
  componentDidCatch(error: unknown) { console.error('WorkSuite rendering failed', error); }
  render() {
    if (this.state.failed) return (
      <main role="alert" style={{ padding: '2rem', maxWidth: '38rem', margin: '10vh auto', color: '#fff', background: '#081820' }}>
        <h1>DREMEVO WorkSuite</h1>
        <p>The application could not start. Please reload to try again.</p>
        <p>Diagnostic reference: WS-RENDER</p>
        <button type="button" onClick={() => window.location.reload()} style={{ marginTop: '1rem', padding: '0.8rem 1.2rem', background: '#a4f000', color: '#071108', borderRadius: '0.5rem' }}>Reload WorkSuite</button>
      </main>
    );
    return this.props.children;
  }
}

const container = document.getElementById('root');
if (container) {
  import('./App.tsx').then(({ default: App }) => {
    createRoot(container).render(<StartupBoundary><App /></StartupBoundary>);
  }).catch((error: unknown) => {
    console.error('WorkSuite startup bundle failed', error);
    const status = document.getElementById('worksuite-startup-status');
    if (status) status.textContent = 'Unable to load the application. Reload and try again. Diagnostic reference: WS-BOOT.';
  });
}
