// Global error handler for chart disposal errors
export function setupChartErrorHandler() {
  // Only suppress chart disposal errors during page unload
  let isUnloading = false;

  window.addEventListener('beforeunload', () => {
    isUnloading = true;
  });

  window.addEventListener('unload', () => {
    isUnloading = true;
  });

  // Intercept console errors for chart disposal
  const originalError = console.error;
  console.error = (...args) => {
    // Check if this is a chart disposal error during unload
    if (isUnloading) {
      const errorStr = args.join(' ');
      if (errorStr.includes('Object is disposed') || 
          errorStr.includes('Cannot read properties of null') ||
          errorStr.includes('lightweight-charts')) {
        // Suppress the error during unload
        return;
      }
    }
    
    // Otherwise, log normally
    originalError.apply(console, args);
  };

  // Also catch unhandled errors
  window.addEventListener('error', (event) => {
    if (isUnloading && event.error?.message?.includes('Object is disposed')) {
      event.preventDefault();
      return;
    }
  });

  // Catch unhandled promise rejections
  window.addEventListener('unhandledrejection', (event) => {
    if (isUnloading && event.reason?.message?.includes('Object is disposed')) {
      event.preventDefault();
      return;
    }
  });
}