// ECO-PANNEAU.FR - __react/socle/_socle_messagerie_ui.jsx

const { memo, useEffect } = React;

// 1. - UTILITAIRES ET MODALES TRANSVERSES
window.pano_ModerationModal = ({ word, onModify, onRequestControl }) => {
    const { ShieldIcon } = window.pano_getIcons();
    const { Button, Modal } = window.pano_getComponents();
    
    return (
        <Modal 
            title="Avertissement" 
            type="warning" 
            onClose={onModify} 
            maxWidth="max-w-md"
            actions={(close) => (
                <div className="flex flex-col gap-2 w-full">
                    <Button variant="secondary" onClick={close} className="w-full py-3 justify-center text-xs">
                        Modifier mon message
                    </Button>
                    <Button variant="warningSolid" icon={ShieldIcon} onClick={onRequestControl} className="w-full py-3 justify-center text-xs shadow-md">
                        Envoyer pour contrôle
                    </Button>
                </div>
            )}
        >
            <div className="text-sm text-slate-600 leading-relaxed break-words">
                À cause de l'utilisation de l'expression <strong className="text-red-500 break-all">"{word}"</strong>, vous devez modifier votre message. 
                <br/><br/>
                Vous avez également la possibilité de faire contrôler votre message par le support technique avant envoi au destinataire.
            </div>
        </Modal>
    );
};

window.pano_checkForBlacklist = (text, settings) => {
    if (!settings || !settings.blacklist) return null;
    
    const words = settings.blacklist.split(',')
        .map(w => w.trim().toLowerCase())
        .filter(w => w);
        
    const lowerText = text.toLowerCase();
    for (let w of words) {
        if (lowerText.includes(w)) return w;
    }
    
    return null;
};

