import React, { Component, type ErrorInfo, type ReactNode } from 'react';
import ReactDOM from 'react-dom/client';
import { Box, Typography, Button } from '@mui/material';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AppThemeProvider } from './theme/ThemeContext';
import App from './App';

console.log("[Renderer] Initializing React App...");

window.addEventListener('error', (event) => {
  console.error("[Global Error]", event.error);
});

window.addEventListener('unhandledrejection', (event) => {
  console.error("[Unhandled Rejection]", event.reason);
});

class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean, error: Error | null }> {
  constructor(props: any) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("[Renderer] CRASH DETECTED:", error);
    console.error("[Renderer] Error Info:", errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <Box sx={{ p: 4, textAlign: 'center', backgroundColor: '#171a21', color: 'white', minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
          <Typography variant="h4" color="error" gutterBottom>Application Error</Typography>
          <Typography variant="body1" sx={{ mb: 2, opacity: 0.8, maxWidth: '600px' }}>{this.state.error?.stack || this.state.error?.message}</Typography>
          <Button variant="contained" color="primary" onClick={() => window.location.reload()}>Retry App</Button>
        </Box>
      );
    }
    return this.props.children;
  }
}

const queryClient = new QueryClient();

const rootElement = document.getElementById('root');
if (!rootElement) {
  console.error("[Renderer] Failed to find #root element!");
} else {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <ErrorBoundary>
        <QueryClientProvider client={queryClient}>
          <AppThemeProvider>
            <App />
          </AppThemeProvider>
        </QueryClientProvider>
      </ErrorBoundary>
    </React.StrictMode>
  );
  console.log("[Renderer] Render initiated.");
}
