// Email List Modal Component
const { useState, useEffect } = React;

const EmailListModal = ({ profile, onClose }) => {
    const [emails, setEmails] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (!profile) return;
        setLoading(true);
        fetch(`/profiles/${profile.id}/emails?unread_only=false`)
            .then(r => r.json())
            .then(data => {
                if (data.status === 'success') setEmails(data.emails || []);
            })
            .catch(console.error)
            .finally(() => setLoading(false));
    }, [profile]);

    if (!profile) return null;

    const { isCrifSender } = ApiUtils;

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
            <Card className="w-full max-w-2xl m-4 max-h-[80vh] flex flex-col" onClick={e => e.stopPropagation()}>
                <div className="p-4 border-b border-slate-200 flex items-center justify-between shrink-0">
                    <div>
                        <h3 className="font-semibold text-slate-900">📧 {profile.email_address}</h3>
                        {profile.person_name && <p className="text-sm text-slate-500">{profile.person_name}</p>}
                    </div>
                    <button className="text-slate-400 hover:text-slate-600 text-2xl" onClick={onClose}>×</button>
                </div>
                <div className="flex-1 overflow-y-auto p-4">
                    {loading ? (
                        <div className="text-center py-12">
                            <Spinner className="w-8 h-8 mx-auto text-brand-500" />
                            <p className="text-slate-500 mt-3">Caricamento email...</p>
                        </div>
                    ) : emails.length === 0 ? (
                        <div className="text-center py-12">
                            <div className="text-4xl mb-3">📭</div>
                            <p className="text-slate-500">Nessuna email</p>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {emails.map((email, idx) => {
                                const isCrif = isCrifSender(email);
                                return (
                                    <div key={idx} className={`p-3 rounded-lg border transition-colors hover:bg-slate-50 ${isCrif ? 'border-emerald-300 bg-emerald-50' : 'border-slate-200'}`}>
                                        <div className="flex items-start justify-between mb-1">
                                            <div className="flex items-center gap-2">
                                                {isCrif && <Badge variant="success">CRIF</Badge>}
                                                <span className="font-medium text-slate-900 text-sm">{email.sender_name || email.sender?.split('@')[0] || 'Sconosciuto'}</span>
                                            </div>
                                            <span className="text-xs text-slate-400">
                                                {(() => {
                                                    try {
                                                        const date = new Date(email.date);
                                                        return isNaN(date) ? '' : date.toLocaleDateString('it-IT', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });
                                                    } catch { return ''; }
                                                })()}
                                            </span>
                                        </div>
                                        <div className="font-medium text-slate-800 text-sm truncate">{email.subject || '(Nessun oggetto)'}</div>
                                        <div className="text-xs text-slate-500 truncate mt-0.5">{email.body_preview || ''}</div>
                                        {email.has_attachments && <div className="mt-1 text-xs text-brand-600">📎 Allegati</div>}
                                        {email.is_spam && <Badge variant="warning" className="mt-1">📁 {email.folder}</Badge>}
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>
            </Card>
        </div>
    );
};

window.EmailListModal = EmailListModal;

