/** MotherShip 展示用地址（不含邮编） */
export function formatAddressDisplayLabel(addr: {
  street?: string;
  city?: string;
  state?: string;
  formatted_address?: string;
  mothership_display_label?: string;
  selected_from_mothership?: boolean;
}): string {
  const msLabel = addr.mothership_display_label?.trim();
  if (addr.selected_from_mothership && msLabel) {
    return stripZipAndCountry(msLabel);
  }

  const street = addr.street?.trim();
  const city = addr.city?.trim();
  const state = addr.state?.trim();
  if (street && city && state) {
    return `${street}, ${city}, ${state}`;
  }
  const raw = addr.formatted_address?.trim() ?? "";
  if (!raw) {
    return "";
  }
  return stripZipAndCountry(raw);
}

function stripZipAndCountry(raw: string): string {
  return raw
    .replace(/,?\s*\d{5}(-\d{4})?\b/g, "")
    .replace(/,?\s*USA\s*$/i, "")
    .replace(/\s{2,}/g, " ")
    .replace(/,\s*,/g, ",")
    .replace(/,\s*$/, "")
    .trim();
}
