// ECO-PANNEAU.FR - _react/clients/_clients_modals_riverains.jsx

window.pano_ClientRiverainsListModal = ({ panneau, myClientData, interactions, onClose, refreshData, openLocalDialog }) => {
    const { useState } = React;
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};

    const { MessageCircleIcon, MailIcon, SettingsIcon, EyeIcon } = window.pano_getIcons();
    const { Modal, Button, EmptyState, DataCard, NotificationBadge } = window.pano_getComponents();

    const isOwner = panneau.client_uid === myClientData.id;
    
    // CORRECTION SÉCURITÉ : Identification stricte par UID (Zéro-Rétrocompatibilité)
    const myCollab = !isOwner ? panneau.collaborators?.find(c => c.uid === myClientData.id) : null;
    const canChat = isOwner || (myCollab && ['read', 'rw'].includes(myCollab.rights?.chat_access));

    if (!canChat) {
        return (
            <Modal title="Messages des riverains" type="error" onClose={onClose}>
                <p className="text-center text-slate-500 py-8 break-words">Vous n'avez pas accès à la messagerie de ce panneau.</p>
            </Modal>
        );
    }

    const riverainMessages = interactions.filter(m => m.panneauId === panneau.id && m.isAlert !== 2);
    
    const threadsMap = {};
    riverainMessages.forEach(m => {
        const visitorEmail = (m.authorType === 'Admin' || m.authorType === 'Systeme' || m.authorType === 'System' || (m.authorType === 'Client' && (m.author === 'Client' || m.author === myClientData.email || m.author === myClientData.full_name || m.author === myClientData.name || m.author === `${myClientData.full_name || 'Utilisateur'} (${myClientData.name || 'Société'})`))) ? m.target : m.author;
        
        if (!threadsMap[visitorEmail]) {
            threadsMap[visitorEmail] = { email: visitorEmail, unread: 0, messages: [], lastDate: null };
        }
        threadsMap[visitorEmail].messages.push(m);
        
        const isMyOwnMessage = (m.authorType === 'Client' && (m.author === 'Client' || m.author === myClientData.email || m.author === myClientData.full_name || m.author === myClientData.name || m.author === `${myClientData.full_name || 'Utilisateur'} (${myClientData.name || 'Société'})`));
        if (!m.resolved && !isMyOwnMessage && m.authorType !== 'Systeme' && m.authorType !== 'System') {
            threadsMap[visitorEmail].unread++;
        }
        threadsMap[visitorEmail].lastDate = new Date(String(m.created_at || '').replace(' ', 'T')).getTime();
    });

    const threads = Object.values(threadsMap).sort((a, b) => b.lastDate - a.lastDate);

    return (
        <Modal 
            title={`Riverains : ${panneau.name}`} 
            onClose={onClose}
            actions={(close) => (
                <Button variant="secondary" onClick={close} className="w-full py-3 justify-center text-xs shadow-sm">
                    Fermer
                </Button>
            )}
        >
            <div className="space-y-4 min-w-0">
                {threads.length === 0 ? (
                    <EmptyState icon={MessageCircleIcon} text="Aucun message de riverain pour l'instant." />
                ) : (
                    threads.map(t => (
                        <DataCard key={t.email} onClick={() => { onClose(); urlModal.openChat(`${panneau.id}_${t.email}`, false); }} className="cursor-pointer hover:border-amber-300 transition group p-4 border-slate-200 min-w-0">
                            <div className="flex justify-between items-start gap-2 mb-2 min-w-0">
                                <div className="flex items-center gap-3 min-w-0 flex-1">
                                    <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 bg-amber-50 text-amber-600">
                                        <MessageCircleIcon size={18} />
                                    </div>
                                    <div className="min-w-0 flex-1 pr-2">
                                        <p className="font-bold text-slate-800 break-words leading-tight">{t.email}</p>
                                        <p className="text-[10px] text-slate-500 uppercase tracking-widest mt-1 font-bold break-words">{window.pano_formatPlural(t.messages.length, 'message', 'messages')}</p>
                                    </div>
                                </div>
                                <div className="shrink-0 relative">
                                    {t.unread > 0 && <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'}`}>
                                    {t.messages[t.messages.length - 1].detail.replace(/\[ATTACHMENT:[^\]]+\]/g, '[Pièce jointe]').replace(/<[^>]*>?/gm, '')}
                                </div>
                            </div>
                        </DataCard>
                    ))
                )}
            </div>
        </Modal>
    );
};

/* EOF ========== [_react/clients/_clients_modals_riverains.jsx] */