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

declare global {
  interface Window {
    __NOVYTHERIS_MOUNTED__?: boolean;
  }
}

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

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

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-[#08060E] text-[#F3F0F9] flex items-center justify-center p-6 font-sans">
          <div className="max-w-md w-full bg-[#110D1B] border border-[#271F3A] rounded-xl p-6 space-y-4">
            <div className="text-xs font-mono text-[#C084FC]">
              Novytheris ($NVTHR) · Solana Recovery Console
            </div>
            <h1 className="text-lg font-bold text-[#F3F0F9]">
              Interface Recovery Mode
            </h1>
            <p className="text-xs text-[#9D8EC4] leading-relaxed">
              {this.state.message}
            </p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 rounded-lg bg-[#C084FC] text-[#08060E] text-xs font-semibold hover:bg-[#D8B4FE] transition-colors"
            >
              Reload Terminal
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

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