import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import './index.css';
import { DataProvider } from './store/DataContext';

// Global Error Boundary to prevent white screen crashes and allow instant data recovery
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMsg: '' };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, errorMsg: error?.message || String(error) };
  }

  componentDidCatch(error, errorInfo) {
    console.error('GlucoTrack Runtime Crash Caught by Error Boundary:', error, errorInfo);
  }

  handleResetAndReload = () => {
    try {
      localStorage.clear();
    } catch (e) {
      console.error(e);
    }
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#F7F4EC', padding: '20px' }}>
          <div style={{ maxWidth: '500px', background: '#FFFDF8', border: '1px solid #DAD4C2', borderRadius: '14px', padding: '32px', textAlign: 'center', boxShadow: '0 16px 40px rgba(0,0,0,0.08)' }}>
            <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: '24px', color: '#B8503F', margin: '0 0 12px' }}>⚠️ Application Error Encountered</h2>
            <p style={{ fontSize: '14px', color: '#5B6156', lineHeight: 1.5, margin: '0 0 20px' }}>
              Your browser may have encountered incompatible or corrupted cached storage from an older build.
            </p>
            <div style={{ background: '#F2DAD4', color: '#B8503F', padding: '10px 14px', borderRadius: '8px', fontSize: '12px', fontFamily: 'monospace', marginBottom: '24px', textAlign: 'left', overflowX: 'auto' }}>
              Error: {this.state.errorMsg || 'Unknown frontend crash'}
            </div>
            <button
              onClick={this.handleResetAndReload}
              style={{ background: '#5B7A5B', color: '#fff', border: 'none', padding: '12px 22px', borderRadius: '10px', fontSize: '15px', fontWeight: '600', cursor: 'pointer' }}
            >
              🔄 Clear Cache & Reload App
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

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