export function normalizeSocialUrl(value: string | null | undefined) {
  const trimmed = (value || "").trim();
  if (!trimmed) return "";
  return trimmed;
}

function parseSocialUrl(value: string | null | undefined) {
  const trimmed = normalizeSocialUrl(value);
  if (!trimmed) return null;

  try {
    return new URL(trimmed);
  } catch {
    return null;
  }
}

function isAllowedSocialHostname(hostname: string, allowed: string[]) {
  return allowed.some((domain) => hostname === domain || hostname === `www.${domain}`);
}

export function isValidFacebookUrl(value: string | null | undefined) {
  const url = parseSocialUrl(value);
  if (!value || !String(value).trim()) return true;
  if (!url) return false;
  return url.protocol === "https:" && isAllowedSocialHostname(url.hostname.toLowerCase(), ["facebook.com", "fb.com"]);
}

export function isValidInstagramUrl(value: string | null | undefined) {
  const url = parseSocialUrl(value);
  if (!value || !String(value).trim()) return true;
  if (!url) return false;
  return url.protocol === "https:" && isAllowedSocialHostname(url.hostname.toLowerCase(), ["instagram.com"]);
}

export function getFacebookEmbedUrl(value: string | null | undefined) {
  const trimmed = normalizeSocialUrl(value);
  if (!isValidFacebookUrl(trimmed)) return null;
  const url = new URL(trimmed);
  const embedUrl = new URL("https://www.facebook.com/plugins/page.php");
  embedUrl.searchParams.set("href", url.toString());
  embedUrl.searchParams.set("tabs", "timeline");
  embedUrl.searchParams.set("width", "500");
  embedUrl.searchParams.set("height", "380");
  embedUrl.searchParams.set("small_header", "true");
  embedUrl.searchParams.set("adapt_container_width", "true");
  embedUrl.searchParams.set("hide_cover", "false");
  embedUrl.searchParams.set("show_facepile", "false");
  return embedUrl.toString();
}

export function getSocialHandle(value: string | null | undefined) {
  const url = parseSocialUrl(value);
  if (!url) return null;

  const handle = url.pathname
    .split("/")
    .map((part) => part.trim())
    .filter(Boolean)[0];

  return handle ? `@${handle}` : null;
}
