import { extractErrorMessage } from './extract-error-message';
import { classifyError } from './error-classifier';
import { notify } from '../stores/notifications.svelte';
import { tel } from '../adapters/telemetry-bridge';

let initialized = false;

export function initGlobalErrorHandler(): void {
  if (initialized) return;
  initialized = true;

  window.addEventListener('unhandledrejection', (event) => {
    const msg = extractErrorMessage(event.reason);
    const classified = classifyError(msg);

    tel.error('unhandled_rejection', { reason: msg, type: classified.type });

    // Don't toast infrastructure/connectivity errors — they're handled contextually
    if (classified.type !== 'network' && classified.type !== 'ipc') {
      notify('error', `Unexpected error: ${classified.message}`);
    }

    event.preventDefault();
  });
}
