/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Admin - Onglet : Messagerie Globale
 * =========================================================================
 */

// =========================================================================
// FACTORISATION : LOGIQUE MÉTIER DES MESSAGES ADMIN
// =========================================================================
window.pano_buildAdminChatThreads = (interactions, panneaux, clients) => {
    const threadsMap = {};

    interactions.forEach(m => {
        let threadId;
        let title = "Conversation";
        let targetEmail = (m.author === 'Admin' || m.author === 'Système' || m.author === 'Systeme') ? m.target : m.author;
        let type = 'riverain';
        let unread = (!m.resolved && m.author !== 'Admin' && m.author !== 'Système' && m.author !== 'Systeme') ? 1 : 0;
        let panneauData = null;

        if (m.panneauId === 'CONTACT_PUBLIC') {
            const visitorEmail = (m.author === 'Admin' || m.author === 'Système' || m.author === 'Systeme') ? m.target : m.author;
            threadId = `CONTACT_PUBLIC_${visitorEmail}`;
            title = `Contact Site : ${visitorEmail}`;
            targetEmail = visitorEmail;
            type = 'contact';
        } else if (m.panneauId.startsWith('SUPPORT_')) {
            threadId = m.panneauId;
            const cUid = m.panneauId.split('_')[1];
            const c = clients.find(cl => cl.id === cUid);
            title = `Support : ${c ? (c.company || c.name || c.full_name || c.email) : 'Client inconnu'}`;
            targetEmail = c ? c.email : 'Client';
            type = 'support';
        } else if (m.panneauId.startsWith('GROUP_')) {
            threadId = m.panneauId;
            const pId = m.panneauId.replace('GROUP_', '');
            panneauData = panneaux.find(pan => pan.id === pId);
            title = `Équipe : ${panneauData ? panneauData.name : 'Panneau introuvable'}`;
            targetEmail = 'Groupe';
            type = 'group';
        } else {
            const riverainEmail = (m.author === 'Client' || m.author === 'Admin' || m.author === 'Système' || m.author === 'Systeme') ? m.target : m.author;
            threadId = `${m.panneauId}_${riverainEmail}`;
            panneauData = panneaux.find(pan => pan.id === m.panneauId);
            title = `Riverain : ${panneauData ? panneauData.name : 'Panneau'}`;
            targetEmail = riverainEmail;
            type = 'riverain';
        }

        if (!threadsMap[threadId]) {
            threadsMap[threadId] = {
                id: threadId,
                panneauId: m.panneauId,
                title,
                targetEmail,
                type,
                messages: [],
                unread: 0,
                panneauData
            };
        }
        threadsMap[threadId].messages.push(m);
        threadsMap[threadId].unread += unread;
    });

    return Object.values(threadsMap).sort((a, b) => {
        const dateA = a.messages.length > 0 ? new Date(String(a.messages[a.messages.length - 1].created_at || '').replace(' ', 'T')).getTime() : 0;
        const dateB = b.messages.length > 0 ? new Date(String(b.messages[b.messages.length - 1].created_at || '').replace(' ', 'T')).getTime() : 0;
        return dateB - dateA;
    });
};

// =========================================================================
// COMPOSANT PRINCIPAL : MESSAGERIE ADMIN
// =========================================================================

