import { fullContactDisplayName } from "./types"
import type { FullContact } from "./types"

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
}

export function printContacts(contacts: FullContact[], title = "Contacts"): void {
  const rows = contacts
    .map((c) => {
      const name = escapeHtml(
        fullContactDisplayName(c) || c.emails[0]?.value || c.phones[0]?.value || "—"
      )
      const email = escapeHtml(c.emails[0]?.value ?? "")
      const phone = escapeHtml(c.phones[0]?.value ?? "")
      const company = escapeHtml(
        [c.jobTitle, c.company].filter(Boolean).join(", ")
      )
      return `<tr><td>${name}</td><td>${email}</td><td>${phone}</td><td>${company}</td></tr>`
    })
    .join("")

  const html = `<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8" />
  <title>${escapeHtml(title)}</title>
  <style>
    body { font-family: Roboto, Arial, sans-serif; font-size: 12px; margin: 24px; color: #1f1f1f; }
    h1 { font-size: 20px; font-weight: normal; margin-bottom: 16px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; }
    th { font-size: 11px; color: #5f6368; font-weight: 500; }
    @media print { body { margin: 12px; } }
  </style>
</head>
<body>
  <h1>${escapeHtml(title)} (${contacts.length})</h1>
  <table>
    <thead>
      <tr>
        <th>Nom</th>
        <th>E-mail</th>
        <th>Téléphone</th>
        <th>Fonction et entreprise</th>
      </tr>
    </thead>
    <tbody>${rows}</tbody>
  </table>
</body>
</html>`

  const win = window.open("", "_blank", "noopener,noreferrer")
  if (!win) {
    window.alert("Impossible d'ouvrir la fenêtre d'impression. Vérifiez les pop-ups bloquées.")
    return
  }
  win.document.write(html)
  win.document.close()
  win.focus()
  win.onload = () => {
    win.print()
  }
  setTimeout(() => win.print(), 250)
}
