'use client'; import { useState, useRef, useEffect } from 'react'; import { formatEmailForReplyOrForward, EmailMessage, EmailAddress } from '@/lib/services/email-service'; import { X, Paperclip, ChevronDown, ChevronUp, SendHorizontal, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'; import DOMPurify from 'isomorphic-dompurify'; interface ComposeEmailProps { initialEmail?: EmailMessage | null; type?: 'new' | 'reply' | 'reply-all' | 'forward'; onClose: () => void; onSend: (emailData: { to: string; cc?: string; bcc?: string; subject: string; body: string; attachments?: Array<{ name: string; content: string; type: string; }>; }) => Promise; } export default function ComposeEmail({ initialEmail, type = 'new', onClose, onSend }: ComposeEmailProps) { // Email form state const [to, setTo] = useState(''); const [cc, setCc] = useState(''); const [bcc, setBcc] = useState(''); const [subject, setSubject] = useState(''); const [body, setBody] = useState(''); const [showCc, setShowCc] = useState(false); const [showBcc, setShowBcc] = useState(false); const [sending, setSending] = useState(false); const [attachments, setAttachments] = useState>([]); // Refs const editorRef = useRef(null); const attachmentInputRef = useRef(null); // Initialize the form when replying to or forwarding an email useEffect(() => { if (initialEmail && type !== 'new') { if (type === 'forward') { initializeForwardedEmail(); } else { // For reply/reply-all, continue using formatEmailForReplyOrForward const formattedEmail = formatEmailForReplyOrForward(initialEmail, type as 'reply' | 'reply-all'); setTo(formattedEmail.to); if (formattedEmail.cc) { setCc(formattedEmail.cc); setShowCc(true); } setSubject(formattedEmail.subject); setBody(formattedEmail.body); } // Focus editor after initializing setTimeout(() => { if (editorRef.current) { editorRef.current.focus(); // Place cursor at the beginning of the content const selection = window.getSelection(); const range = document.createRange(); range.setStart(editorRef.current, 0); range.collapse(true); selection?.removeAllRanges(); selection?.addRange(range); } }, 100); } }, [initialEmail, type]); // Format date for the forwarded message header const formatDate = (date: Date | null): string => { if (!date) return ''; try { return date.toLocaleString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch (e) { return date.toString(); } }; // Format sender address in a readable format const formatSender = (from: Array<{name?: string, address: string}> | undefined): string => { if (!from || from.length === 0) return 'Unknown'; return from.map(sender => sender.name && sender.name !== sender.address ? `${sender.name} <${sender.address}>` : sender.address ).join(', '); }; // Format recipient addresses in a readable format const formatRecipients = (recipients: Array<{name?: string, address: string}> | undefined): string => { if (!recipients || recipients.length === 0) return ''; return recipients.map(recipient => recipient.name && recipient.name !== recipient.address ? `${recipient.name} <${recipient.address}>` : recipient.address ).join(', '); }; // Initialize forwarded email with clear structure and style preservation const initializeForwardedEmail = async () => { console.log('Starting initializeForwardedEmail'); if (!initialEmail) { console.error('No email available for forwarding'); setBody('
No email available for forwarding
'); return; } // Debug the email object structure console.log('Forwarding email object:', { id: initialEmail.id, subject: initialEmail.subject, fromLength: initialEmail.from?.length, from: initialEmail.from, to: initialEmail.to, date: initialEmail.date, hasContent: Boolean(initialEmail.content), contentLength: initialEmail.content?.length, hasHtml: Boolean(initialEmail.html), htmlLength: initialEmail.html?.length }); try { // Format subject with Fwd: prefix if needed const subjectBase = initialEmail.subject || '(No subject)'; const subjectRegex = /^(Fwd|FW|Forward):\s*/i; const subject = subjectRegex.test(subjectBase) ? subjectBase : `Fwd: ${subjectBase}`; setSubject(subject); // Format the forwarded message with a well-structured header const fromString = Array.isArray(initialEmail.from) && initialEmail.from.length > 0 ? initialEmail.from.map(addr => addr.name ? `${addr.name} <${addr.address}>` : addr.address).join(', ') : 'Unknown'; const toString = Array.isArray(initialEmail.to) && initialEmail.to.length > 0 ? initialEmail.to.map(addr => addr.name ? `${addr.name} <${addr.address}>` : addr.address).join(', ') : ''; const dateString = initialEmail.date ? typeof initialEmail.date === 'string' ? new Date(initialEmail.date).toLocaleString() : initialEmail.date.toLocaleString() : new Date().toLocaleString(); // Create a clean wrapper that won't interfere with the original email's styling // Use inline styles for the header to avoid CSS conflicts const headerHtml = `
---------- Forwarded message ---------
From: ${fromString}
Date: ${dateString}
Subject: ${subjectBase}
To: ${toString}
`; // Process the original content let originalContent = ''; // First try to use the API to parse and sanitize the email content try { // Use server-side parsing via fetch API to properly handle complex emails const response = await fetch('/api/parse-email', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: initialEmail.content || initialEmail.html || initialEmail.text || '' }), }); if (response.ok) { const parsedEmail = await response.json(); if (parsedEmail.html && parsedEmail.html.trim()) { console.log('Using parsed HTML content for forward'); // Create an iframe-like containment for the email content // This prevents CSS from the original email leaking into our compose view originalContent = ` `; } else if (parsedEmail.text && parsedEmail.text.trim()) { console.log('Using parsed text content for forward'); originalContent = `
${parsedEmail.text}
`; } else { console.log('No content available from parser'); originalContent = '
No content available
'; } } else { throw new Error('Failed to parse email content'); } } catch (parseError) { console.error('Error parsing email content:', parseError); // Fall back to direct content handling if API parsing fails if (initialEmail.html && initialEmail.html.trim()) { console.log('Falling back to HTML content for forward'); // Use DOMPurify to sanitize HTML and remove dangerous elements originalContent = DOMPurify.sanitize(initialEmail.html, { ADD_TAGS: ['style', 'div', 'span', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'img', 'table', 'tr', 'td', 'th'], ADD_ATTR: ['style', 'class', 'id', 'src', 'alt', 'href', 'target'], FORBID_TAGS: ['script', 'iframe', 'object', 'embed'], FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover'] }); } else if (initialEmail.content && initialEmail.content.trim()) { console.log('Falling back to content field for forward'); originalContent = DOMPurify.sanitize(initialEmail.content); } else if (initialEmail.text && initialEmail.text.trim()) { console.log('Falling back to text content for forward'); originalContent = `
${initialEmail.text}
`; } else { console.log('No content available for forward'); originalContent = '
No content available
'; } } // Preserve all original structure by wrapping, not modifying the original content // Important: We add a style scope to prevent CSS leakage const forwardedContent = ` ${headerHtml} `; console.log('Setting body with forwarded content'); setBody(forwardedContent); } catch (error) { console.error('Error initializing forwarded email:', error); // Even in error case, provide a usable template with empty values setBody(`
---------- Forwarded message ---------
From: ${initialEmail.from ? formatSender(initialEmail.from) : 'Unknown'}
Date: ${new Date().toLocaleString()}
Subject: ${initialEmail.subject || '(No subject)'}
To: ${initialEmail.to ? formatRecipients(initialEmail.to) : ''}
Error loading original message content. The original message may still be viewable in your inbox.
`); } }; // Handle attachment selection const handleAttachmentClick = () => { attachmentInputRef.current?.click(); }; // Process selected files const handleFileSelection = async (e: React.ChangeEvent) => { const files = e.target.files; if (!files || files.length === 0) return; // Convert selected files to attachments const newAttachments = Array.from(files).map(file => ({ file, uploading: true })); // Read files as data URLs for (const file of files) { const reader = new FileReader(); reader.onload = (event) => { const content = event.target?.result as string; setAttachments(current => [ ...current, { name: file.name, content: content.split(',')[1], // Remove data:mime/type;base64, prefix type: file.type } ]); }; reader.readAsDataURL(file); } // Reset file input if (e.target) { e.target.value = ''; } }; // Remove attachment const removeAttachment = (index: number) => { setAttachments(current => current.filter((_, i) => i !== index)); }; // Send the email const handleSend = async () => { if (!to) { alert('Please specify at least one recipient'); return; } try { setSending(true); await onSend({ to, cc: cc || undefined, bcc: bcc || undefined, subject, body: editorRef.current?.innerHTML || body, attachments }); onClose(); } catch (error) { console.error('Error sending email:', error); alert('Failed to send email. Please try again.'); } finally { setSending(false); } }; // Handle editor input const handleEditorInput = (e: React.FormEvent) => { // Store the HTML content for use in the send function setBody(e.currentTarget.innerHTML); }; return (
{type === 'new' ? 'New Message' : type === 'reply' ? 'Reply' : type === 'reply-all' ? 'Reply All' : 'Forward'}
{/* Email header fields */}
To: setTo(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="recipient@example.com" />
{showCc && (
Cc: setCc(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="cc@example.com" />
)} {showBcc && (
Bcc: setBcc(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="bcc@example.com" />
)} {/* CC/BCC controls */}
Subject: setSubject(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="Subject" />
{/* Email body editor */}
{/* Attachments list */} {attachments.length > 0 && (
Attachments:
{attachments.map((attachment, index) => (
{attachment.name}
))}
)}
); }