import type { Email } from "@/lib/email-data" import { formatMailDetailDate } from "@/lib/mail-date" import { cleanSenderName } from "@/lib/sender-display" function escapeHtml(s: string): string { return s .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) } type PrintSegment = { fromName: string fromEmail: string date: string bodyHtml: string } function buildSegments(email: Email): PrintSegment[] { const conv = email.conversation ?? [] const segments: PrintSegment[] = [] for (const msg of conv) { segments.push({ fromName: cleanSenderName(msg.sender), fromEmail: msg.senderEmail, date: formatMailDetailDate(msg.date), bodyHtml: msg.body, }) } const mainName = cleanSenderName(email.sender) const mainEmail = email.senderEmail || `${mainName.toLowerCase().replace(/\s+/g, ".")}@example.com` segments.push({ fromName: mainName, fromEmail: mainEmail, date: formatMailDetailDate(email.date), bodyHtml: email.body ?? `

${escapeHtml(email.preview)}

`, }) return segments } function buildPrintHtml(email: Email): string { const subject = escapeHtml(email.subject) const segments = buildSegments(email) const blocks = segments .map( (seg) => `
De${escapeHtml(seg.fromName)} <${escapeHtml(seg.fromEmail)}>
Àmoi
Date${escapeHtml(seg.date)}
${seg.bodyHtml}
` ) .join("") return ` ${subject}

${subject}

${blocks} ` } /** * Ouvre un nouvel onglet avec la conversation en mise en page imprimable * (en-têtes De / À / Date par message), puis déclenche la boîte d’impression du système. */ export function openConversationPrint(email: Email): void { if (typeof window === "undefined") return const html = buildPrintHtml(email) const win = window.open("", "_blank", "noopener,noreferrer") if (!win) { window.alert( "Impossible d’ouvrir la fenêtre d’impression. Vérifiez que les fenêtres pop-up ne sont pas bloquées pour ce site." ) return } win.document.open() win.document.write(html) win.document.close() const runPrint = () => { try { win.focus() win.print() } catch { /* ignore */ } } if (win.document.readyState === "complete") { window.setTimeout(runPrint, 0) } else { win.addEventListener("load", () => window.setTimeout(runPrint, 0), { once: true }) } }