export function normalizeFacebookUrl(urlStr: string): string {
  if (!urlStr || typeof urlStr !== 'string') return '';
  let trimmed = urlStr.trim().replace(/^@/, '');
  if (!trimmed) return '';
  const lower = trimmed.toLowerCase();
  if (
    lower.startsWith('javascript:') ||
    lower.startsWith('data:') ||
    lower.startsWith('vbscript:') ||
    lower.startsWith('file:') ||
    lower.startsWith('about:')
  ) {
    return '';
  }
  if (/^https?:\/\//i.test(trimmed)) {
    return trimmed;
  }
  if (
    lower.startsWith('facebook.com/') ||
    lower.startsWith('www.facebook.com/') ||
    lower.startsWith('fb.com/') ||
    lower.startsWith('www.fb.com/') ||
    lower.startsWith('fb.me/')
  ) {
    return 'https://' + trimmed;
  }
  if (!lower.includes('facebook.com') && !lower.includes('fb.com') && !lower.includes('fb.me')) {
    return 'https://facebook.com/' + trimmed;
  }
  return 'https://' + trimmed;
}

export function normalizeUrl(urlStr: string): string {
  if (!urlStr || typeof urlStr !== 'string') return '';
  let trimmed = urlStr.trim();
  if (!trimmed) return '';
  const lower = trimmed.toLowerCase();
  if (
    lower.startsWith('javascript:') ||
    lower.startsWith('data:') ||
    lower.startsWith('vbscript:') ||
    lower.startsWith('file:') ||
    lower.startsWith('about:')
  ) {
    return '';
  }
  if (!/^https?:\/\//i.test(trimmed)) {
    trimmed = 'https://' + trimmed;
  }
  return trimmed;
}

export function isValidFacebookUrl(urlStr: string): boolean {
  if (!urlStr || typeof urlStr !== 'string') return false;
  const normalized = normalizeFacebookUrl(urlStr);
  if (!normalized) return false;
  try {
    const parsed = new URL(normalized);
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
    const host = parsed.hostname.toLowerCase();
    return (
      host === 'facebook.com' ||
      host.endsWith('.facebook.com') ||
      host === 'fb.com' ||
      host.endsWith('.fb.com') ||
      host === 'fb.me' ||
      host === 'm.facebook.com' ||
      host === 'web.facebook.com'
    );
  } catch {
    return false;
  }
}

export function isValidWebsiteUrl(urlStr: string): boolean {
  if (!urlStr || !urlStr.trim()) return true; // Optional field
  const normalized = normalizeUrl(urlStr);
  if (!normalized) return false;
  try {
    const parsed = new URL(normalized);
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
    return parsed.hostname.length > 0 && (parsed.hostname.includes('.') || parsed.hostname === 'localhost');
  } catch {
    return false;
  }
}

