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

interface Props {
  children: ReactNode;
}

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

class RootErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
    error: null,
  };

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

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('AIMCE Uncaught Runtime Error:', error, errorInfo);
  }

  private handleReset = () => {
    try {
      localStorage.clear();
      sessionStorage.clear();
    } catch {}
    window.location.reload();
  };

  public render() {
    if (this.state.hasError) {
      return (
        <div style={{ minHeight: '100vh', background: '#081A38', color: '#ffffff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px', textAlign: 'center', fontFamily: 'system-ui, sans-serif' }}>
          <div style={{ width: '64px', height: '64px', borderRadius: '16px', background: 'rgba(245, 130, 32, 0.2)', border: '1px solid rgba(245, 130, 32, 0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '16px', color: '#F58220', fontSize: '32px' }}>
            ⚠
          </div>
          <h1 style={{ fontSize: '22px', fontWeight: 900, margin: '0 0 8px 0' }}>AIMCE Portal Recovery</h1>
          <p style={{ fontSize: '12px', color: '#93c5fd', maxWidth: '440px', lineHeight: 1.6, margin: '0 0 24px 0' }}>
            The application encountered a browser initialization state. Click below to clear stored data and reload cleanly.
          </p>
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', justifyContent: 'center' }}>
            <button
              onClick={() => window.location.reload()}
              style={{ padding: '10px 20px', background: '#0284C7', color: '#fff', border: 'none', borderRadius: '10px', fontWeight: 'bold', fontSize: '13px', cursor: 'pointer' }}
            >
              Reload Page
            </button>
            <button
              onClick={this.handleReset}
              style={{ padding: '10px 20px', background: '#F58220', color: '#fff', border: 'none', borderRadius: '10px', fontWeight: 'bold', fontSize: '13px', cursor: 'pointer' }}
            >
              Reset Data &amp; Reload
            </button>
          </div>
          {this.state.error && (
            <pre style={{ marginTop: '24px', padding: '12px', background: 'rgba(0,0,0,0.4)', borderRadius: '8px', color: '#fca5a5', fontSize: '11px', maxWidth: '500px', overflowX: 'auto', textAlign: 'left' }}>
              {this.state.error.toString()}
            </pre>
          )}
        </div>
      );
    }
    return this.props.children;
  }
}

// 1. Mount React FIRST to guarantee UI renders immediately
const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(
    <RootErrorBoundary>
      <App />
    </RootErrorBoundary>
  );
}

// 2. Safely register service worker in the background (NEVER crash or block initial render)
if (typeof window !== 'undefined' && 'serviceWorker' in navigator && (window.location.protocol === 'https:' || window.location.hostname === 'localhost')) {
  try {
    import('virtual:pwa-register')
      .then(({ registerSW }) => {
        registerSW({ immediate: true });
      })
      .catch((err) => {
        console.warn('PWA registration skipped or unsupported:', err);
      });
  } catch (err) {
    console.warn('PWA dynamic import error:', err);
  }
}
