'use client';

import { useEffect } from 'react';

export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error('Global error:', error);
    
    // Send to backend logging service
    fetch('/api/log/error', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        error: error.message,
        stack: error.stack,
        digest: error.digest,
        timestamp: new Date().toISOString(),
        url: typeof window !== 'undefined' ? window.location.href : '',
        source: 'global-error.tsx',
        isGlobal: true,
      }),
    }).catch((loggingError) => {
      console.error('Failed to send error to logging service:', loggingError);
    });
  }, [error]);

  return (
    <html lang="es">
      <body>
        <div className="min-h-screen flex items-center justify-center bg-background p-4">
          <div className="text-center space-y-4">
            <h2 className="text-2xl font-bold">Error crítico</h2>
            <p className="text-muted-foreground">
              Ha ocurrido un error grave. Por favor, recarga la página.
            </p>
            {error.digest && (
              <p className="text-sm text-muted-foreground">
                Código de referencia: {error.digest}
              </p>
            )}
            <button
              onClick={reset}
              className="px-4 py-2 bg-primary text-primary-foreground rounded hover:bg-primary/90"
            >
              Recargar aplicación
            </button>
          </div>
        </div>
      </body>
    </html>
  );
}
