'use strict';

/**
 * Turn thrown errors / IPC failures into short, user-safe strings.
 * Keep in sync with:
 * - desktop/src/renderer/userFacingError.js (Electron renderer, packaged in asar)
 * - NolimitsEvolution/utils/userFacingError.js (Phonecap / Expo)
 */

const DEFAULT_FALLBACK = 'Something went wrong. Please try again.';

function toUserMessage(err, fallback) {
  const fb =
    typeof fallback === 'string' && fallback.trim() ? fallback.trim() : DEFAULT_FALLBACK;

  if (err == null) return fb;

  let raw = '';
  if (typeof err === 'string') raw = err;
  else if (typeof err === 'object' && err != null && err.message != null) raw = String(err.message);
  else {
    try {
      raw = String(err);
    } catch (_) {
      return fb;
    }
  }

  raw = raw.replace(/\s+/g, ' ').trim();
  if (!raw || raw === '[object Object]') return fb;

  const lower = raw.toLowerCase();

  if (
    lower.includes('network') ||
    lower.includes('fetch failed') ||
    lower.includes('failed to fetch') ||
    lower.includes('load failed') ||
    lower.includes('net::')
  ) {
    return 'Network error. Check your connection and try again.';
  }
  if (lower.includes('timeout') || lower.includes('timed out') || lower.includes('etimedout')) {
    return 'Request timed out. Try again.';
  }
  if (
    lower.includes('econnrefused') ||
    lower.includes('connection refused') ||
    (lower.includes('websocket') && lower.includes('failed'))
  ) {
    return 'Could not reach the desktop. Check Wi‑Fi and that Mephonecast is running.';
  }
  if (lower.includes('enotfound') || lower.includes('getaddrinfo')) {
    return 'Could not find the server. Check the address and your network.';
  }

  // Likely stack / dev noise — don't show to users
  if (raw.includes(' at ') && (raw.includes('.js:') || raw.includes('.ts:'))) return fb;

  const max = 220;
  if (raw.length > max) return raw.slice(0, max - 1) + '…';

  return raw;
}

if (typeof module !== 'undefined' && module.exports) {
  module.exports = { toUserMessage, DEFAULT_FALLBACK };
}
if (typeof globalThis !== 'undefined') {
  globalThis.MephonecastUserFacingError = { toUserMessage, DEFAULT_FALLBACK };
}
