import { Component, StrictMode, type ErrorInfo, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import { AuthProvider } from '@/lib/auth';
import './index.css';

type ErrorBoundaryState = { hasError: boolean };

class AppErrorBoundary extends Component<{ children: ReactNode }, ErrorBoundaryState> {
  state: ErrorBoundaryState = { hasError: false };

  static getDerivedStateFromError(): ErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('Application render failed', error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-neutral-50 p-6 dark:bg-neutral-900">
          <div className="w-full max-w-md rounded-2xl border border-red-200 bg-white p-8 text-center shadow-sm dark:bg-neutral-800 dark:border-red-900">
            <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-50 text-red-500 dark:bg-red-900/30">!</div>
            <h1 className="text-xl font-semibold text-neutral-800 dark:text-neutral-100">Die Reiseplanung konnte nicht geladen werden</h1>
            <p className="mt-2 text-sm leading-6 text-neutral-500 dark:text-neutral-400">Bitte lade die Seite neu. Wenn das Problem bleibt, prüfe die Verbindung zur Reiseplanung.</p>
            <button
              onClick={() => window.location.reload()}
              className="mt-6 rounded-xl bg-arctic-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-arctic-600"
            >
              Seite neu laden
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <AppErrorBoundary>
      <AuthProvider>
        <App />
      </AuthProvider>
    </AppErrorBoundary>
  </StrictMode>
);
