import React, { Component, ErrorInfo, ReactNode } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null }> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-amber-50 p-8 font-sans text-center">
          <div className="max-w-md bg-white p-8 rounded-3xl shadow-xl border-2 border-amber-200">
            <h1 className="text-4xl font-bold text-amber-500 mb-4 font-display">Oh fudge! 🍬</h1>
            <p className="text-gray-600 mb-6 font-medium">
              We dropped the lollipop. Something went wrong while loading the shop.
            </p>
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-200 text-left mb-6 overflow-hidden">
               <p className="text-xs text-gray-400 font-mono mb-1">Error Details:</p>
               <pre className="text-xs text-red-500 overflow-auto whitespace-pre-wrap font-mono">
                {this.state.error?.message || "Unknown error"}
              </pre>
            </div>
            <button 
              onClick={() => window.location.reload()}
              className="bg-amber-400 text-white px-8 py-3 rounded-full font-bold hover:bg-amber-500 transition-colors shadow-lg"
            >
              Try Reloading
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  </React.StrictMode>
);