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

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

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

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

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("Application Error:", error, errorInfo);
  }

  render() {
    const state = (this as unknown as { state: ErrorBoundaryState; props: ErrorBoundaryProps }).state;
    const props = (this as unknown as { state: ErrorBoundaryState; props: ErrorBoundaryProps }).props;
    if (state.hasError) {
      return (
        <div style={{ padding: '32px', fontFamily: 'system-ui, sans-serif', maxWidth: '600px', margin: '40px auto', border: '1px solid #e2e8f0', borderRadius: '12px', background: '#ffffff', color: '#1e293b' }}>
          <h2 style={{ fontSize: '20px', fontWeight: 600, color: '#dc2626', marginBottom: '8px' }}>Application Error</h2>
          <p style={{ fontSize: '14px', color: '#64748b', marginBottom: '16px' }}>An error occurred while loading the application.</p>
          <pre style={{ background: '#f8fafc', padding: '12px', borderRadius: '8px', fontSize: '13px', overflowX: 'auto', border: '1px solid #cbd5e1' }}>
            {state.error?.message || String(state.error)}
          </pre>
          <button 
            onClick={() => window.location.reload()}
            style={{ marginTop: '16px', padding: '8px 16px', background: '#0284c7', color: '#ffffff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 500 }}
          >
            Reload Page
          </button>
        </div>
      );
    }
    return props.children;
  }
}

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

