import React, {StrictMode, type ErrorInfo, type 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;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState;
  props: ErrorBoundaryProps;

  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("ErrorBoundary caught an error", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{
          padding: "2rem",
          maxWidth: "40rem",
          margin: "4rem auto",
          backgroundColor: "#fef2f2",
          border: "1px solid #fca5a5",
          borderRadius: "0.5rem",
          fontFamily: "ui-sans-serif, system-ui, sans-serif"
        }}>
          <h1 style={{ fontSize: "1.5rem", fontWeight: "bold", color: "#991b1b", marginBottom: "0.5rem" }}>
            Application Error
          </h1>
          <p style={{ color: "#7f1d1d", fontSize: "0.875rem", marginBottom: "1rem" }}>
            An unexpected error occurred while rendering the application interface.
          </p>
          <pre style={{
            padding: "1rem",
            backgroundColor: "#1e293b",
            color: "#f8fafc",
            borderRadius: "0.375rem",
            fontSize: "0.75rem",
            overflowX: "auto"
          }}>
            {this.state.error?.stack || this.state.error?.message}
          </pre>
          <button
            onClick={() => window.location.reload()}
            style={{
              marginTop: "1rem",
              padding: "0.5rem 1rem",
              backgroundColor: "#ef4444",
              color: "white",
              borderRadius: "0.25rem",
              border: "none",
              cursor: "pointer",
              fontWeight: 500
            }}
          >
            Reload application
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

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