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

interface ErrorBoundaryState {
  hasError: boolean;
  message: string;
}

class RootErrorBoundary extends React.Component<
  { children: React.ReactNode },
  ErrorBoundaryState
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false, message: '' };
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return {
      hasError: true,
      message: error?.message || 'Unexpected application error',
    };
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-[#040b07] text-stone-200 flex flex-col items-center justify-center p-6 text-center">
          <div className="max-w-md w-full bg-[#07160e] border border-emerald-500/30 rounded-2xl p-6 shadow-2xl">
            <h1 className="text-xl font-black text-white mb-2">GB STUDY</h1>
            <p className="text-sm text-stone-400 mb-4">
              Something went wrong while loading the page.
            </p>
            <p className="text-xs text-red-300 bg-red-500/10 border border-red-500/20 rounded-xl p-3 mb-5 break-words">
              {this.state.message}
            </p>
            <button
              onClick={() => {
                try {
                  localStorage.removeItem('studybee_wishlist');
                  localStorage.removeItem('gbstudy_wishlist');
                } catch {
                  // ignore
                }
                window.location.reload();
              }}
              className="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold uppercase tracking-wider cursor-pointer"
            >
              Reload GB STUDY
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

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