window.pano_AdminMessagesTab = ({ data, refreshData, showToast }) => {
    const { useState, useEffect } = React;

    const [forceRender, setForceRender] = useState(0);
    useEffect(() => {
        const handlePop = () => setForceRender(f => f + 1);
        window.addEventListener('popstate', handlePop);
        return () => window.removeEventListener('popstate', handlePop);
    }, []);

    const { UsersIcon, MessageSquareIcon, MessageCircleIcon, MailIcon } = window.pano_getIcons();
    const IconBadge = window.pano_IconBadge || (() => null);

    const panneaux = data.panneaux || [];
    const clients = data.clients || [];
    const interactions = data.interactions || [];

    const threads = window.pano_buildAdminChatThreads(interactions, panneaux, clients);

    const openChat = (id) => {
        const u = new URL(window.location);
        u.searchParams.set('chat_id', id);
        window.history.pushState({ chat_id: id }, '', u);
        window.dispatchEvent(new Event('popstate'));
        if (refreshData) refreshData(); 
    };

    const getThreadIcon = (type) => {
        switch(type) {
            case 'support': return MessageSquareIcon;
            case 'group': return UsersIcon;
            case 'contact': return MailIcon;
            default: return MessageCircleIcon;
        }
    };

    const getThreadVariant = (type) => {
        switch(type) {
            case 'support': return 'success';
            case 'group': return 'info';
            case 'contact': return 'warning';
            default: return 'secondary';
        }
    };

    const getThreadTitleClass = (type) => {
        if (type === 'support') return 'font-black text-emerald-700';
        if (type === 'group') return 'font-black text-blue-700';
        if (type === 'contact') return 'font-black text-amber-700';
        return 'font-bold text-slate-800';
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex justify-between items-center mb-6">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Messagerie Globale</h1>
                    <p className="text-slate-500 font-medium">Vue globale (Support, Groupes, Riverains, Contact public).</p>
                </div>
            </div>

            <div className="grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))] gap-4">
                {threads.map(t => {
                    const lastMsg = t.messages.length > 0 ? t.messages[t.messages.length - 1] : null;
                    return (
                        <div 
                            key={t.id} 
                            onClick={() => openChat(t.id)} 
                            className="bg-white border border-slate-200 rounded-3xl p-5 cursor-pointer hover:border-emerald-300 hover:shadow-md transition flex flex-col gap-3 relative overflow-hidden group"
                        >
                            {t.unread > 0 && (
                                <span className="absolute top-4 right-4 bg-red-500 text-white w-6 h-6 flex items-center justify-center rounded-full text-xs font-black shadow-sm animate-pulse">
                                    {t.unread}
                                </span>
                            )}
                            
                            <div className="flex items-center gap-3">
                                {IconBadge && (
                                    <IconBadge 
                                        icon={getThreadIcon(t.type)} 
                                        variant={getThreadVariant(t.type)} 
                                        size="md" 
                                    />
                                )}
                                <div className="min-w-0 flex-1 pr-6">
                                    <p className={`text-sm truncate ${getThreadTitleClass(t.type)}`}>{t.title}</p>
                                    <p className="text-[10px] uppercase tracking-widest text-slate-400 font-bold truncate mt-0.5">{t.targetEmail}</p>
                                </div>
                            </div>
                            
                            <div className="pt-3 border-t border-slate-100 flex-1">
                                <p className={`text-sm line-clamp-2 ${t.unread > 0 ? 'text-slate-800 font-bold' : 'text-slate-600'}`}>
                                    {lastMsg ? lastMsg.detail.replace(/\[ATTACHMENT:[^\]]+\]/g, '[Pièce jointe]').replace(/<[^>]*>?/gm, '') : <span className="italic text-slate-400">Nouvelle conversation...</span>}
                                </p>
                            </div>
                            
                            <div className="text-[10px] font-bold text-slate-400 text-right mt-2 flex justify-between items-center">
                                <span className={`px-2 py-0.5 rounded uppercase tracking-wider ${t.type === 'support' ? 'bg-emerald-50 text-emerald-600' : (t.type === 'contact' ? 'bg-amber-50 text-amber-600' : 'bg-slate-100 text-slate-500')}`}>
                                    {t.type}
                                </span>
                                <span>{lastMsg ? new Date(String(lastMsg.created_at || '').replace(' ', 'T')).toLocaleString('fr-FR') : ''}</span>
                            </div>
                        </div>
                    );
                })}
                
                {threads.length === 0 && (
                    <div className="col-span-full p-12 text-center text-slate-500 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <MessageSquareIcon size={48} className="mx-auto mb-4 opacity-50"/>
                        <p className="font-medium">Aucune conversation détectée sur la plateforme.</p>
                    </div>
                )}
            </div>
        </div>
    );
};

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