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

interface ErrorBoundaryProps {
  children: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
  errorInfo: ErrorInfo | null;
}

class RootErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  public state: ErrorBoundaryState = {
    hasError: false,
    error: null,
    errorInfo: null,
  };

  public static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Fatal Application Error caught by RootErrorBoundary:', error, errorInfo);
    this.setState({ errorInfo });
  }

  private handleReset = () => {
    try {
      localStorage.removeItem('sandanuwan_science_students_v5');
      localStorage.removeItem('sandanuwan_science_institute_v5');
    } catch (e) {
      console.warn('Storage cleanup failed', e);
    }
    window.location.reload();
  };

  public render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-slate-900 text-white flex items-center justify-center p-6 font-sans">
          <div className="max-w-lg w-full bg-slate-800/90 border border-red-500/30 rounded-2xl p-6 sm:p-8 shadow-2xl backdrop-blur-xl text-center">
            <div className="w-16 h-16 bg-red-500/20 text-red-400 rounded-2xl flex items-center justify-center mx-auto mb-4 border border-red-500/30">
              <span className="text-3xl">⚠️</span>
            </div>
            <h1 className="text-xl sm:text-2xl font-bold text-white mb-2">
              පද්ධතිය ධාවනය වීමේ දෝෂයක් (System Runtime Error)
            </h1>
            <p className="text-slate-300 text-sm mb-6 leading-relaxed">
              Sandanuwan Sir Science Portal එක Load වීමේදී දෝෂයක් හටගැණුනි. පහත විස්තරය පරීක්ෂා කරන්න:
            </p>

            <div className="bg-slate-950/80 border border-slate-700/60 rounded-xl p-4 text-left mb-6 overflow-x-auto text-xs font-mono text-red-300">
              <p className="font-bold text-red-400 mb-1">{this.state.error?.name || 'Error'}: {this.state.error?.message || 'Unknown runtime error'}</p>
              {this.state.error?.stack && (
                <pre className="text-slate-400 whitespace-pre-wrap text-[11px] mt-2 max-h-36 overflow-y-auto">
                  {this.state.error.stack}
                </pre>
              )}
            </div>

            <div className="flex flex-col sm:flex-row gap-3">
              <button
                onClick={() => window.location.reload()}
                className="flex-1 py-3 px-4 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold rounded-xl transition shadow-lg shadow-indigo-600/30 cursor-pointer"
              >
                🔄 Reload Page (යළි උත්සාහ කරන්න)
              </button>
              <button
                onClick={this.handleReset}
                className="py-3 px-4 bg-slate-700 hover:bg-slate-600 text-slate-200 font-medium rounded-xl transition cursor-pointer"
                title="Clears local cache and reloads"
              >
                🧹 Reset Cache
              </button>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootElement = document.getElementById('root');
if (rootElement) {
  createRoot(rootElement).render(
    <RootErrorBoundary>
      <App />
    </RootErrorBoundary>
  );
}
