import React, { StrictMode, type ReactNode } from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { registerSW } from 'virtual:pwa-register';

interface Props {
  children: ReactNode;
}

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

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

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

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

  render() {
    const { hasError, error } = (this as any).state as State;
    if (hasError) {
      return (
        <div className="min-h-screen bg-[#F8F9FA] flex items-center justify-center p-6 text-center font-sans">
          <div className="max-w-md space-y-6">
            <div className="w-16 h-16 bg-rose-100 text-rose-600 rounded-2xl flex items-center justify-center mx-auto shadow-lg animate-bounce">
              <span className="text-2xl font-black">!</span>
            </div>
            <div className="space-y-2">
              <h1 className="text-xl font-black text-[#001D3D] uppercase tracking-tight">Ocorreu um Erro Crítico</h1>
              <p className="text-xs text-[#001D3D]/60 font-medium leading-relaxed">
                A aplicação encontrou um problema inesperado. Isto pode dever-se a uma falha de rede ou configuração do navegador.
              </p>
            </div>
            {error && (
              <div className="p-4 bg-white border border-[#001D3D]/5 rounded-2xl text-[10px] text-left overflow-auto max-h-40 font-mono text-rose-500 shadow-inner">
                {error.message}
              </div>
            )}
            <div className="pt-4 space-y-3">
              <button 
                onClick={() => window.location.reload()}
                className="w-full px-8 py-3 bg-[#001D3D] text-[#FFD60A] rounded-xl font-black uppercase text-xs tracking-widest shadow-xl shadow-[#001D3D]/20 hover:scale-[1.02] active:scale-95 transition-all"
              >
                Recarregar Sistema
              </button>
              <p className="text-[9px] text-[#001D3D]/30 font-bold uppercase tracking-widest">
                Se o erro persistir, tente limpar a cache do navegador.
              </p>
            </div>
          </div>
        </div>
      );
    }
    return (this as any).props.children;
  }
}

if (typeof window !== 'undefined') {
  registerSW({
    onNeedRefresh() {
      console.log('New content available, please refresh.');
    },
    onOfflineReady() {
      console.log('App ready to work offline.');
    },
  });
}

const rootElement = document.getElementById('root');
if (rootElement) {
  createRoot(rootElement).render(
    <StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </StrictMode>,
  );
}
