// ECO-PANNEAU.FR - _react/admin/_admin_messages.jsx

// 1. - LOGIQUE MÉTIER : GÉNÉRATION DES CONVERSATIONS ADMIN
window.pano_buildAdminChatThreads = (interactions, panneaux, clients) => {
    const threadsMap = {};
    const moderationMessages = [];

    interactions.forEach(m => {
        if (m.isAlert === 2) {
            moderationMessages.push(m);
            return; 
        }

        let threadId;
        let title = "Conversation";
        
        const isAdminOrSystem = m.authorType === 'Admin' || m.authorType === 'Système' || m.authorType === 'Systeme' || m.authorType === 'System';
        
        let targetEmail = isAdminOrSystem ? m.target : m.author;
        let type = 'contact';
        let unread = (!m.resolved && !isAdminOrSystem) ? 1 : 0;

        if (m.panneauId === 'CONTACT_PUBLIC') {
            const visitorEmail = isAdminOrSystem ? 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) : ''}`;
            targetEmail = c ? c.email : '';
            type = 'support';
        } else {
            return; 
        }

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

    if (moderationMessages.length > 0) {
        threadsMap['MODERATION_QUEUE'] = {
            id: 'MODERATION_QUEUE',
            panneauId: 'MODERATION_QUEUE',
            title: 'Modération en attente',
            targetEmail: 'Système d\'alerte',
            type: 'contact', 
            messages: moderationMessages,
            unread: moderationMessages.length,
            panneauData: null
        };
    }

    return Object.values(threadsMap).sort((a, b) => {
        if (a.id === 'MODERATION_QUEUE') return -1;
        if (b.id === 'MODERATION_QUEUE') return 1;

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

// 2. - COMPOSANT CARTE ISOLÉ ET RÉUTILISABLE (ZÉRO-DETTE)
window.pano_AdminMessageCard = ({ thread: t, isPinned, toggleDashboardPin, openChat }) => {
    const { MessageSquareIcon, MessageCircleIcon, MailIcon, AlertTriangleIcon, PinIcon } = window.pano_getIcons();
    const { IconBadge, NotificationBadge, DataCard } = window.pano_getComponents();

    const getThreadIcon = (type, threadId) => {
        if (threadId === 'MODERATION_QUEUE') return AlertTriangleIcon;
        switch(type) {
            case 'support': return MessageSquareIcon;
            case 'contact': return MailIcon;
            default: return MessageCircleIcon;
        }
    };

    const getThreadVariant = (type, threadId) => {
        if (threadId === 'MODERATION_QUEUE') return 'danger';
        switch(type) {
            case 'support': return 'success';
            case 'contact': return 'warning';
            default: return 'secondary';
        }
    };

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

    const lastMsg = t.messages.length > 0 ? t.messages[t.messages.length - 1] : null;
    const isModQueue = t.id === 'MODERATION_QUEUE';

    return (
        <DataCard 
            key={t.id} 
            variant={isModQueue ? 'danger' : 'default'}
            onClick={(e) => openChat(t.id, e)} 
            className="group gap-2 relative cursor-pointer p-3 transition-colors hover:border-emerald-300 min-w-0"
        >
            {/* ÉPINGLE VOLANTE ET INCLINÉE (INDIGO POUR LES MESSAGES) */}
            {!isModQueue && (
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); toggleDashboardPin && toggleDashboardPin('threads', t.id, e); }} 
                    className={`absolute top-2 right-2 z-20 p-1 cursor-pointer transition-all duration-200 ${isPinned ? 'text-indigo-500 opacity-100 hover:scale-110' : 'text-slate-300 opacity-0 group-hover:opacity-100 hover:text-slate-500 hover:scale-110'}`}
                    style={{ transform: 'rotate(30deg)' }}
                    title={isPinned ? "Désépingler" : "Épingler au tableau de bord"}
                >
                    <PinIcon size={18} filled={isPinned} />
                </div>
            )}

            <div className="flex justify-between items-start gap-2 mb-1 min-w-0">
                <div className="flex items-center gap-2 min-w-0 flex-1">
                    {IconBadge && (
                        <IconBadge 
                            icon={getThreadIcon(t.type, t.id)} 
                            variant={getThreadVariant(t.type, t.id)} 
                            size="md" 
                            className="shrink-0"
                        />
                    )}
                    <div className="min-w-0 flex-1">
                        <p className={`text-sm break-words leading-tight ${getThreadTitleClass(t.type, t.id)}`}>{t.title}</p>
                        {t.targetEmail && <p className="text-[10px] uppercase tracking-widest text-slate-400 font-bold mt-0.5 truncate">{t.targetEmail}</p>}
                    </div>
                </div>
                <div className="shrink-0 relative z-10 mt-1">
                    <NotificationBadge count={t.unread} />
                </div>
            </div>
            
            <div className="pt-2 border-t border-slate-100 flex-1 min-w-0">
                <div className={`text-sm max-h-16 overflow-y-auto custom-scrollbar break-words block ${t.unread > 0 ? 'text-slate-800 font-bold' : 'text-slate-600'}`}>
                    {isModQueue 
                        ? <span className="font-bold text-amber-600">{window.pano_formatPlural(t.unread, "Cliquez pour contrôler 1 message suspect.", `Cliquez pour contrôler ${t.unread} messages suspects.`)}</span> 
                        : (lastMsg ? lastMsg.detail.replace(/\[ATTACHMENT:[^\]]+\]/g, '[Pièce jointe]').replace(/<[^>]*>?/gm, '') : <span className="italic text-slate-400">Nouvelle conversation...</span>)
                    }
                </div>
            </div>
            
            <div className="text-[10px] font-bold text-slate-400 text-right mt-1 flex justify-between items-center min-w-0">
                <span className={`px-2 py-0.5 rounded uppercase tracking-wider shrink-0 ${isModQueue ? 'bg-amber-200 text-amber-800' : (t.type === 'support' ? 'bg-emerald-50 text-emerald-600' : 'bg-slate-100 text-slate-500')}`}>
                    {isModQueue ? 'Urgent' : t.type}
                </span>
                <span className="break-words leading-tight">{lastMsg ? new Date(String(lastMsg.created_at || '').replace(' ', 'T')).toLocaleString('fr-FR') : ''}</span>
            </div>
        </DataCard>
    );
};

// 3. - COMPOSANT PRINCIPAL : MESSAGERIE ADMIN
window.pano_AdminMessagesTab = ({ data, refreshData, showToast, adminOpts, toggleDashboardPin }) => {
    const { useState } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();
    
    // 3.1 - États et Routage Zéro-Dette
    const [isSaving, setIsSaving] = useState(false);
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    
    const routerActiveDialog = urlModal.activeDialog;
    const routerOpenDialog = urlModal.openDialog;
    const routerCloseLayer = urlModal.closeCurrentLayer;
    
    const [broadcastSubject, setBroadcastSubject] = useState("Message du support technique.");
    const [broadcastMessage, setBroadcastMessage] = useState("");
    const [adminPassword, setAdminPassword] = useState("");

    // 3.2 - Composants et Icônes
    const { 
        MessageSquareIcon, AlertTriangleIcon, SendIcon, LoaderIcon, PinIcon
    } = window.pano_getIcons();
    
    const {
        Button, Modal, FormInput, FormTextarea, 
        CardGrid, SearchBar, EmptySearch, PaginationFooter, AdminMessageCard
    } = window.pano_getComponents();

    // 3.3 - Logique de recherche et pagination
    const panneaux = data.panneaux || [];
    const clients = data.clients || [];
    const interactions = data.interactions || [];

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

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData 
    } = window.pano_useSearchAndPagination(threads, (t, q) => {
        const n = window.pano_normalizeString;
        const statusStr = n(t.unread > 0 ? "non lu urgent " : "lu ") + n(t.id === 'MODERATION_QUEUE' ? "moderation alerte" : "");
        return n(t.title).includes(q) || 
               n(t.targetEmail).includes(q) ||
               n(t.type).includes(q) ||
               statusStr.includes(q); 
    });

    // 3.4 - Actions
    const openChat = (id, e) => {
        if (e) { e.preventDefault(); e.stopPropagation(); }
        urlModal.openChat(id, false);
        if (refreshData) refreshData(); 
    };

    const handleBroadcastSubmit = async (e) => {
        e.preventDefault();
        if (!broadcastSubject.trim() || !broadcastMessage.trim() || !adminPassword) return;

        const d = await safeFetch('admin/broadcast', {
            body: { subject: broadcastSubject, message: broadcastMessage, password: adminPassword },
            setLoading: setIsSaving,
            successMessage: "Alerte globale diffusée avec succès !"
        });

        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit

        if (d) {
            setBroadcastSubject("Message du support technique.");
            setBroadcastMessage('');
            setAdminPassword('');
            routerCloseLayer();
            if (refreshData) refreshData();
        }
    };

    const pinnedIds = adminOpts?.threads || [];

    const attentionThreads = [];
    const pinnedThreads = [];
    const otherThreads = [];

    // CLASSIFICATION : URGENCE > FAVORIS > RESTE
    filteredData.forEach(t => {
        const isPinned = pinnedIds.includes(t.id);
        
        if (t.unread > 0 || t.id === 'MODERATION_QUEUE') {
            attentionThreads.push(t);
        } else if (isPinned) {
            pinnedThreads.push(t);
        } else {
            otherThreads.push(t);
        }
    });

    const displayedOtherThreads = otherThreads.slice(0, visibleCount);

    // 4. - RENDU UI
    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full overflow-x-hidden">
            
            {/* 4.1 - En-tête */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 min-w-0 w-full">
                <div className="min-w-0">
                    <h1 className="text-3xl font-black text-slate-800 break-words">Messagerie Globale</h1>
                    <p className="text-slate-500 font-medium break-words leading-relaxed">Vue globale du support et du contact public.</p>
                </div>
                
                {threads.length > 0 && SearchBar && (
                    <div className="w-full md:w-auto flex-1 flex justify-end gap-2 shrink-0">
                        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} placeholder="Rechercher (Nom, Statut)..." />
                        <Button variant="danger" icon={AlertTriangleIcon} onClick={() => { 
                            setAdminPassword(""); 
                            setBroadcastSubject("Message du support technique.");
                            routerOpenDialog('broadcast'); 
                        }} className="px-4 py-3 shrink-0 shadow-md">
                            <span className="hidden sm:inline">Diffuser une alerte</span>
                        </Button>
                    </div>
                )}
                {threads.length === 0 && (
                    <div className="flex gap-2 shrink-0">
                        <Button variant="danger" icon={AlertTriangleIcon} onClick={() => { 
                            setAdminPassword(""); 
                            setBroadcastSubject("Message du support technique.");
                            routerOpenDialog('broadcast'); 
                        }} className="px-4 py-2 shadow-md">
                            Diffuser une alerte
                        </Button>
                    </div>
                )}
            </div>

            {/* 4.2 - Liste des conversations */}
            {threads.length === 0 ? (
                <div className="p-10 text-center text-slate-500 bg-white rounded-3xl border border-slate-200 border-dashed min-w-0 w-full">
                    <MessageSquareIcon size={48} className="mx-auto mb-4 opacity-50"/>
                    <p className="font-medium break-words">Aucune conversation détectée sur la plateforme.</p>
                </div>
            ) : filteredData.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* A. PRIORITÉ */}
                    {attentionThreads.length > 0 && (
                        <div className="mb-8 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2 break-words">
                                <AlertTriangleIcon size={20} className="text-amber-500 shrink-0" /> Modération et Non lus
                            </h2>
                            <CardGrid minWidth="300px">
                                {attentionThreads.map(t => <AdminMessageCard key={t.id} thread={t} isPinned={pinnedIds.includes(t.id)} toggleDashboardPin={toggleDashboardPin} openChat={openChat} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* B. FAVORIS */}
                    {pinnedThreads.length > 0 && (
                        <div className="mb-8 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2 break-words">
                                <PinIcon size={20} className="text-indigo-600 shrink-0" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="300px">
                                {pinnedThreads.map(t => <AdminMessageCard key={t.id} thread={t} isPinned={pinnedIds.includes(t.id)} toggleDashboardPin={toggleDashboardPin} openChat={openChat} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* C. LE RESTE */}
                    {otherThreads.length > 0 && (
                        <div className="space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2 break-words">
                                <MessageSquareIcon size={20} className="text-blue-600 shrink-0" /> Historique des conversations
                            </h2>
                            <CardGrid minWidth="300px">
                                {displayedOtherThreads.map(t => <AdminMessageCard key={t.id} thread={t} isPinned={pinnedIds.includes(t.id)} toggleDashboardPin={toggleDashboardPin} openChat={openChat} />)}
                            </CardGrid>
                            
                            {PaginationFooter && (
                                <PaginationFooter 
                                    visibleCount={visibleCount} 
                                    setVisibleCount={setVisibleCount} 
                                    totalCount={otherThreads.length} 
                                    itemName="conversations" 
                                />
                            )}
                        </div>
                    )}
                </>
            )}

            {/* 4.3 - Modale : Diffusion d'alerte globale (Broadcast) */}
            {routerActiveDialog === 'broadcast' && Modal && (
                <Modal 
                    title="Diffusion d'alerte générale" 
                    type="error" 
                    onClose={routerCloseLayer} 
                    preventClose={isSaving} 
                    actions={(close) => (
                        <>
                            <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs shadow-sm">
                                Annuler
                            </Button>
                            <Button variant="dangerSolid" type="submit" form="broadcast-form" disabled={isSaving || !broadcastSubject.trim() || !broadcastMessage.trim() || !adminPassword} icon={isSaving ? LoaderIcon : SendIcon} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs text-center">
                                Diffuser à tous les clients
                            </Button>
                        </>
                    )}
                >
                    <form id="broadcast-form" onSubmit={handleBroadcastSubmit} className="space-y-4 min-w-0">
                        
                        <div className="space-y-4 animate-in fade-in zoom-in-95 duration-200 min-w-0">
                            {FormInput && (
                                <FormInput 
                                    label="Objet du message" 
                                    type="text"
                                    name="subject"
                                    autoComplete="off"
                                    value={broadcastSubject} 
                                    onChange={e => setBroadcastSubject(e.target.value)} 
                                    placeholder="Ex: Mise à jour importante de la plateforme..."
                                    required 
                                    disabled={isSaving}
                                    className="min-w-0 w-full"
                                />
                            )}

                            {FormTextarea && (
                                <FormTextarea 
                                    label="Message global" 
                                    value={broadcastMessage} 
                                    onChange={e => setBroadcastMessage(e.target.value)} 
                                    placeholder="Saisissez votre annonce générale..."
                                    rows={6}
                                    required 
                                    disabled={isSaving}
                                    className="min-w-0 w-full"
                                />
                            )}
                        </div>

                        <div className="bg-red-50 text-red-800 p-3 rounded-xl border border-red-100 text-xs font-medium flex items-start gap-3 mt-4 min-w-0">
                            <AlertTriangleIcon size={16} className="shrink-0 mt-0.5" />
                            <div className="min-w-0 break-words leading-relaxed">
                                <strong className="block mb-1">Attention :</strong>
                                Ce message sera envoyé par e-mail <strong>simultanément à tous les clients inscrits</strong>.
                            </div>
                        </div>

                        <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl space-y-3 mt-4 min-w-0">
                            {FormInput && (
                                <FormInput 
                                    label="Mot de passe administrateur (Sécurité requise)" 
                                    type="password" 
                                    value={adminPassword} 
                                    onChange={e => setAdminPassword(e.target.value)} 
                                    required 
                                    disabled={isSaving} 
                                    className="min-w-0 w-full"
                                />
                            )}
                        </div>
                    </form>
                </Modal>
            )}
        </div>
    );
};

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