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

// 1. - COMPOSANT CARTE ISOLÉ ET RÉUTILISABLE ADMINISTRATEUR (CLIENTS)
window.pano_AdminClientCard = ({ 
    client: c, data, isPinned, toggleDashboardPin, unreadSupport, refreshData,
    // PROPS DE ROUTAGE INJECTÉES PAR LE PARENT
    openDialog, closeCurrentLayer, openChat, activeDialog, dialogId
}) => {
    const { useState } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // CORRECTION ZÉRO-DETTE : Fallbacks de navigation robustes
    const handleOpenDialog = (n, id, s) => { if (openDialog) openDialog(n, id, s); };
    const handleCloseLayer = () => { if (closeCurrentLayer) closeCurrentLayer(); };
    const handleOpenChat = (id, s) => {
        if (openChat) openChat(id, s);
        else {
            const prev = window.history.state || { panoStack: [], level: 0, currentTab: 'dashboard' };
            const newStack = (prev.panoStack || []).filter(l => l.type !== 'chat');
            newStack.push({ type: 'chat', name: 'chat', targetId: id });
            window.history.pushState({ ...prev, panoStack: newStack, level: newStack.length }, '', window.location.href);
            window.dispatchEvent(new Event('pano_stack_sync'));
        }
    };

    // États encapsulés
    const [isSaving, setIsSaving] = useState(false);
    const [adminPassword, setAdminPassword] = useState("");
    const [aesKeyConfirm, setAesKeyConfirm] = useState("");
    const [confirmConfig, setConfirmConfig] = useState(null);

    const [creditAmount, setCreditAmount] = useState("");
    const [creditReason, setCreditReason] = useState("Geste commercial / Annulation de dette");

    const [discount, setDiscount] = useState(c.discount || 0);
    const [discountDuration, setDiscountDuration] = useState(c.discount_duration || '1');

    const {
        UsersIcon, KeyRoundIcon, ShieldAlertIcon, ShieldIcon,
        ZapIcon, MessageSquareIcon, Trash2Icon, EditIcon,
        MailIcon, CheckCircleIcon, LoaderIcon, LockIcon, PinIcon
    } = window.pano_getIcons();
    
    const { Modal, ConfirmModal, Button, IconBadge, NotificationBadge, DataCard, FormInput } = window.pano_getComponents();

    // Calculs de statistiques par client isolés
    const clientPanels = (data?.panneaux || []).filter(p => p.clientName === c.id || p.client_uid === c.id);
    const activePanels = clientPanels.filter(p => p.status === 'Actif').length;
    const draftPanels = clientPanels.filter(p => p.status === 'Brouillon').length;
    
    let revenue12m = 0;
    const twelveMonthsAgoMs = new Date().setMonth(new Date().getMonth() - 12);
    (data?.invoices || []).forEach(inv => {
        if (inv.clientName === c.id) {
            const invTime = new Date(String(inv.created_at || '').replace(' ', 'T')).getTime();
            if (invTime >= twelveMonthsAgoMs) {
                revenue12m += parseFloat(inv.amount || 0);
            }
        }
    });

    const isImpersonable = c.admin_access_until && new Date(String(c.admin_access_until || '').replace(' ', 'T')) > new Date();
    const isSuspended = c.paymentStatus === 'suspended';
    const hasDebt = c.wallet_balance < 0;

    let cardVariant = 'default';
    if (isSuspended || hasDebt) cardVariant = 'danger';
    else if (unreadSupport > 0) cardVariant = 'warning';

    // Actions métier localisées (SÉCURISÉES)
    const sendAccessRequest = async (mode) => {
        const d = await safeFetch('clients/request_access', { 
            body: { uid: c.id, mode },
            setLoading: setIsSaving,
            successMessage: "Demande d'accès envoyée avec succès."
        });
        
        if (!isMounted.current) return;

        if (d) {
            handleCloseLayer();
            if (refreshData) refreshData();
        }
    };

    const revokeAccess = async () => {
        setConfirmConfig({
            title: "Révocation d'accès",
            message: "Êtes-vous sûr de vouloir révoquer l'autorisation d'accès du support technique pour ce client ?",
            confirmText: "Oui, révoquer",
            isDestructive: true,
            onConfirm: async () => {
                handleCloseLayer();
                const d = await safeFetch('clients/revoke_access', { 
                    body: { uid: c.id },
                    setLoading: setIsSaving,
                    successMessage: "Accès révoqué."
                });

                if (!isMounted.current) return;

                if (d && refreshData) refreshData();
            }
        });
        handleOpenDialog('confirm_client_action', c.id, false);
    };

    const impersonateClient = async () => {
        const d = await safeFetch('auth/impersonate', { 
            body: { uid: c.id },
            setLoading: setIsSaving
        });

        if (!isMounted.current) return;

        if (d) window.location.href = '?'; 
    };

    const handleDeleteClientSubmit = async (e) => {
        e.preventDefault();
        if (!adminPassword || !aesKeyConfirm) return;
        
        const d = await safeFetch('clients/admin_delete', { 
            body: { uid: c.id, pwd: adminPassword, aes_key_confirm: aesKeyConfirm },
            setLoading: setIsSaving,
            successMessage: "Client supprimé avec succès."
        });
        
        if (!isMounted.current) return;

        if (d) {
            handleCloseLayer();
            if (refreshData) refreshData();
            setTimeout(() => {
                if (isMounted.current) {
                    setAdminPassword('');
                    setAesKeyConfirm('');
                }
            }, 300);
        }
    };

    const handleAddCredit = async (e) => {
        e.preventDefault();
        const amt = parseFloat(creditAmount);
        if (amt <= 0) {
            if (window.pano_showToast) window.pano_showToast("Montant invalide", "error");
            return;
        }
        
        const d = await safeFetch('invoices/credit', {
            body: { client_uid: c.id, amount: amt, reason: creditReason },
            setLoading: setIsSaving,
            successMessage: "Crédit ajouté avec succès !"
        });

        if (!isMounted.current) return;

        if (d) {
            handleCloseLayer();
            if (refreshData) refreshData();
        }
    };

    const handleEditClientSubmit = async (e) => {
        e.preventDefault();
        if (!adminPassword) return;

        const d = await safeFetch('clients/update', {
            body: {
                uid: c.id,
                discount: parseInt(discount) || 0,
                discountDuration: discountDuration,
                pwd: adminPassword
            },
            setLoading: setIsSaving,
            successMessage: "Remise mise à jour avec succès."
        });

        if (!isMounted.current) return;

        if (d) {
            handleCloseLayer();
            if (refreshData) refreshData();
            setTimeout(() => {
                if (isMounted.current) setAdminPassword('');
            }, 300);
        }
    };

    return (
        <>
            <DataCard variant={cardVariant} className="group hover:border-blue-300 min-w-0 relative p-4">
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); toggleDashboardPin && toggleDashboardPin('clients', c.id, e); }} 
                    className={`absolute top-2 right-2 z-20 p-1 cursor-pointer transition-all duration-200 ${isPinned ? 'text-emerald-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 min-w-0">
                    <div className="flex gap-3 min-w-0 flex-1">
                        <IconBadge icon={UsersIcon} variant={isSuspended ? "danger" : "info"} size="lg" className="shrink-0" />
                        <div className="min-w-0 flex-1">
                            <p className="font-black text-base text-slate-800 break-words leading-tight" title={c.name}>{c.name}</p>
                            {c.full_name && <p className="text-xs font-bold text-slate-600 break-words leading-tight mt-0.5" title={c.full_name}>{c.full_name}</p>}
                            <p className="text-xs text-slate-500 break-all leading-tight mt-0.5" title={c.email}>{c.email}</p>
                            <div className="flex items-center gap-2 mt-2 min-w-0 flex-wrap">
                                <p className="text-[10px] text-slate-400 font-mono">ID : {c.id.substring(0,8)}</p>
                                {c.wallet_balance !== 0 && (
                                    <span className={`px-1.5 py-0.5 rounded text-[9px] font-black tracking-widest uppercase break-words ${c.wallet_balance > 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'}`}>
                                        {c.wallet_balance > 0 ? `Solde: +${c.wallet_balance.toFixed(2)}€` : `Dette: ${c.wallet_balance.toFixed(2)}€`}
                                    </span>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                <div className="grid grid-cols-3 gap-2 mt-2 bg-slate-50/50 p-2 rounded-xl border border-slate-100/50 text-center min-w-0">
                    <div className="min-w-0">
                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest break-words leading-tight">Revenu (12m)</p>
                        <p className="font-black text-slate-700 text-xs break-words mt-1">{revenue12m.toFixed(2)} €</p>
                    </div>
                    <div className="border-l border-slate-200 min-w-0">
                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest break-words leading-tight">Actifs</p>
                        <p className="font-black text-slate-700 text-xs break-words mt-1">{activePanels}</p>
                    </div>
                    <div className="border-l border-slate-200 min-w-0">
                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest break-words leading-tight">Brouillons</p>
                        <p className="font-black text-slate-700 text-xs break-words mt-1">{draftPanels}</p>
                    </div>
                </div>
                
                {(isSuspended || c.discount > 0) && (
                    <div className="flex items-center gap-2 flex-wrap min-w-0 mt-1">
                        {isSuspended && (
                            <span className="px-2 py-1 inline-flex items-center justify-center text-[10px] font-black uppercase tracking-wider rounded-lg break-words bg-red-100 text-red-700">
                                Impayé (Suspendu)
                            </span>
                        )}
                        {c.discount > 0 && <span className="px-2 py-1 bg-purple-100 text-purple-700 text-[10px] font-black tracking-wider uppercase rounded-lg break-words">Remise {c.discount}%</span>}
                    </div>
                )}
                
                <div className="flex items-center gap-2 flex-wrap pt-3 border-t border-slate-100 mt-auto min-w-0">
                    {isImpersonable ? (
                        <div className="flex-1 flex items-center gap-2 min-w-0">
                            <Button variant="primary" icon={KeyRoundIcon} onClick={() => impersonateClient()} title="Prendre le contrôle du compte client" className="flex-1 justify-center">Contrôler</Button>
                            <Button variant="warning" shape="round" icon={ShieldAlertIcon} onClick={revokeAccess} title="Révoquer l'accès" className="p-2 shadow-none shrink-0" />
                        </div>
                    ) : (
                        <Button variant="secondary" icon={ShieldIcon} onClick={() => handleOpenDialog('access_request', c.id, false)} title="Demander l'accès au compte" className="flex-1 justify-center bg-white border-slate-200">Accès</Button>
                    )}
                    
                    <Button variant="secondary" shape="square" icon={EditIcon} onClick={() => { setAdminPassword(''); handleOpenDialog('edit_client', c.id, false); }} title="Modifier la remise commerciale" className="p-2 shadow-none bg-white border-slate-200 shrink-0" />
                    <Button variant="success" shape="square" icon={ZapIcon} onClick={() => { setCreditAmount(''); setCreditReason("Geste commercial / Annulation de dette"); handleOpenDialog('credit', c.id, false); }} title="Ajuster le solde (Crédit ou Dette)" className="p-2 shadow-none shrink-0" />
                    
                    <Button variant="info" shape="square" icon={MessageSquareIcon} onClick={(e) => {
                        e.preventDefault(); 
                        e.stopPropagation(); 
                        handleOpenChat('SUPPORT_' + c.id, false);
                    }} title="Ouvrir la messagerie avec ce client sur place" className="p-2 shadow-none relative shrink-0">
                        <NotificationBadge count={unreadSupport} animate={true} className="absolute -top-2 -right-2 scale-75" />
                    </Button>
                    
                    <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => { setAdminPassword(''); setAesKeyConfirm(''); handleOpenDialog('delete_client', c.id, false); }} title="Supprimer définitivement ce compte" className="p-2 shadow-none shrink-0" />
                </div>
            </DataCard>

            {/* Modales Encapsulées Zéro-Dette */}
            {activeDialog === 'access_request' && dialogId === c.id && Modal && (
                <Modal 
                    title="Demande d'accès" 
                    onClose={handleCloseLayer} 
                    actions={(close) => (
                        <div className="flex flex-col gap-2 w-full min-w-0">
                            <Button variant="outline" icon={MessageSquareIcon} onClick={() => { sendAccessRequest('chat'); }} disabled={isSaving} className="w-full py-3 justify-center text-xs shadow-sm">
                                Dans la messagerie (recommandé)
                            </Button>
                            <Button variant="outline" icon={MailIcon} onClick={() => { sendAccessRequest('email'); }} disabled={isSaving} className="w-full py-3 justify-center text-xs shadow-sm">
                                Par e-mail
                            </Button>
                            <Button variant="primary" icon={CheckCircleIcon} onClick={() => { sendAccessRequest('both'); }} disabled={isSaving} className="w-full py-3 shadow-md justify-center text-xs">
                                Les deux
                            </Button>
                            <Button variant="secondary" onClick={close} disabled={isSaving} className="w-full py-3 justify-center text-xs mt-2">
                                Annuler
                            </Button>
                        </div>
                    )}
                >
                    <div className="space-y-4 pb-2 min-w-0">
                        <div className="bg-blue-50 p-4 rounded-xl border border-blue-100 text-blue-800 text-sm leading-relaxed break-words">
                            Comment souhaitez-vous envoyer la demande d'autorisation d'accès temporaire (24h) à ce client ?
                        </div>
                    </div>
                </Modal>
            )}

            {activeDialog === 'credit' && dialogId === c.id && Modal && (
                <Modal 
                    title={`Ajuster le solde : ${c.name || c.email}`} 
                    onClose={handleCloseLayer} 
                    preventClose={isSaving} 
                    actions={(close) => (
                        <>
                            <Button variant="secondary" onClick={close} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                            <Button type="submit" form={`credit-form-${c.id}`} variant="primary" disabled={isSaving} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                                Valider
                            </Button>
                        </>
                    )}
                >
                    <form id={`credit-form-${c.id}`} onSubmit={handleAddCredit} className="space-y-4 min-w-0">
                        <div className="text-xs text-slate-500 mb-2 break-words"><span className="text-red-500 font-black">*</span> Champs obligatoires</div>
                        <div className="bg-emerald-50 text-emerald-800 p-4 rounded-xl border border-emerald-100 text-sm min-w-0">
                            <strong className="break-words">Ajout d'un crédit ou Annulation de dette</strong><br/>
                            <span className="break-words leading-relaxed">Ce montant sera ajouté au solde du client. S'il a une dette (solde négatif ou statut impayé), cela permettra de l'annuler en tout ou partie.</span>
                        </div>
                        <div className="min-w-0">
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1 break-words">Montant à créditer (€) <span className="text-red-500">*</span></label>
                            <input type="number" step="0.01" min="0.01" value={creditAmount} onChange={e => setCreditAmount(e.target.value)} required className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500 font-bold min-w-0" placeholder="Ex: 50,00" />
                        </div>
                        <div className="min-w-0">
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1 break-words">Motif (visible par le client) <span className="text-red-500">*</span></label>
                            <input type="text" value={creditReason} onChange={e => setCreditReason(e.target.value)} required className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500 font-bold min-w-0" />
                        </div>
                    </form>
                </Modal>
            )}

            {activeDialog === 'edit_client' && dialogId === c.id && Modal && (
                <Modal 
                    title={`Modifier la remise : ${c.name || c.email}`} 
                    onClose={handleCloseLayer} 
                    preventClose={isSaving} 
                    actions={(close) => (
                        <>
                            <Button variant="secondary" onClick={close} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                            <Button type="submit" form={`edit-client-form-${c.id}`} variant="primary" disabled={isSaving || !adminPassword} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                                Enregistrer
                            </Button>
                        </>
                    )}
                >
                    <form id={`edit-client-form-${c.id}`} onSubmit={handleEditClientSubmit} className="space-y-4 min-w-0">
                        <div className="text-xs text-slate-500 mb-2 break-words"><span className="text-red-500 font-black">*</span> Champs obligatoires</div>

                        <div className="pt-2 border-t border-slate-100 min-w-0">
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1 break-words">Remise commerciale (%)</label>
                            <input type="number" min="0" max="100" value={discount} onChange={e => setDiscount(e.target.value)} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500 font-bold min-w-0" />
                        </div>

                        <div className="min-w-0">
                            <label className="block text-xs font-bold text-slate-500 uppercase mb-1 break-words">Durée de validité de la remise <span className="text-red-500">*</span></label>
                            <select value={discountDuration} onChange={e => setDiscountDuration(e.target.value)} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm outline-none focus:border-emerald-500 font-bold text-slate-700 bg-white min-w-0">
                                <option value="1">1 mois</option>
                                <option value="2">2 mois</option>
                                <option value="3">3 mois</option>
                                <option value="6">6 mois</option>
                                <option value="9">9 mois</option>
                                <option value="12">12 mois</option>
                            </select>
                        </div>

                        <div className="p-4 bg-slate-50 border border-slate-200 rounded-xl mt-4 min-w-0">
                            <FormInput label="Sécurité requise" icon={<LockIcon size={14}/>} type="password" value={adminPassword} onChange={e => setAdminPassword(e.target.value)} placeholder="Mot de passe admin" required className="min-w-0 w-full" />
                        </div>
                    </form>
                </Modal>
            )}

            {activeDialog === 'delete_client' && dialogId === c.id && Modal && (
                <Modal 
                    title="Suppression irréversible" 
                    type="error" 
                    onClose={handleCloseLayer} 
                    preventClose={isSaving} 
                    actions={(close) => (
                        <>
                            <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                            <Button variant="dangerSolid" type="submit" form={`delete-client-form-${c.id}`} disabled={isSaving || !adminPassword || !aesKeyConfirm} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">Détruire le compte</Button>
                        </>
                    )}
                >
                    <form id={`delete-client-form-${c.id}`} onSubmit={handleDeleteClientSubmit} className="space-y-4 min-w-0">
                        <p className="text-sm text-slate-600 font-medium break-words leading-relaxed">
                            Vous êtes sur le point de détruire définitivement le compte de <strong className="text-red-600 break-all">{c.name}</strong> et toutes ses données associées. Cette action est irréversible.
                        </p>
                        <div className="p-4 bg-red-50 border border-red-200 rounded-xl space-y-3 min-w-0">
                            <h4 className="text-xs font-bold text-red-700 uppercase flex items-center gap-2 mb-2 break-words"><LockIcon size={14} className="shrink-0"/> Sécurité requise</h4>
                            <FormInput type="password" value={adminPassword} onChange={e => setAdminPassword(e.target.value)} placeholder="Mot de passe admin" required error className="min-w-0 w-full" />
                            <FormInput type="password" value={aesKeyConfirm} onChange={e => setAesKeyConfirm(e.target.value)} placeholder="Clé AES_KEY_CONFIRM" required error className="min-w-0 w-full" />
                        </div>
                    </form>
                </Modal>
            )}

            {activeDialog === 'confirm_client_action' && dialogId === c.id && confirmConfig && ConfirmModal && (
                <ConfirmModal {...confirmConfig} onCancel={() => { setConfirmConfig(null); handleCloseLayer(); }} />
            )}
        </>
    );
};

