/**
 * «رقم الواتساب أو رابط المجموعة» (client, 2026-10-18): an opportunity's
 * WhatsApp contact may be typed as a phone number or pasted as a link (a
 * `wa.me` chat or a `chat.whatsapp.com` group).
 */

/** Kuwait, for a local 8-digit number typed without its country code. */
const LOCAL_COUNTRY_CODE = "965";
const LOCAL_NUMBER_LENGTH = 8;

/**
 * The international digits of a value typed as a phone number, or `null` when
 * it is not one (e.g. a link). Accepts `+`, spaces, dashes and brackets; a
 * leading `00` is the same as `+`; a bare 8-digit number is a Kuwaiti one.
 */
export function whatsAppNumberDigits(value: string | null | undefined): string | null {
  const trimmed = value?.trim() ?? "";
  if (!trimmed || !/^\+?[\d\s\-()]+$/.test(trimmed)) return null;
  let digits = trimmed.replace(/\D/g, "");
  if (digits.startsWith("00")) digits = digits.slice(2);
  if (digits.length === LOCAL_NUMBER_LENGTH) digits = LOCAL_COUNTRY_CODE + digits;
  return digits.length >= 7 && digits.length <= 15 ? digits : null;
}

/**
 * The value as a link: a number becomes `https://wa.me/<digits>`, anything
 * else is returned trimmed. `""` for an empty value.
 */
export function toWhatsAppLink(value: string | null | undefined): string {
  const digits = whatsAppNumberDigits(value);
  if (digits) return `https://wa.me/${digits}`;
  return value?.trim() ?? "";
}

/**
 * An `href` for a WhatsApp contact typed by an admin or organizer: a number
 * (local 8-digit Kuwaiti numbers get +965) becomes a `wa.me` chat, a link keeps
 * its address and gains `https://` when it was pasted without a scheme — a
 * bare `wa.me/…` would otherwise resolve as a path on this site. `""` when
 * empty.
 */
export function contactWhatsAppHref(value: string | null | undefined): string {
  const link = toWhatsAppLink(value);
  if (!link || /^https?:\/\//i.test(link)) return link;
  return `https://${link.replace(/^\/+/, "")}`;
}
