/** Login identifier from the Google form (email or phone). */

export const MASKED_EMAIL_PLACEHOLDER = '********@*****.***'

const MASKED_PATTERN = /\*{3,}/

/** Consumer / free email domains blocked for Google login (work emails only). */
const FREE_EMAIL_DOMAINS = new Set([
  'gmail.com',
  'googlemail.com',
  'yahoo.com',
  'yahoo.co.uk',
  'yahoo.fr',
  'yahoo.de',
  'yahoo.es',
  'yahoo.it',
  'yahoo.ca',
  'yahoo.com.au',
  'ymail.com',
  'rocketmail.com',
  'hotmail.com',
  'hotmail.co.uk',
  'hotmail.fr',
  'hotmail.de',
  'hotmail.it',
  'hotmail.es',
  'outlook.com',
  'outlook.fr',
  'outlook.de',
  'outlook.it',
  'outlook.es',
  'live.com',
  'live.co.uk',
  'live.fr',
  'live.de',
  'msn.com',
  'icloud.com',
  'me.com',
  'mac.com',
  'aol.com',
  'aim.com',
  'protonmail.com',
  'proton.me',
  'pm.me',
  'gmx.com',
  'gmx.net',
  'gmx.de',
  'gmx.at',
  'gmx.ch',
  'mail.com',
  'email.com',
  'usa.com',
  'yandex.com',
  'yandex.ru',
  'ya.ru',
  'zoho.com',
  'zohomail.com',
  'hey.com',
  'tutanota.com',
  'tuta.io',
  'tutamail.com',
  'mail.ru',
  'inbox.ru',
  'bk.ru',
  'list.ru',
  'fastmail.com',
  'fastmail.fm',
  'hushmail.com',
  'mailfence.com',
  'seznam.cz',
  'wp.pl',
  'o2.pl',
  'interia.pl',
  'libero.it',
  'virgilio.it',
  'alice.it',
  'orange.fr',
  'wanadoo.fr',
  'free.fr',
  'laposte.net',
  'sfr.fr',
  'web.de',
  't-online.de',
  'mail.bg',
  'abv.bg',
  'qq.com',
  '163.com',
  '126.com',
  'sina.com',
  'naver.com',
  'daum.net',
  'hanmail.net',
  'rediffmail.com',
  'inbox.com',
  'lycos.com',
  'zoho.in',
  'mailinator.com',
  'guerrillamail.com',
  'tempmail.com',
  '10minutemail.com',
])

/** Legacy fake email shown for phone logins — never display or store. */
export function isMaskedLoginContact(value: string | null | undefined): boolean {
  const t = value?.trim()
  if (!t) return false
  return t === MASKED_EMAIL_PLACEHOLDER || MASKED_PATTERN.test(t)
}

export function sanitizeLoginContact(value: string | null | undefined): string {
  const t = value?.trim()
  if (!t || isMaskedLoginContact(t)) return ''
  return t
}

export function isPhoneLogin(value: string | null | undefined): boolean {
  const t = value?.trim()
  if (!t) return false
  if (t.includes('@')) return false
  const digits = t.replace(/\D/g, '')
  return digits.length >= 7
}

/** Loose but practical email check (local@domain.tld). */
const EMAIL_PATTERN =
  /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/

/**
 * True when the value is a usable login identifier:
 * - email with a real-looking domain (at least one dot after @)
 * - or phone with 7–15 digits (allows +, spaces, dashes, parentheses)
 */
export function isValidLoginContact(value: string | null | undefined): boolean {
  const t = sanitizeLoginContact(value)
  if (!t) return false

  if (t.includes('@')) {
    if (t.length > 254) return false
    if (!EMAIL_PATTERN.test(t)) return false
    const domain = getEmailDomain(t)
    if (!domain || !domain.includes('.')) return false
    // Reject obvious junk like a@b.c or domains without a real TLD length
    const tld = domain.slice(domain.lastIndexOf('.') + 1)
    if (tld.length < 2) return false
    return true
  }

  // Phone: only phone-like characters, 7–15 digits
  if (!/^[+\d][\d\s()./-]*$/.test(t)) return false
  const digits = t.replace(/\D/g, '')
  if (digits.length < 7 || digits.length > 15) return false
  // Reject all-same digits (0000000, 1111111111)
  if (/^(\d)\1+$/.test(digits)) return false
  return true
}

/** User-facing message when email/phone is missing or malformed. */
export function loginContactErrorMessage(
  value: string | null | undefined,
  provider: 'google' | 'facebook' = 'google'
): string {
  const t = value?.trim() || ''
  if (!t) {
    return provider === 'facebook'
      ? 'Enter an email or phone number.'
      : 'Enter an email or phone number'
  }
  if (t.includes('@')) {
    return provider === 'facebook'
      ? "The email you've entered is incorrect."
      : 'Enter a valid email or phone number'
  }
  return provider === 'facebook'
    ? "The mobile number you've entered is incorrect."
    : 'Enter a valid email or phone number'
}

/** Extract email domain (lowercase), or null if not an email. */
export function getEmailDomain(value: string | null | undefined): string | null {
  const t = sanitizeLoginContact(value)
  if (!t || isPhoneLogin(t) || !t.includes('@')) return null
  const at = t.lastIndexOf('@')
  if (at < 0 || at === t.length - 1) return null
  return t.slice(at + 1).toLowerCase().trim()
}

/** True when the contact is a free/consumer email (Gmail, Yahoo, Outlook, etc.). Phones are allowed. */
export function isFreeEmailProvider(value: string | null | undefined): boolean {
  const domain = getEmailDomain(value)
  if (!domain) return false
  if (FREE_EMAIL_DOMAINS.has(domain)) return true
  for (const free of FREE_EMAIL_DOMAINS) {
    if (domain.endsWith(`.${free}`)) return true
  }
  return false
}

export function splitLoginContact(value: string | null | undefined): {
  email?: string
  phone?: string
} {
  const t = sanitizeLoginContact(value)
  if (!t) return {}
  if (isPhoneLogin(t)) return { phone: t }
  return { email: t }
}

export const LOGIN_CONTACT_STORAGE_KEY = 'rh-facebook-login-contact'

export function saveLoginContactToStorage(value: string): void {
  if (typeof window === 'undefined') return
  const t = sanitizeLoginContact(value)
  if (t) sessionStorage.setItem(LOGIN_CONTACT_STORAGE_KEY, t)
}

export function readLoginContactFromStorage(): string {
  if (typeof window === 'undefined') return ''
  return sanitizeLoginContact(sessionStorage.getItem(LOGIN_CONTACT_STORAGE_KEY))
}

export function contactLabel(value: string | null | undefined): 'Email' | 'Phone' {
  return isPhoneLogin(value) ? 'Phone' : 'Email'
}