// 2. - COMPOSANT : BULLE DE MESSAGE (MÉMORISÉE POUR PERFORMANCES)
window.pano_MessageBubble = memo(({ msg, isMe, displayAuthor, onImageLoad, onViewAttachment, isAdmin, onModerate, themeColor = '#059669', onAction, canDeleteAttachment, onDeleteAttachment }) => {
    const { AlertTriangleIcon, LoaderIcon, FileTextIcon, EditIcon, CheckCircleIcon, Trash2Icon } = window.pano_getIcons();
    const { Button, PdfThumbnail } = window.pano_getComponents();

    useEffect(() => {
        if (!window.DOMPurify && window.pano_logFallback) {
            window.pano_logFallback("DOMPurify introuvable dans MessageBubble. Utilisation du fallback regex pour la sécurisation HTML.");
        }
    }, []);

    const attachments = [];
    const deletedAttachments = [];
    
    // Capture des pièces jointes valides
    const regex = /\[ATTACHMENT:([a-zA-Z0-9_.\/-]+):(image|pdf)(?::(\d+))?\]/g;
    let match;
    while ((match = regex.exec(msg.detail || '')) !== null) {
        attachments.push({ id: match[1], type: match[2], numPages: match[3] ? parseInt(match[3], 10) : 1 });
    }

    // Capture robuste des pièces jointes supprimées
    const delRegex = /\[DELETED_ATTACHMENT(?::(image|pdf))?\]/g;
    let delMatch;
    while ((delMatch = delRegex.exec(msg.detail || '')) !== null) {
        deletedAttachments.push({ type: delMatch[1] || 'fichier' });
    }
    
    // Nettoyage complet du texte
    const textContent = (msg.detail || '').replace(regex, '').replace(delRegex, '').trim();
    const isHtmlAllowed = msg.authorType === 'Admin' || msg.authorType === 'Système' || msg.authorType === 'Systeme' || msg.authorType === 'System';

    const suspendRegex = /Le panneau "([^"]+)" a été (?:suspendu|rejeté)/i;
    const suspendMatch = textContent.match(suspendRegex);
    
    const isTemp = msg.id.toString().startsWith('temp_');

    const handleCorrigerClick = (e) => {
        e.preventDefault();
        // Délégation propre de l'action au composant parent
        if (onAction && suspendMatch) {
            onAction('correct_panel', suspendMatch[1]);
        }
    };

    const handleHtmlClick = (e) => {
        const grantBtn = e.target.closest('[data-action="grant_access"]');
        if (grantBtn) {
            e.preventDefault();
            e.stopPropagation();
            window.dispatchEvent(new CustomEvent('chat_grant_access'));
        }
    };

    return (
        <div className={`flex flex-col w-full ${isMe ? 'items-end' : 'items-start'} mb-4`}>
            {msg.isAlert === 2 && (
                <div className="bg-amber-100 text-amber-800 text-[10px] font-bold px-2 py-1 rounded-t-lg mb-0.5 flex flex-col sm:flex-row sm:items-center gap-2 w-fit max-w-[85%] sm:max-w-[70%]">
                    <span className="flex items-center gap-1 shrink-0"><AlertTriangleIcon size={12}/> En attente de contrôle</span>
                    {isAdmin && onModerate && (
                        <div className="flex items-center gap-1 sm:ml-auto">
                            <Button variant="successSolid" onClick={() => onModerate(msg.id, 'approve')} className="py-1 px-2 text-[9px] h-auto min-h-0 shadow-none rounded-md" icon={CheckCircleIcon}>
                                Valider
                            </Button>
                            <Button variant="dangerSolid" shape="round" onClick={() => onModerate(msg.id, 'reject')} className="p-1 h-auto min-h-0 shadow-none" icon={Trash2Icon} title="Rejeter" />
                        </div>
                    )}
                </div>
            )}
            
            <div 
                className={`max-w-[85%] sm:max-w-[70%] p-3 rounded-2xl flex flex-col shadow-sm ${
                    isMe 
                    ? 'text-white rounded-br-sm' 
                    : 'bg-white border border-slate-200 text-slate-700 rounded-bl-sm'
                } ${msg.isAlert === 2 && !isMe ? 'opacity-60 border-amber-300 bg-amber-50' : ''}`}
                style={isMe ? { backgroundColor: themeColor } : undefined}
            >
                
                {textContent && (
                    isHtmlAllowed ? (
                        <div 
                            onClick={handleHtmlClick}
                            dangerouslySetInnerHTML={{ 
                                __html: window.DOMPurify 
                                    ? window.DOMPurify.sanitize(textContent, { USE_PROFILES: { html: true } }) 
                                    : textContent.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
                            }} 
                            className="text-sm leading-relaxed whitespace-pre-wrap admin-html break-words" 
                        />
                    ) : (
                        <p className="text-sm leading-relaxed whitespace-pre-wrap break-words">{textContent}</p>
                    )
                )}

                {suspendMatch && msg.authorType === 'Admin' && !isMe && (
                    <div className="mt-3 pt-3 border-t border-slate-200/50 w-full">
                        <Button 
                            variant="primary" 
                            icon={EditIcon} 
                            onClick={handleCorrigerClick}
                            className="w-full justify-center py-2.5 shadow-md"
                        >
                            Corriger le panneau
                        </Button>
                    </div>
                )}
                
                {attachments.length > 0 && (
                    <div className={`mt-2 flex flex-wrap gap-2 ${textContent ? 'pt-2 border-t border-white/10' : ''}`}>
                        {attachments.map((att, i) => (
                            <React.Fragment key={i}>
                                {att.type === 'image' && (
                                    <div className="relative group shrink-0 max-w-full">
                                        <div onClick={() => onViewAttachment(att)} className="cursor-pointer">
                                            {/* ZÉRO-DETTE : Utilisation de preview=1 pour les images */}
                                            <img 
                                                src={`${window.pano_CONFIG.apiBaseUrl}file/download&type=image&id=${att.id}&preview=1`} 
                                                className={`rounded-lg max-h-48 max-w-full object-contain border transition-transform hover:scale-[1.02] ${isMe ? 'border-white/20 bg-black/10' : 'border-slate-200/50 bg-slate-50'}`} 
                                                alt="Pièce jointe" 
                                                loading="lazy"
                                                onLoad={onImageLoad}
                                            />
                                        </div>
                                        {canDeleteAttachment && onDeleteAttachment && (
                                            <Button 
                                                variant="danger" 
                                                shape="round" 
                                                icon={Trash2Icon}
                                                onClick={(e) => { e.stopPropagation(); onDeleteAttachment(msg.id, att.id, att.type); }}
                                                className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-all shadow-md p-1.5 w-7 h-7"
                                                title="Supprimer cette pièce jointe (Libérer de l'espace)"
                                            />
                                        )}
                                    </div>
                                )}
                                {att.type === 'pdf' && PdfThumbnail && (
                                    <div className="relative group shrink-0 w-32">
                                        <div onClick={() => onViewAttachment(att)} className={`cursor-pointer rounded-xl border flex flex-col text-left transition-transform hover:scale-[1.02] h-full ${isMe ? 'border-white/20 bg-black/10' : 'border-slate-200 bg-white'}`}>
                                            <PdfThumbnail id={att.id} />
                                            <div className={`p-2 flex items-center gap-1.5 shrink-0 border-t rounded-b-xl ${isMe ? 'border-white/20 text-white' : 'border-slate-100 text-slate-700'}`}>
                                                <FileTextIcon size={12} className="shrink-0" />
                                                <span className="text-[9px] font-bold break-words leading-tight">Aperçu PDF</span>
                                            </div>
                                        </div>
                                        {canDeleteAttachment && onDeleteAttachment && (
                                            <Button 
                                                variant="danger" 
                                                shape="round" 
                                                icon={Trash2Icon}
                                                onClick={(e) => { e.stopPropagation(); onDeleteAttachment(msg.id, att.id, att.type); }}
                                                className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-all shadow-md p-1.5 w-7 h-7"
                                                title="Supprimer cette pièce jointe (Libérer de l'espace)"
                                            />
                                        )}
                                    </div>
                                )}
                            </React.Fragment>
                        ))}
                    </div>
                )}

                {/* Affichage des pièces jointes supprimées */}
                {deletedAttachments.length > 0 && (
                    <div className={`mt-2 flex flex-col gap-2 ${textContent || attachments.length > 0 ? 'pt-2 border-t border-white/10' : ''}`}>
                        {deletedAttachments.map((att, i) => (
                            <div key={`del_${i}`} className={`p-3 rounded-xl flex items-center gap-3 border min-w-[200px] ${isMe ? 'bg-black/10 border-white/20 text-white' : 'bg-slate-100 border-slate-200 text-slate-500'}`}>
                                <div className={`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${isMe ? 'bg-black/20 text-white/50' : 'bg-slate-200 text-slate-400'}`}>
                                    <Trash2Icon size={20} />
                                </div>
                                <span className="text-xs font-medium italic leading-snug">
                                    Fichier supprimé par l'utilisateur pour libérer de l'espace.
                                </span>
                            </div>
                        ))}
                    </div>
                )}
            </div>
            
            {/* CORRECTION UX : Modification de l'horodatage pour l'envoi en cours */}
            <span className="text-[10px] font-bold text-slate-400 mt-1 px-1 flex items-center gap-1 break-words">
                {displayAuthor} • {isTemp ? <span className="italic text-slate-400">Envoi en cours...</span> : new Date(String(msg.created_at || '').replace(' ', 'T')).toLocaleString('fr-FR')}
                {isTemp && <LoaderIcon size={10} className="animate-spin inline text-slate-300 ml-1" />}
            </span>
        </div>
    );
}, (prevProps, nextProps) => {
    return prevProps.msg.id === nextProps.msg.id && 
           prevProps.msg.resolved === nextProps.msg.resolved && 
           prevProps.msg.isAlert === nextProps.msg.isAlert && 
           prevProps.isAdmin === nextProps.isAdmin &&
           prevProps.themeColor === nextProps.themeColor;
});

/* EOF ========== [__react/socle/_socle_messagerie_ui.jsx] */