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

window.pano_AdminDashboardTab = ({ data, refreshData, adminOpts, updateAdminOpts, toggleDashboardPin, setManagingPanneau, setValidationErrors, setPreviewPanneau }) => {
    const { useState, useEffect } = React;
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // CORRECTION ZÉRO-DETTE PERFORMANCE : Extraction centralisée des fonctions du routeur
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    const { openModal, openDialog, closeCurrentLayer, openChat, activeModal, activeDialog, targetId, dialogId } = urlModal;

    const [isSavingOrder, setIsSavingOrder] = useState(false);

    const { 
        ActivityIcon, UsersIcon, BuildingIcon, EyeIcon, MessageSquareIcon, MessageCircleIcon,
        TerminalIcon, ArchiveIcon, FileDigitIcon, AlertTriangleIcon, PackageIcon,
        PinIcon, ChevronUpIcon, ChevronDownIcon, SlidersHorizontalIcon, FileTextIcon, MailIcon, EditIcon, QrCodeIcon, KeyRoundIcon, ShieldAlertIcon, ShieldIcon
    } = window.pano_getIcons();

    const { 
        StatCard, Button, IconBadge, NotificationBadge, Modal, ConfirmModal,
        CardGrid, DataCard, TextLogo, StatusBadge,
        AdminPanelCard, AdminLogisticsCard, AdminMessageCard, AdminClientCard
    } = window.pano_getComponents();

    const [confirmDialog, setConfirmDialog] = useState(null);

    // CORRECTION : Retrait du bloc "maintenance" de l'ordre par défaut
    const defaultOrder = ['pinned', 'actions', 'stats', 'chats'];
    const currentOrder = adminOpts?.dashboard_order || defaultOrder;
    const currentActionsMode = adminOpts?.actions_mode || 'mini';
    
    const [tempOrder, setTempOrder] = useState(currentOrder);
    const [tempActionsMode, setTempActionsMode] = useState(currentActionsMode);

    useEffect(() => {
        setTempOrder(currentOrder);
        setTempActionsMode(currentActionsMode);
    }, [JSON.stringify(currentOrder), currentActionsMode]);

    const blockNames = {
        pinned: "Favoris (Épinglés)",
        actions: "À traiter en priorité",
        stats: "Vue d'ensemble de la plateforme",
        chats: "Conversations récentes"
    };

    const moveBlock = (index, dir) => {
        const newOrder = [...tempOrder];
        if (dir === 'up' && index > 0) {
            [newOrder[index-1], newOrder[index]] = [newOrder[index], newOrder[index-1]];
        } else if (dir === 'down' && index < newOrder.length - 1) {
            [newOrder[index+1], newOrder[index]] = [newOrder[index], newOrder[index+1]];
        }
        setTempOrder(newOrder);
    };

    const saveOrder = async (e) => {
        setIsSavingOrder(true);
        if (updateAdminOpts) {
            await updateAdminOpts({ ...adminOpts, dashboard_order: tempOrder, actions_mode: tempActionsMode });
        }
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        setIsSavingOrder(false);
        if (closeCurrentLayer) closeCurrentLayer(e);
    };

    const clients = data.clients || [];
    const panneaux = data.panneaux || [];
    const interactions = data.interactions || [];
    
    const regularPanneaux = panneaux.filter(p => p.id !== 'demo-panneau' && p.status !== 'Brouillon');
    const activePanneaux = panneaux.filter(p => p.status === 'Actif' && p.id !== 'demo-panneau');
    const draftPanneaux = panneaux.filter(p => p.status === 'Brouillon' && p.id !== 'demo-panneau');
    const mrr = activePanneaux.filter(p => p.offerType === 'rental').reduce((sum, p) => sum + (p.currentRate || 0), 0);

    const threads = window.pano_buildAdminChatThreads ? window.pano_buildAdminChatThreads(interactions, panneaux, clients) : [];

    const checkPanelViolations = (p) => {
        const blacklist = (data.settings?.blacklist || '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
        const greylist = (data.settings?.greylist || '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
        let blackCount = 0; let greyCount = 0;
        const textToSearch = [p.name, p.location, p.description, p.maitreOuvrage].filter(Boolean).join(' ').toLowerCase();
        const detected = { black: [], grey: [] };
        
        const containsWord = (text, word) => {
            const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(`\\b${escapedWord}\\b`, 'iu');
            return regex.test(text);
        };
        
        blacklist.forEach(word => { if(containsWord(textToSearch, word)) { blackCount++; detected.black.push(word); } });
        greylist.forEach(word => { if(containsWord(textToSearch, word)) { greyCount++; detected.grey.push(word); } });
        
        return { isViolation: blackCount > 0 || greyCount > 2, detected };
    };

    // CORRECTION : Prise en compte de la violation sémantique pour la remonter en "Action requise" sur le Dashboard
    const pendingPanels = regularPanneaux.filter(p => {
        const { isViolation } = checkPanelViolations(p);
        return p.status === 'Attente validation' || (!p.admin_seen && p.status === 'Actif') || isViolation;
    });
    
    const limitShippingForce = parseInt(data.settings?.limit_shipping_force || 90, 10);

    const pendingLogistics = regularPanneaux.filter(p => {
        if (p.physicalPanels <= 0) return false;
        const currentStatus = p.shipping_status || 'En attente de validation';
        if (['En attente de validation', 'Maquette refusée', 'En attente de commande au fournisseur', "En attente d'impression"].includes(currentStatus)) return true;
        if (currentStatus === 'Expédié' && p.updated_at) {
            const updateTime = new Date(p.updated_at.replace(' ', 'T')).getTime();
            const daysSince = (Date.now() - updateTime) / (1000 * 3600 * 24);
            return daysSince > limitShippingForce;
        }
        return false;
    });

    const attentionThreads = threads.filter(t => t.unread > 0 || t.id === 'MODERATION_QUEUE');
    const totalActionsRequises = pendingPanels.length + pendingLogistics.length + attentionThreads.length;
    const dashboardThreads = [...threads].filter(t => t.id !== 'MODERATION_QUEUE').slice(0, 5);

    const unreadMessagesCount = interactions.filter(m => 
        m.isAlert === 2 || (!m.resolved && m.authorType !== 'Admin' && m.authorType !== 'Systeme' && m.authorType !== 'System')
    ).length;

    const unreadMap = {};
    threads.forEach(t => {
        if (t.unread > 0 && t.type === 'support') {
            const cuid = t.id.replace('SUPPORT_', '');
            if (!unreadMap[cuid]) unreadMap[cuid] = { support: 0 };
            unreadMap[cuid].support += t.unread;
        }
    });

    const renderPinnedBlock = () => {
        const pinnedPanelsIds = adminOpts?.panels || [];
        const pinnedDeliveriesIds = adminOpts?.deliveries || [];
        const pinnedInvoicesIds = adminOpts?.invoices || [];
        const pinnedClientsIds = adminOpts?.clients || [];
        const pinnedThreadsIds = adminOpts?.threads || [];

        const pinnedPanels = (data.panneaux || []).filter(p => pinnedPanelsIds.includes(p.id));
        const pinnedDeliveries = (data.panneaux || []).filter(p => pinnedDeliveriesIds.includes(p.id));
        const pinnedInvoices = (data.invoices || []).filter(i => pinnedInvoicesIds.includes(i.invoice_ref || i.invoiceNumber));
        const pinnedClients = (data.clients || []).filter(c => pinnedClientsIds.includes(c.id));
        const pinnedChats = threads.filter(t => pinnedThreadsIds.includes(t.id));

        const totalPinned = pinnedPanels.length + pinnedDeliveries.length + pinnedInvoices.length + pinnedClients.length + pinnedChats.length;
        if (totalPinned === 0) return null;

        return (
            <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">
                    <PinIcon size={20} className="text-emerald-600" filled /> Favoris Administrateur
                </h2>
                <CardGrid minWidth="280px">
                    {pinnedPanels.map(p => {
                        const { isViolation, detected } = checkPanelViolations(p);
                        return (
                            <AdminPanelCard
                                key={`pin_pan_${p.id}`}
                                panel={p}
                                clients={clients}
                                isPinned={true}
                                toggleDashboardPin={toggleDashboardPin}
                                unreadSupport={unreadMap[p.clientName]?.support || 0}
                                needsControl={p.status === 'Attente validation' || (!p.admin_seen && p.status === 'Actif')}
                                hasBeenSuspended={(p.suspend_count || 0) > 0}
                                isViolation={isViolation}
                                detected={detected}
                                refreshData={refreshData}
                                setManagingPanneau={setManagingPanneau}
                                setValidationErrors={setValidationErrors}
                                openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat} activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                            />
                        );
                    })}

                    {pinnedDeliveries.map(c => (
                        <AdminLogisticsCard
                            key={`pin_del_${c.id}`}
                            delivery={c}
                            clients={clients}
                            isPinned={true}
                            toggleDashboardPin={toggleDashboardPin}
                            refreshData={refreshData}
                            limitShippingForce={limitShippingForce}
                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                        />
                    ))}

                    {AdminClientCard && pinnedClients.map(c => (
                        <AdminClientCard 
                            key={`pin_cli_${c.id}`} 
                            client={c} 
                            data={data}
                            isPinned={true} 
                            toggleDashboardPin={toggleDashboardPin}
                            unreadSupport={unreadMap[c.id]?.support || 0}
                            refreshData={refreshData}
                            openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat} activeDialog={activeDialog} dialogId={dialogId}
                        />
                    ))}

                    {pinnedInvoices.map(inv => {
                        const ref = inv.invoice_ref || inv.invoiceNumber;
                        return (
                            <DataCard key={`pin_inv_${ref}`} onClick={() => urlModal.changeTab('factures')} className="cursor-pointer hover:border-amber-300 transition group p-4 min-w-0">
                                <div className="flex justify-between items-start">
                                    <div className="flex items-center gap-3 min-w-0 pr-2">
                                        <IconBadge icon={FileTextIcon} variant="warning" size="md" className="shrink-0" />
                                        <div className="min-w-0">
                                            <h3 className="font-black text-slate-800 text-lg break-words leading-tight">{inv.amount} €</h3>
                                            <p className="text-[10px] text-slate-500 uppercase tracking-widest mt-0.5 break-words">{inv.type}</p>
                                        </div>
                                    </div>
                                    <button onClick={(e) => { e.stopPropagation(); toggleDashboardPin('invoices', ref, e); }} className="text-amber-500 hover:text-amber-600 p-1 bg-amber-50 rounded-full shrink-0"><PinIcon size={14} filled /></button>
                                </div>
                            </DataCard>
                        );
                    })}

                    {pinnedChats.map(t => (
                        <AdminMessageCard
                            key={`pin_chat_${t.id}`}
                            thread={t}
                            isPinned={true}
                            toggleDashboardPin={toggleDashboardPin}
                            openChat={(id) => openChat(id, false)}
                        />
                    ))}
                </CardGrid>
            </div>
        );
    };

    const renderActionsBlock = () => {
        if (totalActionsRequises === 0) return null;

        const pendingPanelsExtra = pendingPanels.length > 4 ? pendingPanels.length - 4 : 0;
        const pendingLogisticsExtra = pendingLogistics.length > 4 ? pendingLogistics.length - 4 : 0;
        const attentionThreadsExtra = attentionThreads.length > 4 ? attentionThreads.length - 4 : 0;

        if (currentActionsMode === 'full') {
            return (
                <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">
                        <AlertTriangleIcon size={20} className="text-amber-500" /> À traiter en priorité
                    </h2>

                    {pendingPanels.length > 0 && (
                        <div className="space-y-3">
                            <h3 className="text-sm font-bold text-slate-500 uppercase tracking-widest">Panneaux à valider</h3>
                            <CardGrid minWidth="320px">
                                {pendingPanels.slice(0, 4).map(p => {
                                    const { isViolation, detected } = checkPanelViolations(p);
                                    return (
                                        <AdminPanelCard
                                            key={`pan_full_${p.id}`}
                                            panel={p}
                                            clients={clients}
                                            isPinned={adminOpts?.panels?.includes(p.id)}
                                            toggleDashboardPin={toggleDashboardPin}
                                            unreadSupport={unreadMap[p.clientName]?.support || 0}
                                            needsControl={p.status === 'Attente validation' || (!p.admin_seen && p.status === 'Actif')}
                                            hasBeenSuspended={(p.suspend_count || 0) > 0}
                                            isViolation={isViolation}
                                            detected={detected}
                                            refreshData={refreshData}
                                            setManagingPanneau={setManagingPanneau}
                                            setValidationErrors={setValidationErrors}
                                            openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} openChat={openChat} activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                                        />
                                    );
                                })}
                                {pendingPanelsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => urlModal.changeTab('panneaux')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                                        <p className="font-bold text-emerald-600 break-words text-center">
                                            {`+ ${pendingPanelsExtra} ${pendingPanelsExtra > 1 ? 'autres panneaux' : 'autre panneau'}`}
                                        </p>
                                    </DataCard>
                                )}
                            </CardGrid>
                        </div>
                    )}

                    {pendingLogistics.length > 0 && (
                        <div className="space-y-3 mt-6">
                            <h3 className="text-sm font-bold text-slate-500 uppercase tracking-widest">Logistique</h3>
                            <CardGrid minWidth="320px">
                                {pendingLogistics.slice(0, 4).map(p => (
                                    <AdminLogisticsCard
                                        key={`log_full_${p.id}`}
                                        delivery={p}
                                        clients={clients}
                                        isPinned={adminOpts?.deliveries?.includes(p.id)}
                                        toggleDashboardPin={toggleDashboardPin}
                                        refreshData={refreshData}
                                        limitShippingForce={limitShippingForce}
                                        openModal={openModal} openDialog={openDialog} closeCurrentLayer={closeCurrentLayer} activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                                    />
                                ))}
                                {pendingLogisticsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => urlModal.changeTab('logistique')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                                        <p className="font-bold text-emerald-600 break-words text-center">
                                            {`+ ${pendingLogisticsExtra} ${pendingLogisticsExtra > 1 ? 'autres commandes' : 'autre commande'}`}
                                        </p>
                                    </DataCard>
                                )}
                            </CardGrid>
                        </div>
                    )}

                    {attentionThreads.length > 0 && (
                        <div className="space-y-3 mt-6">
                            <h3 className="text-sm font-bold text-slate-500 uppercase tracking-widest">Messages non lus</h3>
                            <CardGrid minWidth="320px">
                                {attentionThreads.slice(0, 4).map(t => (
                                    <AdminMessageCard
                                        key={`msg_full_${t.id}`}
                                        thread={t}
                                        isPinned={adminOpts?.threads?.includes(t.id)}
                                        toggleDashboardPin={toggleDashboardPin}
                                        openChat={(id) => openChat(id, false)}
                                    />
                                ))}
                                {attentionThreadsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => urlModal.changeTab('messages')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                                        <p className="font-bold text-emerald-600 break-words text-center">
                                            {`+ ${attentionThreadsExtra} ${attentionThreadsExtra > 1 ? 'autres conversations' : 'autre conversation'}`}
                                        </p>
                                    </DataCard>
                                )}
                            </CardGrid>
                        </div>
                    )}
                </div>
            );
        }

        return (
            <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">
                    <AlertTriangleIcon size={20} className="text-amber-500" /> À traiter en priorité
                </h2>
                <CardGrid minWidth="280px">
                    
                    {pendingPanels.slice(0, 4).map(p => (
                        <DataCard key={`pan_mini_${p.id}`} variant={p.status === 'Attente validation' ? 'danger' : 'info'} onClick={() => urlModal.changeTab('panneaux')} className="cursor-pointer group hover:scale-[1.02] transition-transform min-w-0">
                            <div className="flex items-center gap-3 min-w-0">
                                <IconBadge icon={BuildingIcon} variant={p.status === 'Attente validation' ? 'danger' : 'info'} size="md" className="shrink-0" />
                                <div className="min-w-0 flex-1">
                                    <p className={`font-bold text-sm break-words leading-tight ${p.status === 'Attente validation' ? 'text-red-900' : 'text-blue-900'}`}>
                                        {p.name || 'Projet sans nom'}
                                    </p>
                                    <div className="flex flex-wrap items-center gap-2 mt-1">
                                        <span className={`text-[10px] font-bold uppercase tracking-widest ${p.status === 'Attente validation' ? 'text-red-700' : 'text-blue-700'}`}>
                                            {p.status === 'Attente validation' ? 'Validation requise' : 'Contrôle requis'}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </DataCard>
                    ))}
                    {pendingPanelsExtra > 0 && (
                        <DataCard variant="default" onClick={() => urlModal.changeTab('panneaux')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                            <p className="font-bold text-emerald-600 break-words text-center">
                                {`+ ${pendingPanelsExtra} ${pendingPanelsExtra > 1 ? 'autres panneaux' : 'autre panneau'}`}
                            </p>
                        </DataCard>
                    )}

                    {pendingLogistics.slice(0, 4).map(p => {
                        const currentStatus = p.shipping_status || 'En attente de validation';
                        const isRefused = currentStatus === 'Maquette refusée';
                        return (
                            <DataCard key={`log_mini_${p.id}`} variant={isRefused ? 'danger' : 'warning'} onClick={() => urlModal.changeTab('logistique')} className="cursor-pointer group hover:scale-[1.02] transition-transform min-w-0">
                                <div className="flex items-center gap-3 min-w-0">
                                    <IconBadge icon={PackageIcon} variant={isRefused ? 'danger' : 'warning'} size="md" className="shrink-0" />
                                    <div className="min-w-0 flex-1">
                                        <p className={`font-bold text-sm break-words leading-tight ${isRefused ? 'text-red-900' : 'text-amber-900'}`}>
                                            {p.name}
                                        </p>
                                        <p className={`text-[10px] mt-0.5 break-words leading-tight ${isRefused ? 'text-red-700' : 'text-amber-700'}`}>
                                            Logistique: {currentStatus === 'Expédié' ? `Non réceptionné (> ${limitShippingForce}j)` : currentStatus}
                                        </p>
                                    </div>
                                </div>
                            </DataCard>
                        );
                    })}
                    {pendingLogisticsExtra > 0 && (
                        <DataCard variant="default" onClick={() => urlModal.changeTab('logistique')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                            <p className="font-bold text-emerald-600 break-words text-center">
                                {`+ ${pendingLogisticsExtra} ${pendingLogisticsExtra > 1 ? 'autres commandes' : 'autre commande'}`}
                            </p>
                        </DataCard>
                    )}

                    {attentionThreads.slice(0, 4).map(t => (
                        <DataCard key={`msg_mini_${t.id}`} variant={t.id === 'MODERATION_QUEUE' ? 'danger' : 'warning'} onClick={(e) => {
                            if (e) { e.preventDefault(); e.stopPropagation(); }
                            openChat(t.id, false);
                        }} className="cursor-pointer group hover:scale-[1.02] transition-transform min-w-0">
                            <div className="flex items-center gap-3 min-w-0">
                                <IconBadge icon={t.id === 'MODERATION_QUEUE' ? AlertTriangleIcon : MessageSquareIcon} variant={t.id === 'MODERATION_QUEUE' ? 'danger' : 'warning'} size="md" className="shrink-0" />
                                <div className="min-w-0 flex-1">
                                    <p className={`font-bold text-sm break-words leading-tight ${t.id === 'MODERATION_QUEUE' ? 'text-red-900' : 'text-amber-900'}`}>
                                        {t.id === 'MODERATION_QUEUE' ? 'Modération requise' : 'Nouveau message'}
                                    </p>
                                    <p className={`text-[10px] mt-0.5 break-words leading-tight ${t.id === 'MODERATION_QUEUE' ? 'text-red-700' : 'text-amber-700'}`}>{t.title}</p>
                                </div>
                            </div>
                        </DataCard>
                    ))}
                    {attentionThreadsExtra > 0 && (
                        <DataCard variant="default" onClick={() => urlModal.changeTab('messages')} className="cursor-pointer group flex items-center justify-center hover:scale-[1.02] transition-transform min-w-0">
                            <p className="font-bold text-emerald-600 break-words text-center">
                                {`+ ${attentionThreadsExtra} ${attentionThreadsExtra > 1 ? 'autres conversations' : 'autre conversation'}`}
                            </p>
                        </DataCard>
                    )}
                </CardGrid>
            </div>
        );
    };

    const renderStatsBlock = () => (
        <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">
                <ActivityIcon size={20} className="text-blue-600" /> Vue d'ensemble de la plateforme
            </h2>
            <CardGrid minWidth="260px">
                <StatCard title="MRR (revenus loc.)" value={`${mrr} €`} icon={<ActivityIcon size={24}/>} variant="success" />
                <StatCard title="Clients inscrits" value={clients.length} icon={<UsersIcon size={24}/>} variant="info" onClick={() => urlModal.changeTab('clients')} />
                <StatCard title="Panneaux actifs" value={activePanneaux.length} icon={<BuildingIcon size={24}/>} variant="indigo" onClick={() => urlModal.changeTab('panneaux')} />
                <StatCard title="Brouillons (Non payés)" value={draftPanneaux.length} icon={<EditIcon size={24}/>} variant="secondary" />
                <StatCard title="Total scans QR" value={data.stats?.totalViews || 0} icon={<EyeIcon size={24}/>} variant="warning" />
            </CardGrid>
        </div>
    );

    const renderChatsBlock = () => (
        <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 min-w-0 w-full">
            <div className="flex justify-between items-center mb-6 min-w-0">
                <h3 className="font-black text-slate-800 flex items-center gap-2 break-words">
                    <MessageSquareIcon size={18} className="text-emerald-600 shrink-0"/> Conversations récentes
                </h3>
                <span role="button" tabIndex={0} onClick={() => urlModal.changeTab('messages')} className="text-xs font-bold text-emerald-600 hover:underline cursor-pointer shrink-0 ml-2">Voir tout</span>
            </div>
            <div className="space-y-3 min-w-0">
                {dashboardThreads.map(t => (
                    <AdminMessageCard
                        key={t.id}
                        thread={t}
                        isPinned={adminOpts?.threads?.includes(t.id)}
                        toggleDashboardPin={toggleDashboardPin}
                        openChat={(id) => openChat(id, false)}
                    />
                ))}
                {dashboardThreads.length === 0 && (
                    <p className="text-sm text-slate-400 italic text-center py-8 bg-slate-50 rounded-2xl border border-slate-200 border-dashed break-words">Aucune interaction récente.</p>
                )}
            </div>
        </div>
    );

    const blocksMap = {
        pinned: renderPinnedBlock(),
        actions: renderActionsBlock(),
        stats: renderStatsBlock(),
        chats: renderChatsBlock()
    };

    // 7. - Rendu final
    return (
        <>
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full pb-10">
                <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 min-w-0 w-full">
                    <div className="min-w-0">
                        <h1 className="text-3xl font-black text-slate-800 break-words">Supervision</h1>
                        <p className="text-slate-500 font-medium flex items-center flex-wrap gap-1">Vue d'ensemble de la plateforme <TextLogo className="text-sm" />.</p>
                    </div>
                    <div className="flex gap-2 w-full md:w-auto shrink-0">
                        <Button 
                            variant="secondary" 
                            icon={SlidersHorizontalIcon} 
                            onClick={(e) => openDialog('reorder_dashboard', null, e)} 
                            className="px-4 py-3 shadow-md bg-white border-slate-200 flex-1 justify-center"
                            title="Personnaliser l'ordre des sections"
                        >
                            <span className="hidden sm:inline">Personnaliser</span>
                        </Button>
                    </div>
                </div>

                {currentOrder.map(blockKey => {
                    const blockContent = blocksMap[blockKey];
                    if (!blockContent) return null;
                    if (blockKey === 'chats') {
                        return <div key={blockKey} className="w-full min-w-0">{blockContent}</div>;
                    }
                    return (
                        <React.Fragment key={blockKey}>
                            {blockContent}
                        </React.Fragment>
                    );
                })}
            </div>

            {/* MODALE DE RÉORGANISATION */}
            {activeDialog === 'reorder_dashboard' && Modal && (
                <Modal 
                    title="Personnaliser l'affichage" 
                    onClose={closeCurrentLayer} 
                    preventClose={isSavingOrder}
                    actions={(close) => (
                        <>
                            <Button variant="secondary" onClick={close} disabled={isSavingOrder} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button variant="primary" onClick={saveOrder} disabled={isSavingOrder} className="flex-[2] py-3 justify-center uppercase tracking-widest shadow-md font-black text-xs">Enregistrer l'ordre</Button>
                        </>
                    )}
                >
                    <div className="space-y-6">
                        <div>
                            <p className="text-sm text-slate-600 mb-4 font-medium break-words">Utilisez les flèches pour réorganiser les grandes sections de votre tableau de bord selon vos priorités.</p>
                            <div className="space-y-3">
                                {tempOrder.map((blockKey, idx) => (
                                    <div key={blockKey} className="flex items-center justify-between bg-slate-50 border border-slate-200 p-4 rounded-xl shadow-sm transition-all hover:bg-slate-100 hover:border-blue-300">
                                        <span className="font-black text-slate-700 text-sm tracking-wide break-words">{blockNames[blockKey]}</span>
                                        <div className="flex gap-1 shrink-0">
                                            <Button variant="outline" shape="square" icon={ChevronUpIcon} onClick={() => moveBlock(idx, 'up')} disabled={idx === 0 || isSavingOrder} className="p-1.5 shadow-none bg-white text-slate-500 hover:text-blue-600" title="Monter" />
                                            <Button variant="outline" shape="square" icon={ChevronDownIcon} onClick={() => moveBlock(idx, 'down')} disabled={idx === tempOrder.length - 1 || isSavingOrder} className="p-1.5 shadow-none bg-white text-slate-500 hover:text-blue-600" title="Descendre" />
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className="pt-6 border-t border-slate-200">
                            <h4 className="text-sm font-black text-slate-800 mb-3 break-words">Format de la section "À traiter en priorité"</h4>
                            <div className="flex flex-col sm:flex-row gap-3">
                                <label className={`flex-1 p-4 rounded-xl border-2 cursor-pointer transition flex flex-col items-center gap-2 ${tempActionsMode === 'mini' ? 'border-emerald-500 bg-emerald-50 shadow-sm' : 'border-slate-200 hover:bg-slate-50'}`}>
                                    <input type="radio" checked={tempActionsMode === 'mini'} onChange={() => setTempActionsMode('mini')} className="hidden" disabled={isSavingOrder} />
                                    <span className={`text-xs font-black uppercase tracking-widest ${tempActionsMode === 'mini' ? 'text-emerald-700' : 'text-slate-500'}`}>Mini cartes</span>
                                    <span className="text-[10px] text-center font-medium text-slate-500 leading-tight">Format compact et résumé</span>
                                </label>
                                <label className={`flex-1 p-4 rounded-xl border-2 cursor-pointer transition flex flex-col items-center gap-2 ${tempActionsMode === 'full' ? 'border-emerald-500 bg-emerald-50 shadow-sm' : 'border-slate-200 hover:bg-slate-50'}`}>
                                    <input type="radio" checked={tempActionsMode === 'full'} onChange={() => setTempActionsMode('full')} className="hidden" disabled={isSavingOrder} />
                                    <span className={`text-xs font-black uppercase tracking-widest ${tempActionsMode === 'full' ? 'text-emerald-700' : 'text-slate-500'}`}>Cartes complètes</span>
                                    <span className="text-[10px] text-center font-medium text-slate-500 leading-tight">Tous les détails et actions</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </Modal>
            )}
        </>
    );
};

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