'use client'; import { useState, useEffect } from 'react'; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Checkbox } from "@/components/ui/checkbox"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { Label } from "@/components/ui/label"; import { MoreVertical, Settings, Plus as PlusIcon, Trash2, Edit, Mail, Inbox, Send, Star, Trash, Plus, ChevronLeft, ChevronRight, Search, ChevronDown, Folder, ChevronUp, Reply, Forward, ReplyAll, MoreHorizontal, FolderOpen, X, Paperclip, MessageSquare } from 'lucide-react'; interface Account { id: number; name: string; email: string; color: string; } interface Email { id: number; accountId: number; from: string; fromName: string; to: string; subject: string; body: string; date: string; read: boolean; starred: boolean; category: string; } // Improved MIME Decoder Implementation for Infomaniak function extractBoundary(headers: string): string | null { const boundaryMatch = headers.match(/boundary="?([^"\r\n;]+)"?/i) || headers.match(/boundary=([^\r\n;]+)/i); return boundaryMatch ? boundaryMatch[1].trim() : null; } function decodeQuotedPrintable(text: string, charset: string): string { if (!text) return ''; // Replace soft line breaks (=\r\n or =\n or =\r) let decoded = text.replace(/=(?:\r\n|\n|\r)/g, ''); // Replace quoted-printable encoded characters (including non-ASCII characters) decoded = decoded.replace(/=([0-9A-F]{2})/gi, (match, p1) => { return String.fromCharCode(parseInt(p1, 16)); }); // Handle character encoding try { // For browsers with TextDecoder support if (typeof TextDecoder !== 'undefined') { // Convert string to array of byte values const bytes = new Uint8Array(Array.from(decoded).map(c => c.charCodeAt(0))); return new TextDecoder(charset).decode(bytes); } // Fallback for older browsers or when charset handling is not critical return decoded; } catch (e) { console.warn('Charset conversion error:', e); return decoded; } } function parseFullEmail(emailRaw: string) { // Check if this is a multipart message by looking for boundary definition const boundaryMatch = emailRaw.match(/boundary="?([^"\r\n;]+)"?/i) || emailRaw.match(/boundary=([^\r\n;]+)/i); if (boundaryMatch) { const boundary = boundaryMatch[1].trim(); // Check if there's a preamble before the first boundary let mainHeaders = ''; let mainContent = emailRaw; // Extract the headers before the first boundary if they exist const firstBoundaryPos = emailRaw.indexOf('--' + boundary); if (firstBoundaryPos > 0) { const headerSeparatorPos = emailRaw.indexOf('\r\n\r\n'); if (headerSeparatorPos > 0 && headerSeparatorPos < firstBoundaryPos) { mainHeaders = emailRaw.substring(0, headerSeparatorPos); } } return processMultipartEmail(emailRaw, boundary, mainHeaders); } else { // This is a single part message return processSinglePartEmail(emailRaw); } } function processMultipartEmail(emailRaw: string, boundary: string, mainHeaders: string = ''): { text: string; html: string; attachments: { filename: string; contentType: string; encoding: string; content: string; }[]; headers?: string; } { const result = { text: '', html: '', attachments: [] as { filename: string; contentType: string; encoding: string; content: string; }[], headers: mainHeaders }; // Split by boundary (more robust pattern) const boundaryRegex = new RegExp(`--${boundary}(?:--)?(\\r?\\n|$)`, 'g'); // Get all boundary positions const matches = Array.from(emailRaw.matchAll(boundaryRegex)); const boundaryPositions = matches.map(match => match.index!); // Extract content between boundaries for (let i = 0; i < boundaryPositions.length - 1; i++) { const startPos = boundaryPositions[i] + matches[i][0].length; const endPos = boundaryPositions[i + 1]; if (endPos > startPos) { const partContent = emailRaw.substring(startPos, endPos).trim(); if (partContent) { const decoded = processSinglePartEmail(partContent); if (decoded.contentType.includes('text/plain')) { result.text = decoded.text || ''; } else if (decoded.contentType.includes('text/html')) { result.html = cleanHtml(decoded.html || ''); } else if ( decoded.contentType.startsWith('image/') || decoded.contentType.startsWith('application/') ) { const filename = extractFilename(partContent); result.attachments.push({ filename, contentType: decoded.contentType, encoding: decoded.raw?.headers ? parseEmailHeaders(decoded.raw.headers).encoding : '7bit', content: decoded.raw?.body || '' }); } } } } return result; } function processSinglePartEmail(rawEmail: string) { // Split headers and body const headerBodySplit = rawEmail.split(/\r?\n\r?\n/); const headers = headerBodySplit[0]; const body = headerBodySplit.slice(1).join('\n\n'); // Parse headers to get content type, encoding, etc. const emailInfo = parseEmailHeaders(headers); // Decode the body based on its encoding const decodedBody = decodeMIME(body, emailInfo.encoding, emailInfo.charset); return { subject: extractHeader(headers, 'Subject'), from: extractHeader(headers, 'From'), to: extractHeader(headers, 'To'), date: extractHeader(headers, 'Date'), contentType: emailInfo.contentType, text: emailInfo.contentType.includes('html') ? null : decodedBody, html: emailInfo.contentType.includes('html') ? decodedBody : null, raw: { headers, body } }; } function extractHeader(headers: string, headerName: string): string { const regex = new RegExp(`^${headerName}:\\s*(.+?)(?:\\r?\\n(?!\\s)|$)`, 'im'); const match = headers.match(regex); return match ? match[1].trim() : ''; } function extractFilename(headers: string): string { const filenameMatch = headers.match(/filename="?([^"\r\n;]+)"?/i); return filenameMatch ? filenameMatch[1].trim() : 'attachment'; } function parseEmailHeaders(headers: string): { contentType: string; encoding: string; charset: string } { const result = { contentType: 'text/plain', encoding: '7bit', charset: 'utf-8' }; // Extract content type and charset const contentTypeMatch = headers.match(/Content-Type:\s*([^;]+)(?:;\s*charset=([^;"\r\n]+)|(?:;\s*charset="([^"]+)"))?/i); if (contentTypeMatch) { result.contentType = contentTypeMatch[1].trim().toLowerCase(); if (contentTypeMatch[2]) { result.charset = contentTypeMatch[2].trim().toLowerCase(); } else if (contentTypeMatch[3]) { result.charset = contentTypeMatch[3].trim().toLowerCase(); } } // Extract content transfer encoding const encodingMatch = headers.match(/Content-Transfer-Encoding:\s*([^\s;\r\n]+)/i); if (encodingMatch) { result.encoding = encodingMatch[1].trim().toLowerCase(); } return result; } function decodeMIME(text: string, encoding?: string, charset: string = 'utf-8'): string { if (!text) return ''; // Normalize encoding and charset encoding = (encoding || '').toLowerCase(); charset = (charset || 'utf-8').toLowerCase(); try { // Handle different encoding types if (encoding === 'quoted-printable') { return decodeQuotedPrintable(text, charset); } else if (encoding === 'base64') { return decodeBase64(text, charset); } else if (encoding === '7bit' || encoding === '8bit' || encoding === 'binary') { // For these encodings, we still need to handle the character set return convertCharset(text, charset); } else { // Unknown encoding, return as is but still handle charset return convertCharset(text, charset); } } catch (error) { console.error('Error decoding MIME:', error); return text; } } function decodeBase64(text: string, charset: string): string { const cleanText = text.replace(/\s/g, ''); let binaryString; try { binaryString = atob(cleanText); } catch (e) { console.error('Base64 decoding error:', e); return text; } return convertCharset(binaryString, charset); } function convertCharset(text: string, fromCharset: string): string { try { if (typeof TextDecoder !== 'undefined') { const bytes = new Uint8Array(text.length); for (let i = 0; i < text.length; i++) { bytes[i] = text.charCodeAt(i) & 0xFF; } let normalizedCharset = fromCharset.toLowerCase(); // Normalize charset names if (normalizedCharset === 'iso-8859-1' || normalizedCharset === 'latin1') { normalizedCharset = 'iso-8859-1'; } else if (normalizedCharset === 'windows-1252' || normalizedCharset === 'cp1252') { normalizedCharset = 'windows-1252'; } const decoder = new TextDecoder(normalizedCharset); return decoder.decode(bytes); } // Fallback for older browsers or unsupported charsets if (fromCharset.toLowerCase() === 'iso-8859-1' || fromCharset.toLowerCase() === 'windows-1252') { return text .replace(/\xC3\xA0/g, 'à') .replace(/\xC3\xA2/g, 'â') .replace(/\xC3\xA9/g, 'é') .replace(/\xC3\xA8/g, 'è') .replace(/\xC3\xAA/g, 'ê') .replace(/\xC3\xAB/g, 'ë') .replace(/\xC3\xB4/g, 'ô') .replace(/\xC3\xB9/g, 'ù') .replace(/\xC3\xBB/g, 'û') .replace(/\xC3\x80/g, 'À') .replace(/\xC3\x89/g, 'É') .replace(/\xC3\x87/g, 'Ç') .replace(/\xC2\xA0/g, ' '); } return text; } catch (e) { console.error('Character set conversion error:', e, 'charset:', fromCharset); return text; } } function extractHtmlBody(htmlContent: string): string { const bodyMatch = htmlContent.match(/]*>([\s\S]*?)<\/body>/i); return bodyMatch ? bodyMatch[1] : htmlContent; } function cleanHtml(html: string): string { if (!html) return ''; return html .replace(/ç/g, 'ç') .replace(/é/g, 'é') .replace(/è/g, 'ë') .replace(/ê/g, 'ª') .replace(/ë/g, '«') .replace(/û/g, '»') .replace(/ /g, ' ') .replace(/\xA0/g, ' '); } // Update the decodeMimeContent function to use the new implementation function decodeMimeContent(content: string): string { if (!content) return ''; try { // Handle the special case with InfomaniakPhpMail boundary if (content.includes('---InfomaniakPhpMail')) { const boundaryMatch = content.match(/---InfomaniakPhpMail[\w\d]+/); if (boundaryMatch) { const boundary = boundaryMatch[0]; const result = processMultipartEmail(content, boundary); return result.html || result.text || content; } } // Regular email parsing const result = parseFullEmail(content); if ('html' in result && result.html) { return extractHtmlBody(result.html); } else if ('text' in result && result.text) { return result.text; } // If parsing fails, try simple decoding if (content.includes('Content-Type:') || content.includes('Content-Transfer-Encoding:')) { const simpleDecoded = processSinglePartEmail(content); return simpleDecoded.text || simpleDecoded.html || content; } // Try to detect encoding and decode accordingly if (content.includes('=?UTF-8?B?') || content.includes('=?utf-8?B?')) { return decodeMIME(content, 'base64', 'utf-8'); } else if (content.includes('=?UTF-8?Q?') || content.includes('=?utf-8?Q?') || content.includes('=20')) { return decodeMIME(content, 'quoted-printable', 'utf-8'); } // If nothing else worked, return the original content return content; } catch (error) { console.error('Error decoding email content:', error); return content; } } export default function MailPage() { // Single IMAP account for now const [accounts, setAccounts] = useState([ { id: 1, name: 'Mail', email: 'contact@governance-labs.org', color: 'bg-blue-500' }, { id: 2, name: 'Work', email: 'work@governance-labs.org', color: 'bg-green-500' } ]); // State declarations const [selectedAccount, setSelectedAccount] = useState(1); const [currentView, setCurrentView] = useState('inbox'); const [selectedEmail, setSelectedEmail] = useState(null); const [sidebarOpen, setSidebarOpen] = useState(true); const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false); const [composeOpen, setComposeOpen] = useState(false); const [accountsDropdownOpen, setAccountsDropdownOpen] = useState(false); const [foldersDropdownOpen, setFoldersDropdownOpen] = useState(false); const [showAccountActions, setShowAccountActions] = useState(null); const [showEmailActions, setShowEmailActions] = useState(false); const [selectedEmails, setSelectedEmails] = useState([]); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [deleteType, setDeleteType] = useState<'email' | 'emails' | 'account'>('email'); const [itemToDelete, setItemToDelete] = useState(null); const [showBulkActions, setShowBulkActions] = useState(false); const [showCc, setShowCc] = useState(false); const [showBcc, setShowBcc] = useState(false); const [emails, setEmails] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [composeSubject, setComposeSubject] = useState(''); const [composeRecipient, setComposeRecipient] = useState(''); const [composeContent, setComposeContent] = useState(''); // Fetch emails from IMAP API useEffect(() => { async function fetchEmails() { try { setError(null); setLoading(true); const res = await fetch('/api/mail'); if (!res.ok) { throw new Error('Failed to fetch emails'); } const data = await res.json(); if (data.error) { throw new Error(data.error); } setEmails(data.messages || []); } catch (error) { console.error('Error fetching emails:', error); setError('Unable to load emails. Please try again later.'); } finally { setLoading(false); } } fetchEmails(); }, [currentView]); // Mock folders data const folders = [ { id: 1, name: 'Important' }, { id: 2, name: 'Work' }, { id: 3, name: 'Personal' }, { id: 4, name: 'Archive' } ]; // Modified accounts array with "All" option const allAccounts = [ { id: 0, name: 'All', email: '', color: 'bg-gray-500' }, ...accounts ]; // Filter emails based on selected account and view const filteredEmails = emails.filter(email => (selectedAccount === 0 || email.accountId === selectedAccount) && (currentView === 'starred' ? email.starred : email.category === currentView) ); // Format date for display const formatDate = (dateString: string) => { const date = new Date(dateString); const now = new Date(); if (date.toDateString() === now.toDateString()) { return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } else { return date.toLocaleDateString([], { month: 'short', day: 'numeric' }); } }; // Get account color const getAccountColor = (accountId: number) => { const account = accounts.find(acc => acc.id === accountId); return account ? account.color : 'bg-gray-500'; }; // Update email click handler to work without mark-read endpoint const handleEmailClick = (emailId: number) => { // Since the mark-read endpoint is not available, just update the UI const updatedEmails = emails.map(email => email.id === emailId ? { ...email, read: true } : email ); setEmails(updatedEmails); setSelectedEmail(emailId); }; // Toggle starred status const toggleStarred = async (emailId: number, e: React.MouseEvent) => { e.stopPropagation(); // Toggle star in IMAP try { await fetch('/api/mail/toggle-star', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ emailId }) }); } catch (error) { console.error('Error toggling star:', error); } const updatedEmails = emails.map(email => email.id === emailId ? { ...email, starred: !email.starred } : email ); setEmails(updatedEmails); }; // Handle bulk selection const toggleEmailSelection = (emailId: number, e: React.MouseEvent) => { e.stopPropagation(); setSelectedEmails(prev => prev.includes(emailId) ? prev.filter(id => id !== emailId) : [...prev, emailId] ); setShowBulkActions(true); }; // Handle select all const toggleSelectAll = () => { if (selectedEmails.length === filteredEmails.length) { setSelectedEmails([]); setShowBulkActions(false); } else { setSelectedEmails(filteredEmails.map(email => email.id)); setShowBulkActions(true); } }; // Handle bulk delete const handleBulkDelete = () => { setDeleteType('emails'); setShowDeleteConfirm(true); }; // Handle delete confirmation const handleDeleteConfirm = async () => { try { if (deleteType === 'email' && itemToDelete) { await fetch('/api/mail/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ emailIds: [itemToDelete] }) }); setEmails(emails.filter(email => email.id !== itemToDelete)); setSelectedEmail(null); } else if (deleteType === 'emails') { await fetch('/api/mail/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ emailIds: selectedEmails }) }); setEmails(emails.filter(email => !selectedEmails.includes(email.id))); setSelectedEmails([]); setShowBulkActions(false); } } catch (error) { console.error('Error deleting emails:', error); } setShowDeleteConfirm(false); }; // Get selected email const getSelectedEmail = () => { return emails.find(email => email.id === selectedEmail); }; // Add account management functions const handleAddAccount = () => { // Implementation for adding a new account }; const handleRemoveAccount = (accountId: number) => { setAccounts(accounts.filter(acc => acc.id !== accountId)); if (selectedAccount === accountId) { setSelectedAccount(accounts[0].id); } }; const handleEditAccount = (accountId: number, newName: string) => { setAccounts(accounts.map(acc => acc.id === accountId ? { ...acc, name: newName } : acc )); }; // Handle reply const handleReply = async (type: 'reply' | 'replyAll' | 'forward') => { const selectedEmailData = getSelectedEmail(); if (!selectedEmailData) return; setComposeOpen(true); const subject = `${type === 'forward' ? 'Fwd: ' : 'Re: '}${selectedEmailData.subject}`; let to = ''; let content = ''; switch (type) { case 'reply': to = selectedEmailData.from; content = `\n\nOn ${new Date(selectedEmailData.date).toLocaleString()}, ${selectedEmailData.fromName} wrote:\n> ${selectedEmailData.body.split('\n').join('\n> ')}`; break; case 'replyAll': to = selectedEmailData.from; // You would also need to add CC recipients here content = `\n\nOn ${new Date(selectedEmailData.date).toLocaleString()}, ${selectedEmailData.fromName} wrote:\n> ${selectedEmailData.body.split('\n').join('\n> ')}`; break; case 'forward': content = `\n\n---------- Forwarded message ----------\nFrom: ${selectedEmailData.fromName} <${selectedEmailData.from}>\nDate: ${new Date(selectedEmailData.date).toLocaleString()}\nSubject: ${selectedEmailData.subject}\n\n${selectedEmailData.body}`; break; } // Update compose form state (you'll need to add these state variables) setComposeSubject(subject); setComposeRecipient(to); setComposeContent(content); }; if (loading) { return (

