'use client'; import { useRef, useEffect, useState } 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'; 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); 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 we have content if (!emailToProcess?.content) { console.error('[DEBUG] No email content found to process'); composeBodyRef.current.innerHTML = `

Unable to load original message content.
`; setIsLoading(false); return; } // Format the reply/forward content const type = replyTo ? 'reply' : 'forward'; // Use simple, reliable formatting for the quoted content const formatEmailAddresses = (addresses: any) => { if (!addresses) return 'Unknown'; if (typeof addresses === 'string') return addresses; if (Array.isArray(addresses)) { return addresses.map(addr => addr.name || addr.address).join(', '); } return String(addresses); }; // Extract plain text content for reliable display let emailContent = ''; try { // Parse the original email to get clean content const response = await fetch('/api/parse-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: emailToProcess.content }), }); if (response.ok) { const data = await response.json(); emailContent = data.text || ''; // If no text content, try to extract from HTML if (!emailContent && data.html) { // Create a temporary div to extract text from HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = data.html; emailContent = tempDiv.textContent || tempDiv.innerText || ''; } } } catch (error) { console.error('[DEBUG] Error parsing email:', error); // Fallback to simple content extraction emailContent = emailToProcess.content.replace(/<[^>]*>/g, ''); } // Format the content based on reply type const quotedContent = type === 'forward' ? `
---------- Forwarded message ---------
From: ${formatEmailAddresses(emailToProcess.from) || 'Unknown Sender'}
Date: ${new Date(emailToProcess.date || Date.now()).toLocaleString()}
Subject: ${emailToProcess.subject || 'No Subject'}
To: ${formatEmailAddresses(emailToProcess.to) || ''}
${emailToProcess.cc ? `Cc: ${formatEmailAddresses(emailToProcess.cc)}
` : ''}
${emailContent}
` : `
On ${new Date(emailToProcess.date || Date.now()).toLocaleString()}, ${formatEmailAddresses(emailToProcess.from) || 'Unknown Sender'} wrote:
${emailContent}
`; // Set the content in the compose area with proper structure const formattedContent = `

${quotedContent}
`; if (composeBodyRef.current) { composeBodyRef.current.innerHTML = formattedContent; // Place cursor at the beginning before the quoted content const selection = window.getSelection(); const range = document.createRange(); const firstDiv = composeBodyRef.current.querySelector('.cursor-position'); if (firstDiv) { range.setStart(firstDiv, 0); range.collapse(true); selection?.removeAllRanges(); selection?.addRange(range); (firstDiv as HTMLElement).focus(); } // After setting the HTML content, add event listeners for scrolling const messageContents = composeBodyRef.current.querySelectorAll('.message-content'); messageContents.forEach(container => { // Make sure the container is properly styled for scrolling (container as HTMLElement).style.maxHeight = '300px'; (container as HTMLElement).style.overflowY = 'auto'; (container as HTMLElement).style.border = '1px solid #e5e7eb'; (container as HTMLElement).style.borderRadius = '4px'; (container as HTMLElement).style.padding = '10px'; // Ensure wheel events are properly handled if (!(container as HTMLElement).hasAttribute('data-scroll-handler-attached')) { container.addEventListener('wheel', (e: Event) => { const wheelEvent = e as WheelEvent; const target = e.currentTarget as HTMLElement; // 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 ((wheelEvent.deltaY > 0 && !isAtBottom) || (wheelEvent.deltaY < 0 && !isAtTop)) { e.stopPropagation(); e.preventDefault(); // Prevent the parent container from scrolling } }, { passive: false }); // Important for preventDefault to work // Mark this element as having a scroll handler attached (container as HTMLElement).setAttribute('data-scroll-handler-attached', 'true'); } }); // Update compose state setComposeBody(formattedContent); setLocalContent(formattedContent); console.log('[DEBUG] Successfully set compose content with scrollable message area'); } } 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', (e: Event) => { const wheelEvent = e as WheelEvent; const target = e.currentTarget as HTMLElement; // 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 ((wheelEvent.deltaY > 0 && !isAtBottom) || (wheelEvent.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); } } }; 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 */}
); }