import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { runTemplateCleanup } from './lib/templateCleanup';
import { reportError } from './lib/errorReporter';

// Stable session id for correlating errors within one browser tab
if (!sessionStorage.getItem('_sid')) {
  sessionStorage.setItem('_sid', Math.random().toString(36).slice(2));
}

// Catch unhandled JS errors
window.addEventListener('error', (event) => {
  reportError({
    message: event.message || 'Unknown error',
    stack: event.error?.stack,
    type: 'runtime',
  });
});

// Catch unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
  const reason = event.reason;
  reportError({
    message: reason?.message || String(reason) || 'Unhandled promise rejection',
    stack: reason?.stack,
    type: 'unhandled_promise',
  });
});

// Run the database cleanup on initialization
runTemplateCleanup();

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
);