'use client'; import { useRef, useEffect, useState, useCallback } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Paperclip, X } from 'lucide-react'; import { Textarea } from '@/components/ui/textarea'; import { decodeComposeContent, encodeComposeContent } from '@/lib/compose-mime-decoder'; import { Email } from '@/app/courrier/page'; import mime from 'mime'; import { simpleParser } from 'mailparser'; import { decodeEmail } from '@/lib/mail-parser-wrapper'; import DOMPurify from 'dompurify'; 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: Email) => void; onCancel: () => void; onBodyChange?: (body: string) => void; initialTo?: string; initialSubject?: string; initialBody?: string; initialCc?: string; initialBcc?: string; replyTo?: Email | null; forwardFrom?: Email | 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, onSend, onCancel, onBodyChange, initialTo, initialSubject, initialBody, initialCc, initialBcc, replyTo, forwardFrom }: ComposeEmailProps) { const composeBodyRef = useRef(null); const [localContent, setLocalContent] = useState(''); const [isLoading, setIsLoading] = useState(false); const contentRef = useRef(null); useEffect(() => { if (replyTo || forwardFrom) { const initializeContent = async () => { if (!composeBodyRef.current) return; try { const emailToProcess = replyTo || forwardFrom; console.log('[DEBUG] Initializing compose content with email:', emailToProcess ? { id: emailToProcess.id, subject: emailToProcess.subject, hasContent: !!emailToProcess.content, contentLength: emailToProcess.content ? emailToProcess.content.length : 0, preview: emailToProcess.preview } : 'null' ); // Set initial loading state composeBodyRef.current.innerHTML = `

Loading original message...
`; setIsLoading(true); // Check if email object exists if (!emailToProcess) { console.error('[DEBUG] No email to process for reply/forward'); composeBodyRef.current.innerHTML = `

No email selected for reply/forward.
`; setIsLoading(false); return; } // Check if we need to fetch full content first if (!emailToProcess.content || emailToProcess.content.length === 0) { console.log('[DEBUG] Need to fetch content before composing reply/forward'); try { const response = await fetch(`/api/courrier/${emailToProcess.id}?folder=${encodeURIComponent(emailToProcess.folder || 'INBOX')}`); if (!response.ok) { throw new Error(`Failed to fetch email content: ${response.status}`); } const fullContent = await response.json(); // Update the email content with the fetched full content emailToProcess.content = fullContent.content; emailToProcess.contentFetched = true; console.log('[DEBUG] Successfully fetched content for reply/forward'); } catch (error) { console.error('[DEBUG] Error fetching content for reply:', error); composeBodyRef.current.innerHTML = `

Failed to load email content. Please try again.
`; setIsLoading(false); return; // Exit if we couldn't get the content } } // Use the exact same implementation as Panel 3's ReplyContent try { const decoded = await decodeEmail(emailToProcess.content); let formattedContent = ''; if (forwardFrom) { // Create a clean header for the forwarded email const headerHtml = `

---------- Forwarded message ---------

From: ${decoded.from || ''}

Date: ${formatDate(decoded.date)}

Subject: ${decoded.subject || ''}

To: ${decoded.to || ''}

`; // Use the original HTML as-is without DOMPurify or any modification formattedContent = ` ${headerHtml} ${decoded.html || decoded.text || 'No content available'} `; } else { formattedContent = `

On ${formatDate(decoded.date)}, ${decoded.from || ''} wrote:

`; } // Set the content in the compose area with proper structure const wrappedContent = `

${formattedContent}
`; if (composeBodyRef.current) { composeBodyRef.current.innerHTML = wrappedContent; // Place cursor at the beginning before the quoted content const selection = window.getSelection(); const range = document.createRange(); const firstDiv = composeBodyRef.current.querySelector('div[style*="min-height: 20px;"]'); if (firstDiv) { range.setStart(firstDiv, 0); range.collapse(true); selection?.removeAllRanges(); selection?.addRange(range); (firstDiv as HTMLElement).focus(); } // Update compose state setComposeBody(wrappedContent); setLocalContent(wrappedContent); console.log('[DEBUG] Successfully set compose content'); } } catch (error) { console.error('[DEBUG] Error parsing email for compose:', error); // Fallback to basic content display const errorContent = `

---------- Original Message ---------
${emailToProcess.subject ? `Subject: ${emailToProcess.subject}
` : ''} ${emailToProcess.from ? `From: ${emailToProcess.from}
` : ''} ${emailToProcess.date ? `Date: ${new Date(emailToProcess.date).toLocaleString()}
` : ''}
${emailToProcess.preview || 'No content available'}
`; if (composeBodyRef.current) { composeBodyRef.current.innerHTML = errorContent; setComposeBody(errorContent); setLocalContent(errorContent); } } } catch (error) { console.error('[DEBUG] Error initializing compose content:', error); if (composeBodyRef.current) { const errorContent = `

Error loading original message.
Technical details: ${error instanceof Error ? error.message : 'Unknown error'}
`; composeBodyRef.current.innerHTML = errorContent; setComposeBody(errorContent); setLocalContent(errorContent); } } finally { setIsLoading(false); } }; initializeContent(); } }, [replyTo, forwardFrom, setComposeBody]); const handleInput = (e: React.FormEvent) => { if (!e.currentTarget) return; const content = e.currentTarget.innerHTML; if (!content.trim()) { setLocalContent(''); setComposeBody(''); } else { setLocalContent(content); setComposeBody(content); } if (onBodyChange) { onBodyChange(content); } // Ensure scrolling and cursor behavior works after edits const messageContentDivs = e.currentTarget.querySelectorAll('.message-content'); messageContentDivs.forEach(div => { // Make sure the div remains scrollable after input events (div as HTMLElement).style.maxHeight = '300px'; (div as HTMLElement).style.overflowY = 'auto'; (div as HTMLElement).style.border = '1px solid #e5e7eb'; (div as HTMLElement).style.borderRadius = '4px'; (div as HTMLElement).style.padding = '10px'; // Ensure wheel events are properly handled if (!(div as HTMLElement).hasAttribute('data-scroll-handler-attached')) { div.addEventListener('wheel', function(this: HTMLElement, ev: Event) { const e = ev as WheelEvent; const target = this; // Check if we're at the boundary of the scrollable area const isAtBottom = target.scrollHeight - target.scrollTop <= target.clientHeight + 1; const isAtTop = target.scrollTop <= 0; // Only prevent default if we're not at the boundaries in the direction of scrolling if ((e.deltaY > 0 && !isAtBottom) || (e.deltaY < 0 && !isAtTop)) { e.stopPropagation(); e.preventDefault(); // Prevent the parent container from scrolling } }, { passive: false }); // Mark this element as having a scroll handler attached (div as HTMLElement).setAttribute('data-scroll-handler-attached', 'true'); } }); }; const handleSendEmail = async () => { if (!composeBodyRef.current) return; const composeArea = composeBodyRef.current.querySelector('.compose-area'); if (!composeArea) return; const content = composeArea.innerHTML; if (!content.trim()) { console.error('Email content is empty'); return; } try { const encodedContent = await encodeComposeContent(content); setComposeBody(encodedContent); await handleSend(); setShowCompose(false); } catch (error) { console.error('Error sending email:', error); } }; const handleFileAttachment = async (e: React.ChangeEvent) => { if (!e.target.files) return; const newAttachments: any[] = []; const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes const oversizedFiles: string[] = []; for (const file of e.target.files) { if (file.size > MAX_FILE_SIZE) { oversizedFiles.push(file.name); continue; } try { // Read file as base64 const base64Content = await new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => { const base64 = reader.result as string; resolve(base64.split(',')[1]); // Remove data URL prefix }; reader.readAsDataURL(file); }); newAttachments.push({ name: file.name, type: file.type, content: base64Content, encoding: 'base64' }); } catch (error) { console.error('Error processing attachment:', error); } } if (oversizedFiles.length > 0) { alert(`The following files exceed the 10MB size limit and were not attached:\n${oversizedFiles.join('\n')}`); } if (newAttachments.length > 0) { setAttachments([...attachments, ...newAttachments]); } }; // Add focus handling for better UX const handleComposeAreaClick = (e: React.MouseEvent) => { // If the click is directly on the compose area and not on any child element if (e.target === e.currentTarget) { // Find the cursor position element const cursorPosition = e.currentTarget.querySelector('.cursor-position'); if (cursorPosition) { // Focus the cursor position element (cursorPosition as HTMLElement).focus(); // Set cursor at the beginning const selection = window.getSelection(); const range = document.createRange(); range.setStart(cursorPosition, 0); range.collapse(true); selection?.removeAllRanges(); selection?.addRange(range); } } }; // Add formatDate function to match Panel 3 implementation function formatDate(date: Date | null): string { if (!date) return ''; return new Intl.DateTimeFormat('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }).format(date); } if (!showCompose) return null; return (
{/* Modal Header */}

{replyTo ? 'Reply' : forwardFrom ? '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 */}
{/* Modal Footer */}
{/* File Input for Attachments */}
); }