/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Socle Messagerie (1/3) - Composants UI et Utilitaires (Bulles, Modération)
 * =========================================================================
 */

const { memo } = React;

// -------------------------------------------------------------------------
// UTILITAIRES ET MODALES TRANSVERSES
// -------------------------------------------------------------------------

window.pano_ModerationModal = ({ word, onModify, onRequestControl }) => {
    const { AlertTriangleIcon, ShieldIcon } = window.pano_getIcons();
    const Button = window.pano_Button;
    
    return (
        <div className="fixed inset-0 z-[999999] bg-slate-900/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in" onMouseDown={onModify}>
            <div className="bg-white rounded-2xl p-6 max-w-md w-full shadow-2xl" onMouseDown={e => e.stopPropagation()}>
                <div className="flex items-center gap-3 text-amber-600 mb-4">
                    <AlertTriangleIcon size={28} />
                    <h3 className="font-black text-xl text-slate-800">Avertissement</h3>
                </div>
                <div className="text-sm text-slate-600 mb-6 leading-relaxed">
                    À cause de l'utilisation de l'expression <strong className="text-red-500">"{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 client.
                </div>
                <div className="flex flex-col gap-3">
                    <Button variant="secondary" onClick={onModify} className="w-full py-3 justify-center">
                        Modifier mon message
                    </Button>
                    <Button variant="warning" icon={ShieldIcon} onClick={onRequestControl} className="w-full py-3 shadow-md justify-center">
                        Envoyer pour contrôle
                    </Button>
                </div>
            </div>
        </div>
    );
};

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;
};

// -------------------------------------------------------------------------
// COMPOSANT : BULLE DE MESSAGE (MÉMORISÉE POUR PERFORMANCES)
// -------------------------------------------------------------------------

window.pano_MessageBubble = memo(({ msg, isMe, displayAuthor, onImageLoad, onViewAttachment }) => {
    const { AlertTriangleIcon, LoaderIcon, FileTextIcon, EditIcon } = window.pano_getIcons();
    const Button = window.pano_Button;
    const PdfThumbnail = window.pano_PdfThumbnail;

    const attachments = [];
    const regex = /\[ATTACHMENT:([a-zA-Z0-9_.\/-]+):(image|pdf)\]/g;
    let match;
    
    while ((match = regex.exec(msg.detail || '')) !== null) {
        attachments.push({ id: match[1], type: match[2] });
    }
    
    const textContent = (msg.detail || '').replace(regex, '').trim();
    const isHtmlAllowed = msg.authorType === 'Admin' || msg.authorType === 'Système' || msg.authorType === 'Systeme';

    const suspendRegex = /Le panneau "([^"]+)" a été suspendu jusqu'à correction/;
    const suspendMatch = textContent.match(suspendRegex);

    const handleCorrigerClick = (e) => {
        e.preventDefault();
        const panelTab = Array.from(document.querySelectorAll('div[role="button"]')).find(el => el.textContent.includes('Mes panneaux'));
        if (panelTab) {
            panelTab.click(); 
            setTimeout(() => {
                const targetTitle = Array.from(document.querySelectorAll('h3')).find(h3 => h3.textContent.includes(suspendMatch[1]));
                if (targetTitle) {
                    const card = targetTitle.closest('.bg-white');
                    if (card) {
                        const corrigerBtn = Array.from(card.querySelectorAll('div[role="button"]')).find(btn => btn.textContent.includes('Corriger'));
                        if (corrigerBtn) corrigerBtn.click(); 
                    }
                }
            }, 150);
        } else {
            window.location.href = '?tab=panels';
        }
    };

    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 inline-flex items-center gap-1">
                    <AlertTriangleIcon size={12}/> En attente de contrôle
                </div>
            )}
            
            <div className={`max-w-[85%] sm:max-w-[70%] p-3 rounded-2xl flex flex-col shadow-sm ${
                isMe 
                ? 'bg-emerald-600 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' : ''}`}>
                
                {textContent && (
                    isHtmlAllowed ? (
                        <div 
                            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" 
                        />
                    ) : (
                        <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 !bg-emerald-600 hover:!bg-emerald-700 text-white shadow-md py-2.5"
                        >
                            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 onClick={() => onViewAttachment(att)} className="cursor-pointer shrink-0">
                                        <img 
                                            src={`${window.pano_CONFIG.apiBaseUrl}file/download&type=image&id=${att.id}`} 
                                            className={`rounded-lg max-h-48 object-contain border w-auto 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>
                                )}
                                {att.type === 'pdf' && PdfThumbnail && (
                                    <div onClick={() => onViewAttachment(att)} className={`cursor-pointer overflow-hidden rounded-xl border flex flex-col group text-left transition-transform hover:scale-[1.02] shrink-0 ${isMe ? 'border-white/20 bg-emerald-700/50' : 'border-slate-200 bg-white'} w-32`}>
                                        <PdfThumbnail id={att.id} />
                                        <div className={`p-2 flex items-center gap-1.5 shrink-0 border-t ${isMe ? 'border-white/20 text-white' : 'border-slate-100 text-slate-700'}`}>
                                            <FileTextIcon size={12} className="shrink-0" />
                                            <span className="text-[9px] font-bold truncate">Aperçu PDF</span>
                                        </div>
                                    </div>
                                )}
                            </React.Fragment>
                        ))}
                    </div>
                )}
            </div>
            
            <span className="text-[10px] font-bold text-slate-400 mt-1 px-1 flex items-center gap-1">
                {displayAuthor} • {new Date(String(msg.created_at || '').replace(' ', 'T')).toLocaleString('fr-FR')}
                {msg.id.toString().startsWith('temp_') && <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;
});

/* EOF ========== [_react/_socle_messagerie_ui.jsx] */