/**
 * POST client errors to /api/telemetry/js-errors (shop API).
 * Uses same-origin relative URL so the dev-server proxy forwards to the backend.
 */

const TELEMETRY_PATH = '/api/telemetry/js-errors';

/**
 * POST a single error report (same shape as one element of `errors[]`).
 * Used by global handlers and by SocketManager for socket.io failures.
 */
export function reportJsErrorTelemetry(payload) {
  fetch(TELEMETRY_PATH, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }).catch(() => {});
}

function send(payload) {
  reportJsErrorTelemetry(payload);
}

/**
 * Register global listeners once. Safe to call in browser only.
 */
export function installJsErrorTelemetry() {
  if (typeof window === 'undefined') {
    return;
  }

  window.addEventListener('error', (event) => {
    send({
      message: event.message || 'Error',
      name: event.error?.name,
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      url: window.location.href,
      stack: event.error && event.error.stack,
    });
  });

  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    send({
      message:
        reason && typeof reason.message === 'string'
          ? reason.message
          : String(reason),
      name: reason && reason.name,
      stack: reason && reason.stack,
      url: window.location.href,
      context: { type: 'unhandledrejection' },
    });
  });
}
