import React from 'react';
import ReactDOM from 'react-dom/client';
import { Chart, registerables } from 'chart.js';
import App from './App';
import './index.css';

// Register Chart.js components
Chart.register(...registerables);

// Error boundary component
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error, errorInfo) {
    console.error('Application error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ color: 'white', padding: '20px' }}>
          <h1>Something went wrong</h1>
          <p>Please try refreshing the page. If the problem persists, contact support.</p>
          <pre style={{ color: '#ff6b6b', marginTop: '20px', padding: '10px', background: 'rgba(0,0,0,0.1)' }}>
            {this.state.error?.message}
          </pre>
        </div>
      );
    }

    return this.props.children;
  }
}

const root = document.getElementById('root');

if (!root) {
  console.error('Root element not found');
  document.body.innerHTML = `
    <div style="color: white; padding: 20px;">
      <h1>Error Initializing Application</h1>
      <p>Unable to find root element. Please refresh the page.</p>
    </div>
  `;
} else {
  try {
    ReactDOM.createRoot(root).render(
      <ErrorBoundary>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </ErrorBoundary>
    );
    console.log('Application rendered successfully');
  } catch (error) {
    console.error('Error rendering application:', error);
    root.innerHTML = `
      <div style="color: white; padding: 20px;">
        <h1>Error Loading Application</h1>
        <p>Please try refreshing the page. If the problem persists, contact support.</p>
        <pre style="color: #ff6b6b; margin-top: 20px; padding: 10px; background: rgba(0,0,0,0.1);">
          ${error.message}
        </pre>
      </div>
    `;
  }
}
