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

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      hasError: false,
      error: null
    };
  }

  public static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught client-side error:", error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return (
        <div style={{
          fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          padding: '30px',
          maxWidth: '600px',
          margin: '50px auto',
          border: '1px solid #fed7d7',
          borderRadius: '8px',
          backgroundColor: '#fffaf0',
          color: '#2d3748',
          boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
        }}>
          <h2 style={{ color: '#c53030', marginTop: 0, fontSize: '20px' }}>Something went wrong (Client-side Crash)</h2>
          <p style={{ fontSize: '14px', lineHeight: '1.5' }}>The web application crashed while rendering. This could be due to a browser incompatibility, a missing script, or a runtime JavaScript error.</p>
          <div style={{ backgroundColor: '#2d3748', color: '#fff', padding: '15px', borderRadius: '4px', overflowX: 'auto', margin: '20px 0' }}>
            <pre style={{ margin: 0, fontFamily: 'monospace', fontSize: '12px' }}>{this.state.error?.stack || this.state.error?.toString() || 'Unknown Error'}</pre>
          </div>
          <button 
            onClick={() => window.location.reload()}
            style={{
              backgroundColor: '#3182ce',
              color: '#fff',
              border: 'none',
              padding: '10px 16px',
              borderRadius: '4px',
              cursor: 'pointer',
              fontWeight: 'bold',
              fontSize: '14px'
            }}
          >
            Reload Page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

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