// 2. - ONGLET PRINCIPAL DE GESTION CLIENTS ADMIN
window.pano_AdminClientsTab = ({ data, refreshData, adminOpts, toggleDashboardPin }) => {
    const { useState, useMemo, useEffect } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // CORRECTION ZÉRO-DETTE PERFORMANCE : Abonnement unique au routeur
    const urlModal = window.pano_useUrlModal ? window.pano_useUrlModal() : {};
    const { openDialog, closeCurrentLayer, openChat, activeDialog, dialogId } = urlModal;

    const { SearchBar, EmptySearch, PaginationFooter, CardGrid, AdminClientCard } = window.pano_getComponents();
    const { UsersIcon, AlertTriangleIcon, PinIcon, LoaderIcon, DownloadIcon } = window.pano_getIcons();

    const [localClients, setLocalClients] = useState(data.clients || []);
    const [hasMoreClients, setHasMoreClients] = useState((data.clients || []).length >= 50);
    const [isLoadingMore, setIsLoadingMore] = useState(false);

    useEffect(() => {
        setLocalClients(data.clients || []);
        setHasMoreClients((data.clients || []).length >= 50);
    }, [data.clients]);

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData: filteredClients 
    } = window.pano_useSearchAndPagination(localClients, (c, q) => {
        const n = window.pano_normalizeString;
        const displayStatus = c.paymentStatus === 'suspended' ? 'impayé suspendu' : 'actif';
        return n(c.name).includes(q) ||
               n(c.full_name).includes(q) ||
               n(c.email).includes(q) ||
               n(c.id).includes(q) ||
               n(displayStatus).includes(q); 
    });

    const unreadSupportMap = useMemo(() => {
        const map = {};
        const threads = window.pano_buildAdminChatThreads ? window.pano_buildAdminChatThreads(data.interactions || [], data.panneaux || [], localClients) : [];
        threads.forEach(t => {
            if (t.unread > 0 && t.type === 'support') {
                const cuid = t.id.replace('SUPPORT_', '');
                map[cuid] = (map[cuid] || 0) + t.unread;
            }
        });
        return map;
    }, [data.interactions, data.panneaux, localClients]);

    const handleLoadMoreClients = async () => {
        const d = await safeFetch(`sync/more&type=clients&offset=${localClients.length}&limit=50`, { 
            method: 'GET', 
            silent: true,
            setLoading: setIsLoadingMore
        });
        
        if (!isMounted.current) return; // SÉCURITÉ

        if (d && d.status === 'success') {
            const newClients = d.data.clients || [];
            setLocalClients(prev => {
                const combined = [...prev, ...newClients];
                return Array.from(new Map(combined.map(item => [item.id, item])).values());
            });
            setHasMoreClients(newClients.length === 50);
        }
    };

    const pinnedIds = adminOpts?.clients || [];
    const attentionClients = [];
    const pinnedClients = [];
    const otherClients = [];

    filteredClients.forEach(c => {
        const isSuspended = c.paymentStatus === 'suspended';
        const hasDebt = c.wallet_balance < 0;
        const unreadSupport = unreadSupportMap[c.id] || 0;
        const isPinned = pinnedIds.includes(c.id);
        
        // Distribution des props du routeur
        const cardProps = {
            client: c, data, isPinned, toggleDashboardPin, unreadSupport, refreshData,
            openDialog, closeCurrentLayer, openChat, activeDialog, dialogId
        };

        if (isSuspended || hasDebt || unreadSupport > 0) attentionClients.push(cardProps);
        else if (isPinned) pinnedClients.push(cardProps);
        else otherClients.push(cardProps);
    });

    const displayedOtherClients = otherClients.slice(0, visibleCount);

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 min-w-0">
                <div className="min-w-0">
                    <h1 className="text-3xl font-black text-slate-800 break-words">Base clients</h1>
                    <p className="text-slate-500 font-medium break-words">Gestion des comptes et prise de contrôle.</p>
                </div>
                
                {localClients.length > 0 && SearchBar && (
                    <div className="w-full sm:w-auto flex-1 flex justify-end gap-2 shrink-0">
                        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} placeholder="Rechercher par nom, e-mail, statut..." />
                    </div>
                )}
            </div>
            
            {localClients.length === 0 ? (
                <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed min-w-0">
                    <UsersIcon size={48} className="mx-auto text-slate-300 mb-4" />
                    <p className="text-slate-500 italic break-words">Aucun client enregistré.</p>
                </div>
            ) : filteredClients.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* 8.1 - Priorités */}
                    {attentionClients.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0">
                            <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" /> Action requise
                            </h2>
                            <CardGrid minWidth="320px">
                                {attentionClients.map(props => <AdminClientCard key={`att_${props.client.id}`} {...props} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* 8.2 - Favoris */}
                    {pinnedClients.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0">
                            <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-emerald-600 shrink-0" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="320px">
                                {pinnedClients.map(props => <AdminClientCard key={`pin_${props.client.id}`} {...props} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* 8.3 - Autres */}
                    {otherClients.length > 0 && (
                        <div className="space-y-4 min-w-0">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2 break-words">
                                <UsersIcon size={20} className="text-blue-600 shrink-0" /> {attentionClients.length > 0 ? 'Autres clients' : 'Tous les clients'}
                                <span className="ml-auto text-sm font-bold text-slate-400 bg-slate-100 px-3 py-1 rounded-lg shrink-0">{otherClients.length}</span>
                            </h2>
                            <CardGrid minWidth="320px">
                                {displayedOtherClients.map(props => <AdminClientCard key={`oth_${props.client.id}`} {...props} />)}
                            </CardGrid>
                            
                            {PaginationFooter && (
                                <PaginationFooter visibleCount={visibleCount} setVisibleCount={setVisibleCount} totalCount={otherClients.length} itemName="clients" />
                            )}

                            {hasMoreClients && visibleCount >= otherClients.length && (
                                <div className="flex justify-center pb-8 mt-6 min-w-0">
                                    <Button variant="outline" icon={isLoadingMore ? LoaderIcon : DownloadIcon} onClick={handleLoadMoreClients} disabled={isLoadingMore} className="bg-white shadow-sm py-3 px-6 text-center">
                                        {isLoadingMore ? "Chargement..." : "Charger les clients plus anciens depuis le serveur"}
                                    </Button>
                                </div>
                            )}
                        </div>
                    )}
                </>
            )}
        </div>
    );
};

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