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

// Global uncaught client error listener
if (typeof window !== 'undefined') {
  let lastReportedTime = 0;
  const reportErrorToServer = (message: string, stack?: string, details?: any) => {
    const now = Date.now();
    // Throttle client reports to max 1 per 2 seconds to avoid spamming
    if (now - lastReportedTime < 2000) return;
    lastReportedTime = now;

    fetch('/api/logs/client-error', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message,
        stack,
        additionalContext: details,
        url: window.location.href,
        userAgent: navigator.userAgent,
        timestamp: new Date().toISOString()
      })
    }).catch(() => {});
  };

  window.addEventListener('error', (event) => {
    reportErrorToServer(event.message || 'Uncaught window error', event.error?.stack, {
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno
    });
  });

  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    const msg = reason?.message || String(reason || 'Unhandled client promise rejection');
    reportErrorToServer(`Unhandled Promise Rejection: ${msg}`, reason?.stack, { reason });
  });
}

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