import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

interface ErrorBoundaryState {
  hasError: boolean;
  message: string;
}

class AppErrorBoundary extends React.Component<
  { children: React.ReactNode },
  ErrorBoundaryState
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false, message: '' };
  }

  static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
    return {
      hasError: true,
      message: error instanceof Error ? error.message : 'Unexpected runtime error.',
    };
  }

  render() {
    if (this.state.hasError) {
      return (
        <div
          style={{
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '24px',
            backgroundColor: '#141517',
            color: '#f2f3f5',
            fontFamily: 'system-ui, sans-serif',
          }}
        >
          <div
            style={{
              maxWidth: '480px',
              width: '100%',
              padding: '24px',
              borderRadius: '16px',
              background: '#191a1e',
              border: '1px solid rgba(255,255,255,0.08)',
            }}
          >
            <h1 style={{ margin: '0 0 8px', fontSize: '18px', fontWeight: 700 }}>
              Calibre encountered a runtime error
            </h1>
            <p style={{ margin: '0 0 16px', fontSize: '13px', color: '#9ea3ae' }}>
              {this.state.message}
            </p>
            <button
              type="button"
              onClick={() => window.location.reload()}
              style={{
                padding: '10px 16px',
                borderRadius: '10px',
                border: 'none',
                background: '#f2f3f5',
                color: '#111214',
                fontWeight: 600,
                cursor: 'pointer',
              }}
            >
              Reload Workbench
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  </React.StrictMode>,
);
