import React, { Component, ErrorInfo, ReactNode } from 'react';
import { ShieldAlert, Terminal } from 'lucide-react';

interface Props { children: ReactNode }
interface State { hasError: boolean; error: Error | null; errorInfo: ErrorInfo | null }

export class DebugGuard extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.setState({ error, errorInfo });
    console.error("SYSTEM FRACTURE:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="fixed inset-0 z-[999] bg-black text-red-500 font-mono p-6 overflow-auto flex flex-col gap-4">
          <div className="flex items-center gap-3 border-b border-red-500/30 pb-4">
            <ShieldAlert size={32} />
            <h1 className="text-xl font-bold tracking-widest uppercase">SYSTEM FRACTURE</h1>
          </div>
          
          <div className="bg-red-950/20 p-4 border border-red-500/20 rounded-xl">
            <h2 className="text-sm text-white/50 uppercase mb-2">Error Log</h2>
            <p className="text-lg font-bold">{this.state.error?.toString()}</p>
          </div>

          <div className="bg-black border border-white/10 p-4 rounded-xl text-[10px] text-white/60 whitespace-pre-wrap">
             {this.state.errorInfo?.componentStack}
          </div>

          <button 
            onClick={() => window.location.reload()} 
            className="mt-8 py-4 bg-white text-black font-bold uppercase tracking-widest rounded-xl hover:bg-red-500 hover:text-white"
          >
            REBOOT SYSTEM
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
