import { ageFromDateOfBirth } from "@/features/shared/dateOfBirth";

/**
 * Two rules the account form switches on.
 *
 * `isUnderage` decides whether the guardian ("emergency contact") fields are
 * shown and required — the same 18 boundary the registration lists use, but
 * measured **now** rather than at registration, because this form is the
 * volunteer editing their own current details.
 *
 * `isValidUrlForPlatform` is a *host* check, not a URL parse: a volunteer who
 * pastes their Instagram profile into the Facebook row should be told, and the
 * platform is already chosen from a fixed list beside the field.
 */
export const calculateAge = ageFromDateOfBirth;

export const isUnderage = (dob: string, storedBirthYear?: number | null) => {
  // Existing year-only accounts follow Laravel’s stored-year policy.
  const today = new Date(Date.now() + 3 * 60 * 60 * 1000);
  const age = dob ? calculateAge(dob) : storedBirthYear ? today.getUTCFullYear() - storedBirthYear : null;
  return age !== null && age < 18;
};

export const KNOWN_SOCIAL_PLATFORMS = [
  "facebook",
  "twitter",
  "whatsapp",
  "linkedin",
  "instagram",
];

export const isValidUrlForPlatform = (platform: string, link: string) => {
  if (!platform || !link) return false;
  const url = link.toLowerCase();
  switch (platform) {
    case "facebook":
      return url.includes("facebook.com");
    case "twitter":
      return url.includes("twitter.com") || url.includes("x.com");
    case "whatsapp":
      // `wa.me/<number>` is WhatsApp's own share link; the profile endpoint
      // validates `url`, so it passes there and was refused only here.
      return url.includes("whatsapp.com") || /^(https?:\/\/)?(www\.)?wa\.me\//.test(url);
    case "linkedin":
      return url.includes("linkedin.com");
    case "instagram":
      return url.includes("instagram.com");
    default:
      return false;
  }
};
