// Email Profile Card Component
const { useState, useEffect } = React;

const EmailProfileCard = ({ profile, onRefresh, onRemove, onViewEmails }) => {
    const [emails, setEmails] = useState([]);
    const [loadingEmails, setLoadingEmails] = useState(true);

    const { isCrifSender, formatLastCheck } = ApiUtils;

    useEffect(() => {
        if (!profile?.id) return;
        setLoadingEmails(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(() => setLoadingEmails(false));
    }, [profile?.id, profile?.total_count]);

    const isFromJob = profile.source === 'job';
    const flowType = profile.crif_mode ? 'Email + CRIF' : 'Email';

    const isBlocked = profile.is_blocked;

    return (
        <Card className={`p-4 hover:shadow-md transition-shadow cursor-pointer ${isFromJob ? 'ring-1 ring-brand-200' : ''} ${isBlocked ? 'ring-2 ring-red-300 bg-red-50/30' : ''}`} onClick={() => onViewEmails(profile)}>
            {/* Header */}
            <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-3">
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center text-lg ${isBlocked ? 'bg-red-100' : 'bg-brand-100'}`}>
                        {isBlocked ? '🚫' : '📧'}
                    </div>
                    <div>
                        {profile.person_name && <div className="font-medium text-slate-900">{profile.person_name}</div>}
                        <div className={`text-sm ${profile.person_name ? 'text-slate-500' : 'font-medium text-slate-900'}`}>{profile.email_address}</div>
                        <div className="text-xs text-slate-400 flex items-center gap-2">
                            <span>{profile.provider}</span>
                            {isFromJob && <Badge variant="brand">Auto</Badge>}
                            {isBlocked && <Badge variant="error">Bloccato</Badge>}
                        </div>
                    </div>
                </div>
                <div className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium ${isBlocked ? 'bg-red-100 text-red-700' : emails.length > 0 ? 'bg-blue-100 text-blue-700' : 'bg-slate-100 text-slate-600'}`}>
                    <span>{loadingEmails ? '...' : emails.length}</span>
                    <span>email</span>
                </div>
            </div>

            {/* Error / Blocked status */}
            {isBlocked && (
                <div className="bg-red-100 border border-red-300 text-red-800 text-xs p-3 rounded-lg mb-3">
                    <div className="font-semibold mb-1">🚫 Account Bloccato</div>
                    <div className="text-red-600">Errore di autenticazione. {profile.error && `Dettaglio: ${profile.error}`}</div>
                </div>
            )}
            {profile.error && !isBlocked && <div className="bg-red-50 text-red-700 text-xs p-2 rounded mb-3">⚠️ {profile.error}</div>}

            {/* Email previews */}
            {loadingEmails ? (
                <div className="py-4 text-center text-slate-400 text-sm"><Spinner className="w-4 h-4 mx-auto mb-1" />Caricamento...</div>
            ) : emails.length > 0 ? (
                <div className="space-y-1.5 mb-3 max-h-32 overflow-y-auto">
                    {emails.slice(0, 3).map((email, idx) => {
                        const isCrif = isCrifSender(email);
                        return (
                            <div key={idx} className={`p-2 rounded text-xs ${isCrif ? 'bg-emerald-50 border border-emerald-200' : 'bg-slate-50'}`}>
                                <div className="flex items-center gap-2 mb-0.5">
                                    {isCrif && <Badge variant="success">CRIF</Badge>}
                                    <span className="font-medium text-slate-700 truncate">{email.sender_name || email.sender?.split('@')[0]}</span>
                                </div>
                                <div className="text-slate-600 truncate">{email.subject || '(Nessun oggetto)'}</div>
                            </div>
                        );
                    })}
                    {emails.length > 3 && <div className="text-xs text-center text-slate-400">+{emails.length - 3} altre</div>}
                </div>
            ) : !profile.error && (
                <div className="py-4 text-center text-slate-400 text-sm">📭 Nessuna email</div>
            )}

            {/* Footer */}
            <div className="flex items-center justify-between pt-2 border-t border-slate-100" onClick={e => e.stopPropagation()}>
                <span className="text-xs text-slate-400">Ultimo: {formatLastCheck(profile.last_check)}</span>
                <div className="flex items-center gap-1">
                    <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); onRefresh(profile.id); }}>🔄</Button>
                    <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); onViewEmails(profile); }}>📧 Leggi</Button>
                    <Button variant="ghost" size="sm" className="text-red-600" onClick={(e) => { e.stopPropagation(); onRemove(profile.id); }}>✕</Button>
                </div>
            </div>
        </Card>
    );
};

window.EmailProfileCard = EmailProfileCard;

