import { useState, useRef } from 'react' import { Button } from '@/components/ui/Button' import { Card } from '@/components/ui/Card' import { X, Send, Paperclip, Sparkles, Loader2 } from 'lucide-react' interface ComposeModalProps { isOpen: boolean onClose: () => void replyTo?: { uid: number subject: string from: string body: string } onSent?: () => void } export function ComposeModal({ isOpen, onClose, replyTo, onSent }: ComposeModalProps) { const [to, setTo] = useState(replyTo ? extractEmail(replyTo.from) : '') const [subject, setSubject] = useState(replyTo ? `Re: ${replyTo.subject.replace(/^Re: /i, '')}` : '') const [body, setBody] = useState(replyTo ? `\n\n---\n${replyTo.body.substring(0, 500)}` : '') const [sending, setSending] = useState(false) const [aiLoading, setAiLoading] = useState(false) const [attachments, setAttachments] = useState([]) const fileInputRef = useRef(null) if (!isOpen) return null function extractEmail(from: string): string { const match = from.match(/<([^>]+)>/) return match ? match[1] : from } async function handleSend() { if (!to || !subject || !body) return setSending(true) try { const token = localStorage.getItem('amos_token') const res = await fetch('/api/v1/mail/send', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, body: JSON.stringify({ to: [to], subject, body, reply_to: replyTo?.from, }), }) const data = await res.json() if (data.ok) { setTo('') setSubject('') setBody('') setAttachments([]) onSent?.() onClose() } else { alert(data.error || 'Failed to send') } } catch (err) { alert('Failed to send email') } finally { setSending(false) } } async function handleAIAssist() { if (!body.trim()) return setAiLoading(true) try { const token = localStorage.getItem('amos_token') const res = await fetch('/api/v1/mail/ai-assist', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, body: JSON.stringify({ context: body, tone: 'professional', language: 'sv', }), }) const data = await res.json() if (data.ok && data.improved) { setBody(data.improved) } } catch (err) { console.error('AI assist failed:', err) } finally { setAiLoading(false) } } function handleFileSelect(e: React.ChangeEvent) { if (e.target.files) { setAttachments(Array.from(e.target.files)) } } return (
{/* Header */}

{replyTo ? 'Svara' : 'Nytt meddelande'}

{/* Form */}
setTo(e.target.value)} className="w-full h-10 px-3 rounded-xl border bg-surface text-sm text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20" placeholder="email@example.com" />
setSubject(e.target.value)} className="w-full h-10 px-3 rounded-xl border bg-surface text-sm text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20" placeholder="Ämne" />