// Safety patch for window.fetch getter-only properties in sandboxed iframe environments
try {
  if (typeof window !== 'undefined' && window.fetch) {
    const nativeFetch = window.fetch;
    let _currentFetch = nativeFetch;
    Object.defineProperty(window, 'fetch', {
      get() {
        return _currentFetch;
      },
      set(val) {
        _currentFetch = val;
      },
      configurable: true,
      enumerable: true,
    });
  }
} catch {
  // Safe fallback
}

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

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    (this as any).state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Uncaught Application Error:', error, errorInfo);
  }

  render() {
    const state = (this as any).state as ErrorBoundaryState;
    if (state.hasError) {
      return (
        <div className="min-h-screen bg-slate-900 text-white flex items-center justify-center p-6 text-center">
          <div className="max-w-md bg-slate-800 p-8 rounded-2xl border border-slate-700 shadow-2xl space-y-4">
            <div className="w-16 h-16 bg-rose-500/20 text-rose-400 rounded-full flex items-center justify-center mx-auto text-2xl font-bold">
              ⚠️
            </div>
            <h1 className="text-xl font-bold">System Recovery Notice</h1>
            <p className="text-sm text-slate-300">
              The application encountered a browser state issue. Click below to clear cache and reload.
            </p>
            <div className="text-xs bg-slate-950 p-3 rounded text-rose-300 font-mono text-left overflow-x-auto max-h-28">
              {state.error?.message || 'Unknown State Error'}
            </div>
            <button
              onClick={() => {
                localStorage.clear();
                window.location.reload();
              }}
              className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl text-sm transition-all"
            >
              Reset Local Storage & Reload Page
            </button>
          </div>
        </div>
      );
    }

    return (this as any).props.children;
  }
}

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