'use client'; import { useState, useRef, useEffect } from 'react'; import { X, Paperclip, ChevronDown, ChevronUp, SendHorizontal, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { Label } from '@/components/ui/label'; import DOMPurify from 'isomorphic-dompurify'; import { formatEmailForReply, formatEmailForForward } from '@/lib/email-formatter'; interface EmailObject { id?: string; from?: string; fromName?: string; to?: string; subject?: string; content?: string; html?: string; text?: string; body?: string; date?: string; read?: boolean; starred?: boolean; attachments?: { name: string; url: string }[]; folder?: string; cc?: string; bcc?: string; } interface ComposeEmailProps { showCompose: boolean; setShowCompose: (show: boolean) => void; composeTo: string; setComposeTo: (to: string) => void; composeCc: string; setComposeCc: (cc: string) => void; composeBcc: string; setComposeBcc: (bcc: string) => void; composeSubject: string; setComposeSubject: (subject: string) => void; composeBody: string; setComposeBody: (body: string) => void; showCc: boolean; setShowCc: (show: boolean) => void; showBcc: boolean; setShowBcc: (show: boolean) => void; attachments: any[]; setAttachments: (attachments: any[]) => void; handleSend: () => Promise; originalEmail?: { content: string; type: 'reply' | 'reply-all' | 'forward'; }; onSend: (email: any) => Promise; onCancel: () => void; replyTo?: EmailObject | null; forwardFrom?: EmailObject | null; } export default function ComposeEmail({ showCompose, setShowCompose, composeTo, setComposeTo, composeCc, setComposeCc, composeBcc, setComposeBcc, composeSubject, setComposeSubject, composeBody, setComposeBody, showCc, setShowCc, showBcc, setShowBcc, attachments, setAttachments, handleSend, originalEmail, replyTo, forwardFrom, onSend, onCancel }: ComposeEmailProps) { const [isSending, setIsSending] = useState(false); const fileInputRef = useRef(null); const contentEditableRef = useRef(null); const [useRichEditor, setUseRichEditor] = useState(false); const [userMessage, setUserMessage] = useState(''); const [quotedContent, setQuotedContent] = useState(''); useEffect(() => { // When forwarding or replying, use rich editor setUseRichEditor(!!replyTo || !!forwardFrom); }, [replyTo, forwardFrom]); useEffect(() => { // Initialize reply if replyTo is provided if (replyTo) { // For reply/reply-all const formattedEmail = formatEmailForReply(replyTo as any, 'reply'); setComposeTo(formattedEmail.to); setComposeSubject(formattedEmail.subject); // Store the quoted content separately const bodyContent = DOMPurify.sanitize(formattedEmail.body, { ADD_TAGS: ['style'], FORBID_TAGS: ['script', 'iframe'] }); setQuotedContent(bodyContent); setUserMessage(''); // Clear user input // Keep composeBody for backwards compatibility setComposeBody(bodyContent); } }, [replyTo, setComposeTo, setComposeSubject, setComposeBody]); useEffect(() => { // Initialize forward email if forwardFrom is provided if (forwardFrom) { initializeForwardedEmail(forwardFrom); } }, [forwardFrom]); // Initialize forwarded email content const initializeForwardedEmail = async (email: any) => { if (!email) return; console.log('Initializing forwarded email:', email); // Use our client-side formatter const formattedEmail = formatEmailForForward(email); // Set the formatted subject with Fwd: prefix setComposeSubject(formattedEmail.subject); // Create header for forwarded email - use the original styling const headerHtml = formattedEmail.headerHtml; // Prepare content let contentHtml = '
No content available
'; if (email.content) { // Sanitize the content contentHtml = DOMPurify.sanitize(email.content, { ADD_TAGS: ['style'], FORBID_TAGS: ['script', 'iframe'] }); } else if (email.html) { contentHtml = DOMPurify.sanitize(email.html, { ADD_TAGS: ['style'], FORBID_TAGS: ['script', 'iframe'] }); } else if (email.text) { contentHtml = `
${email.text}
`; } else if (email.body) { contentHtml = DOMPurify.sanitize(email.body, { ADD_TAGS: ['style'], FORBID_TAGS: ['script', 'iframe'] }); } // Store the quoted content const formattedQuote = `
${headerHtml}
${contentHtml}
`; setQuotedContent(formattedQuote); setUserMessage(''); // Clear user input // Keep composeBody for backwards compatibility setComposeBody(formattedQuote); }; // Handle file attachment selection const handleFileAttachment = (e: React.ChangeEvent) => { if (e.target.files) { const newFiles = Array.from(e.target.files); setAttachments([...attachments, ...newFiles]); } }; // Handle contentEditable input changes const handleUserMessageChange = () => { if (contentEditableRef.current) { setUserMessage(contentEditableRef.current.innerHTML); // Combine user message with quoted content for the full email body const combined = `
${contentEditableRef.current.innerHTML}
${quotedContent} `; setComposeBody(combined); } }; // Handle sending with combined content const handleSendWithCombinedContent = async () => { // For rich editor mode, ensure we combine user message with quoted content if (useRichEditor) { // Create the final combined email body const finalBody = `
${userMessage}
${quotedContent} `; // Set the complete body and send after a brief delay to ensure state is updated setComposeBody(finalBody); // Small delay to ensure state update completes setTimeout(() => { handleSend(); }, 50); } else { // For normal textarea mode, just use the existing handler handleSend(); } }; return ( <> {/* Compose Email Modal */} {showCompose && (
{/* Modal Header */}

{composeSubject.startsWith('Re:') ? 'Reply' : composeSubject.startsWith('Fwd:') ? 'Forward' : 'New Message'}

{/* Modal Body */}
{/* To Field */}
setComposeTo(e.target.value)} placeholder="recipient@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
{/* CC/BCC Toggle Buttons */}
{/* CC Field */} {showCc && (
setComposeCc(e.target.value)} placeholder="cc@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
)} {/* BCC Field */} {showBcc && (
setComposeBcc(e.target.value)} placeholder="bcc@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
)} {/* Subject Field */}
setComposeSubject(e.target.value)} placeholder="Enter subject" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
{/* Message Body - conditionally render either rich editor or textarea */}
{useRichEditor ? (
{/* User input area - completely separate from quoted content */}
{!userMessage &&

Write your message here...

}
{/* Original email content - completely isolated */} {quotedContent && (
)}
) : (