Loading your emails...

); } if (error) { return (

{error}

); } return (
{/* Sidebar */}
{/* Courrier Title */}
COURRIER
{/* Compose button */}
{/* Accounts Section with Scrollable Content */}
{accountsDropdownOpen && (
{/* All Accounts Option */} {/* Mail Accounts List */} {accounts.map(account => (
{/* Account Actions Dropdown */} {showAccountActions === account.id && (
)}
))} {/* Add Account Button */}
)}
{/* Scrollable Navigation */}
{/* Main content */}
{/* Email list */}
{filteredEmails.length > 0 && ( )}

{currentView === 'starred' ? 'Starred' : currentView}

{filteredEmails.length} emails
{/* Bulk Actions Bar */} {showBulkActions && selectedEmails.length > 0 && (
{selectedEmails.length} selected
)} {/* Email List */} {filteredEmails.length > 0 ? (
    {filteredEmails.map(email => (
  • handleEmailClick(email.id)} >
    toggleEmailSelection(email.id, e)} />
    {email.fromName}
    {formatDate(email.date)}

    {email.subject}

    {decodeMimeContent(email.body)}

  • ))}
) : (

No emails in this folder

)}
{/* Email detail view */}
{selectedEmail ? (
{/* Email actions header */}
{/* Email content */}
{getSelectedEmail() && ( <>

{getSelectedEmail()?.subject}

{getSelectedEmail()?.fromName.charAt(0)}
{getSelectedEmail()?.fromName}
{getSelectedEmail()?.from} {new Date(getSelectedEmail()!.date).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })}

{decodeMimeContent(getSelectedEmail()?.body || '')}

)}
) : (

No email selected

Choose an email from the list to read its contents

)}
{/* Compose email modal */} {composeOpen && (
New Message
{!showCc && ( )} {!showBcc && ( )}
setComposeRecipient(e.target.value)} className="bg-white border-gray-200 py-1.5" />
{showCc && (
)} {showBcc && (
)}
setComposeSubject(e.target.value)} className="bg-white border-gray-200 py-1.5" />