import { Component, StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

class AppErrorBoundary extends Component {
  constructor(props) {
    super(props)
    this.state = { error: null }
  }

  static getDerivedStateFromError(error) {
    return { error }
  }

  componentDidCatch(error, info) {
    console.error('App crashed during render.', error, info)
  }

  render() {
    if (this.state.error) {
      return (
        <div
          style={{
            minHeight: '100vh',
            padding: '24px',
            background: '#fff7f7',
            color: '#7f1d1d',
            fontFamily:
              'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
          }}
        >
          <div
            style={{
              maxWidth: '960px',
              margin: '0 auto',
              background: '#ffffff',
              border: '1px solid #fecaca',
              borderRadius: '12px',
              padding: '20px',
              boxShadow: '0 10px 30px rgba(127, 29, 29, 0.08)',
            }}
          >
            <p style={{ margin: 0, fontSize: '12px', fontWeight: 700, letterSpacing: '0.08em' }}>
              RUNTIME ERROR
            </p>
            <h1 style={{ margin: '10px 0 0', fontSize: '24px', color: '#991b1b' }}>
              App render crash ho gaya
            </h1>
            <p style={{ margin: '12px 0 0', color: '#7f1d1d' }}>
              Error: {this.state.error?.message || 'Unknown error'}
            </p>
            {this.state.error?.stack ? (
              <pre
                style={{
                  marginTop: '16px',
                  padding: '16px',
                  overflow: 'auto',
                  whiteSpace: 'pre-wrap',
                  borderRadius: '8px',
                  background: '#111827',
                  color: '#f9fafb',
                  fontSize: '12px',
                }}
              >
                {this.state.error.stack}
              </pre>
            ) : null}
          </div>
        </div>
      )
    }

    return this.props.children
  }
}

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