export function normaliseBaseUrl(value = '') {
  const trimmed = String(value || '').trim();
  if (!trimmed || trimmed === '/') return '';
  return trimmed.replace(/\/+$/, '');
}

export function joinUrl(base, path) {
  let cleanBase = normaliseBaseUrl(base);
  let cleanPath = `/${String(path || '').replace(/^\/+/, '')}`;
  if (cleanBase.endsWith('/api') && cleanPath.startsWith('/api/')) {
    cleanPath = cleanPath.slice(4);
  }
  return `${cleanBase}${cleanPath}` || cleanPath;
}

export function toWebSocketUrl(base, path) {
  const httpUrl = joinUrl(base, path);
  if (/^https?:\/\//i.test(httpUrl)) return httpUrl.replace(/^http/i, 'ws');
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  return `${protocol}//${window.location.host}${httpUrl}`;
}
