const EMPTY_IMAGE_DATA_URL =
  'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';

/** Return a safe URL for an externally hosted Markdown image. */
export function resolveSafeExternalMarkdownImageUrl(url: string) {
  const value = url.trim();
  try {
    const parsed = new URL(value);
    if (parsed.protocol === 'https:' && !parsed.username && !parsed.password) {
      return parsed.href;
    }
  } catch {
    // Relative and malformed values require an application-level resolver.
  }
  return EMPTY_IMAGE_DATA_URL;
}

export function isBlockedMarkdownImageUrl(url: string) {
  return resolveSafeExternalMarkdownImageUrl(url) === EMPTY_IMAGE_DATA_URL;
}

/** Keep only navigable web/mail/anchor links and application-resolved relative paths. */
export function isSafeMarkdownLinkHref(href: string) {
  const value = href.trim();
  if (!value || hasControlCharacter(value) || value.startsWith('//')) {
    return false;
  }
  if (value.startsWith('#') || /^mailto:/i.test(value)) return true;
  if (/^https?:\/\//i.test(value)) {
    try {
      const parsed = new URL(value);
      return !parsed.username && !parsed.password;
    } catch {
      return false;
    }
  }
  return !/^[a-z][a-z\d+.-]*:/i.test(value);
}

function hasControlCharacter(value: string) {
  return [...value].some((character) => {
    const code = character.codePointAt(0) || 0;
    return code < 32 || code === 127;
  });
}

export { EMPTY_IMAGE_DATA_URL };
