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

window.pano_ClientDashboardTab = ({ 
    data, myClientData, setActiveTab, setManagingPanneau, setValidationErrors, setPreviewPanneau, openLocalModal, openLocalDialog, closeCurrentLayer, activeModal, activeDialog, targetId, dialogId, clientOpts, toggleDashboardPin, handleCreateNewPanel, refreshData, setPanelTeamModal, setArchiveConfig 
}) => {
    const { useState, useEffect } = React;
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

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

    // CORRECTION : Nettoyage des icônes inutilisées (Dette technique)
    const { 
        UsersIcon, BuildingIcon, EyeIcon, MessageSquareIcon, MessageCircleIcon,
        ArchiveIcon, AlertTriangleIcon, PackageIcon,
        PinIcon, ChevronUpIcon, ChevronDownIcon, SlidersHorizontalIcon, PlusIcon,
        CheckCircleIcon, XIcon, EditIcon, QrCodeIcon, MailIcon
    } = window.pano_getIcons();

    // CORRECTION ZÉRO-DETTE : Retrait de UniversalViewer du composant parent
    const { 
        StatCard, Button, IconBadge, NotificationBadge, Modal,
        CardGrid, DataCard, TextLogo, StatusBadge,
        ClientPanelCard, ClientInviteCard, ClientDeliveryCard
    } = window.pano_getComponents();

    // 3. - Gestion de l'ordre d'affichage (Reorder)
    const defaultOrder = ['actions', 'pinned', 'stats', 'chats'];
    const currentOrder = clientOpts?.dashboard_order || defaultOrder;
    const currentActionsMode = clientOpts?.actions_mode || 'full';
    
    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",
        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);
        const newOpts = { ...clientOpts, dashboard_order: tempOrder, actions_mode: tempActionsMode };
        const d = await safeFetch('clients/profile/update', { 
            body: { ...myClientData, uiMode: JSON.stringify(newOpts) } 
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        setIsSavingOrder(false);
        if (d && refreshData) refreshData();
        if (closeCurrentLayer) closeCurrentLayer(e);
    };

    // 4. - Traitement des données (Entonnoir)
    const allPanels = data.panneaux || [];
    const interactions = data.interactions || [];
    
    const { pendingInvites, visiblePanels } = window.pano_getPanelAccessRights ? window.pano_getPanelAccessRights(allPanels, myClientData.id, myClientData.email_hash) : { pendingInvites:[], visiblePanels:[] };
    
    const activePendingInvites = pendingInvites; 

    const activePanelsCount = visiblePanels.filter(p => p.status === 'Actif').length;
    const draftPanelsCount = visiblePanels.filter(p => p.status === 'Brouillon').length;
    
    const totalViews = data.stats?.totalViews || 0;

    const threads = window.pano_buildClientChatThreads ? window.pano_buildClientChatThreads(data.interactions || [], myClientData, visiblePanels, pendingInvites) : [];
    const dashboardThreads = threads.slice(0, 5);

    const unreadMap = {};
    threads.forEach(t => {
        if (t.unread > 0 && t.panneauId) {
            if (!unreadMap[t.panneauId]) unreadMap[t.panneauId] = { total: 0, riverain: 0, group: 0 };
            unreadMap[t.panneauId].total += t.unread;
            if (t.type === 'riverain') unreadMap[t.panneauId].riverain += t.unread;
            if (t.type === 'group') unreadMap[t.panneauId].group += t.unread;
        }
    });

    const pinnedPanelsIds = clientOpts?.pinned_panels || [];
    const pinnedPanels = visiblePanels.filter(p => pinnedPanelsIds.includes(p.id));
    
    const pinnedDeliveriesIds = clientOpts?.pinned_deliveries || [];
    const pinnedDeliveries = visiblePanels.filter(p => pinnedDeliveriesIds.includes(p.id) && p.physicalPanels > 0 && p.status !== 'Brouillon');

    const limitShippingForce = parseInt(data.settings?.limit_shipping_force || 90, 10);

    // CORRECTION SÉCURITÉ/UX : Intégration D.O.E non lus ET retrait des alertes logistiques (pour éviter le doublon avec ClientDeliveryCard)
    const attentionPanels = visiblePanels.filter(p => {
        const unreadCount = unreadMap[p.id]?.total || 0;
        const isUnreadDOE = p.status === 'DOE' && !p.doe_downloaded;
        return p.status === 'Suspendu' || p.status === 'Attente validation' || p.inactivity_alert_level > 0 || unreadCount > 0 || isUnreadDOE;
    });

    const pendingLogistics = visiblePanels.filter(p => {
        if (p.physicalPanels <= 0) return false;
        const currentStatus = p.shipping_status || 'En attente de validation';
        
        if (currentStatus === 'Attente validation client') 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 isFeatureEnabled = (adminOpt, clientVal) => {
        if (adminOpt === 'disabled') return false;
        if (adminOpt === 'active') return true;
        if (adminOpt === 'optional_on') return clientVal !== false; 
        if (adminOpt === 'optional_off' || adminOpt === 'optional') return clientVal === true;
        return true; 
    };

    const hasNewsletterFeature = isFeatureEnabled(data.settings?.opt_newsletter, clientOpts?.newsletter);
    const hasCollabFeature = isFeatureEnabled(data.settings?.opt_collab, clientOpts?.collab);
    const hasMessagingFeature = isFeatureEnabled(data.settings?.opt_messaging, clientOpts?.messaging);
    const isSuspended = myClientData.paymentStatus === 'suspended';

    // 5. - Blocs de rendu dynamiques
    const renderPinnedBlock = () => {
        if (pinnedPanels.length === 0 && pinnedDeliveries.length === 0) return null;
        return (
            <div className="space-y-4">
                <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 /> Vos favoris
                </h2>
                <CardGrid minWidth="320px">
                    {pinnedPanels.map(p => (
                        <ClientPanelCard 
                            key={`pin_pan_${p.id}`} panel={p} data={data} myClientData={myClientData} localPinned={pinnedPanelsIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                            unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} openLocalModal={openLocalModal} openLocalDialog={openLocalDialog} 
                            setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                            isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                            hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData} closeCurrentLayer={closeCurrentLayer} 
                            setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                            activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                        />
                    ))}

                    {/* CORRECTION ZÉRO-DETTE : Distribution des props du routeur */}
                    {ClientDeliveryCard && pinnedDeliveries.map(c => (
                        <ClientDeliveryCard 
                            key={`pin_del_${c.id}`} delivery={c} isPinned={true} 
                            toggleDashboardPin={(id, e) => toggleDashboardPin('pinned_deliveries', id, e)} 
                            refreshData={refreshData} 
                            limitShippingForce={limitShippingForce}
                            openModal={openLocalModal}
                            openDialog={openLocalDialog}
                            closeCurrentLayer={closeCurrentLayer}
                            activeModal={activeModal}
                            activeDialog={activeDialog}
                            targetId={targetId}
                            dialogId={dialogId}
                        />
                    ))}
                </CardGrid>
            </div>
        );
    };

    const renderActionsBlock = () => {
        if (attentionPanels.length === 0 && !isSuspended && activePendingInvites.length === 0 && pendingLogistics.length === 0) return null;
        
        const attentionPanelsExtra = attentionPanels.length > 4 ? attentionPanels.length - 4 : 0;
        const pendingLogisticsExtra = pendingLogistics.length > 4 ? pendingLogistics.length - 4 : 0;

        return (
            <div className="space-y-4">
                <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>
                
                {isSuspended && (
                    <div className="bg-red-50 border border-red-200 p-4 rounded-xl flex items-center justify-between mb-4 shadow-sm min-w-0">
                        <div className="flex items-center gap-3 min-w-0">
                            <AlertTriangleIcon size={24} className="text-red-600 shrink-0" />
                            <div className="min-w-0 pr-2">
                                <h3 className="font-black text-red-900 break-words leading-tight">Compte suspendu (Impayé)</h3>
                                <p className="text-xs text-red-700 mt-0.5 break-words leading-tight">Veuillez régulariser votre situation pour réactiver vos panneaux.</p>
                            </div>
                        </div>
                        <Button variant="dangerSolid" onClick={() => setActiveTab('billing')} className="shadow-md text-xs py-2 px-4 shrink-0">Régulariser</Button>
                    </div>
                )}
                
                {(activePendingInvites.length > 0 || attentionPanels.length > 0 || pendingLogistics.length > 0) && (
                    <CardGrid minWidth="280px">
                        {currentActionsMode === 'full' ? (
                            <>
                                {activePendingInvites.map(p => (
                                    <ClientInviteCard 
                                        key={`inv_full_${p.id}`} 
                                        invite={p} 
                                        setPreviewPanneau={setPreviewPanneau} 
                                        refreshData={refreshData} 
                                        hasCollabFeature={hasCollabFeature}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}

                                {attentionPanels.slice(0, 4).map(p => (
                                    <ClientPanelCard 
                                        key={`pan_full_${p.id}`} panel={p} data={data} myClientData={myClientData} localPinned={pinnedPanelsIds} togglePin={(id, e) => toggleDashboardPin('pinned_panels', id, e)} 
                                        unreadMap={unreadMap} setPreviewPanneau={setPreviewPanneau} openLocalModal={openLocalModal} openLocalDialog={openLocalDialog} 
                                        setManagingPanneau={setManagingPanneau} setValidationErrors={setValidationErrors} 
                                        isSuspended={isSuspended} hasNewsletterFeature={hasNewsletterFeature} 
                                        hasCollabFeature={hasCollabFeature} hasMessagingFeature={hasMessagingFeature} refreshData={refreshData} closeCurrentLayer={closeCurrentLayer} 
                                        setPanelTeamModal={setPanelTeamModal} setArchiveConfig={setArchiveConfig}
                                        activeModal={activeModal} activeDialog={activeDialog} targetId={targetId} dialogId={dialogId}
                                    />
                                ))}
                                {attentionPanelsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => setActiveTab('panels')} 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">
                                            {window.pano_formatPlural(attentionPanelsExtra, `+ ${attentionPanelsExtra} autre panneau`, `+ ${attentionPanelsExtra} autres panneaux`)}
                                        </p>
                                    </DataCard>
                                )}

                                {ClientDeliveryCard && pendingLogistics.slice(0, 4).map(p => (
                                    <ClientDeliveryCard 
                                        key={`log_full_${p.id}`} delivery={p} isPinned={pinnedDeliveriesIds.includes(p.id)} 
                                        toggleDashboardPin={(id, e) => toggleDashboardPin('pinned_deliveries', id, e)} 
                                        refreshData={refreshData} 
                                        limitShippingForce={limitShippingForce} 
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}
                                {pendingLogisticsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => setActiveTab('livraisons')} 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">
                                            {window.pano_formatPlural(pendingLogisticsExtra, `+ ${pendingLogisticsExtra} autre commande`, `+ ${pendingLogisticsExtra} autres commandes`)}
                                        </p>
                                    </DataCard>
                                )}
                            </>
                        ) : (
                            <>
                                {activePendingInvites.map(p => (
                                    <ClientInviteCard 
                                        key={`inv_mini_${p.id}`} 
                                        invite={p} 
                                        isMini={true}
                                        onClick={() => setActiveTab('panels')}
                                        refreshData={refreshData} 
                                        hasCollabFeature={hasCollabFeature}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}

                                {attentionPanels.slice(0, 4).map(p => {
                                    let badgeVariant = 'warning';
                                    if (p.status === 'Suspendu' || p.status === 'Attente validation') badgeVariant = 'danger';
                                    
                                    const isUnreadDOE = p.status === 'DOE' && !p.doe_downloaded;
                                    if (isUnreadDOE) badgeVariant = 'warning';

                                    return (
                                        <DataCard 
                                            key={`pan_mini_${p.id}`} 
                                            variant={badgeVariant} 
                                            onClick={() => setActiveTab('panels')} 
                                            className="cursor-pointer group hover:scale-[1.02] transition-transform min-w-0"
                                        >
                                            <div className="flex items-center gap-3">
                                                <IconBadge icon={isUnreadDOE ? ArchiveIcon : BuildingIcon} variant={badgeVariant} size="md" className="shrink-0" />
                                                <div className="min-w-0 flex-1 pr-2">
                                                    <p className={`font-bold text-sm break-words leading-tight ${badgeVariant === 'danger' ? 'text-red-900' : 'text-amber-900'}`}>{p.name}</p>
                                                    <div className="flex flex-wrap items-center gap-2 mt-1">
                                                        <span className={`text-[10px] font-bold uppercase tracking-widest ${badgeVariant === 'danger' ? 'text-red-700' : 'text-amber-700'}`}>
                                                            {isUnreadDOE ? 'Télécharger D.O.E' : 'Action requise'}
                                                        </span>
                                                        {!isUnreadDOE && <StatusBadge status={p.status} className="scale-90 origin-left" />}
                                                    </div>
                                                </div>
                                            </div>
                                        </DataCard>
                                    );
                                })}
                                {attentionPanelsExtra > 0 && (
                                    <DataCard variant="default" onClick={() => setActiveTab('panels')} 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">
                                            {window.pano_formatPlural(attentionPanelsExtra, `+ ${attentionPanelsExtra} autre panneau`, `+ ${attentionPanelsExtra} autres panneaux`)}
                                        </p>
                                    </DataCard>
                                )}

                                {pendingLogistics.slice(0, 4).map(p => {
                                    const currentStatus = p.shipping_status || 'En attente de validation';
                                    const isRefused = currentStatus === 'Maquette refusée';
                                    const isClientValidation = currentStatus === 'Attente validation client';
                                    const variant = isRefused ? 'danger' : (isClientValidation ? 'warning' : 'warning');
                                    
                                    return (
                                        <DataCard key={`log_mini_${p.id}`} variant={variant} onClick={() => setActiveTab('livraisons')} 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={variant} 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={() => setActiveTab('livraisons')} 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">
                                            {window.pano_formatPlural(pendingLogisticsExtra, `+ ${pendingLogisticsExtra} autre commande`, `+ ${pendingLogisticsExtra} autres commandes`)}
                                        </p>
                                    </DataCard>
                                )}
                            </>
                        )}
                    </CardGrid>
                )}
            </div>
        );
    };

    const renderStatsBlock = () => (
        <div className="space-y-4">
            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                <BuildingIcon size={20} className="text-blue-600" /> Vue d'ensemble
            </h2>
            <CardGrid minWidth="260px">
                <StatCard title="Panneaux actifs" value={activePanelsCount} icon={<BuildingIcon size={24}/>} variant="success" onClick={() => setActiveTab('panels')} />
                <StatCard title="Projets en brouillon" value={draftPanelsCount} icon={<BuildingIcon size={24}/>} variant="secondary" onClick={() => setActiveTab('panels')} />
                <StatCard title="Vues (Scans QR)" value={totalViews} icon={<EyeIcon size={24}/>} variant="info" />
            </CardGrid>
        </div>
    );

    const renderChatsBlock = () => {
        return (
            <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100">
                <div className="flex justify-between items-center mb-6">
                    <h3 className="font-black text-slate-800 flex items-center gap-2">
                        <MessageSquareIcon size={18} className="text-emerald-600"/> Conversations récentes
                    </h3>
                    <span role="button" tabIndex={0} onClick={() => setActiveTab('messages')} className="text-xs font-bold text-emerald-600 hover:underline cursor-pointer">Voir tout</span>
                </div>
                <div className="space-y-3">
                    {dashboardThreads.map(t => {
                        const lastMsg = t.messages.length > 0 ? t.messages[t.messages.length - 1] : null;
                        const IconToUse = t.type === 'support' ? MessageSquareIcon : MessageCircleIcon;
                        return (
                            <DataCard 
                                key={t.id} 
                                onClick={(e) => {
                                    e.stopPropagation();
                                    if(openLocalModal) openLocalModal('chat', t.id, false);
                                }} 
                                className="cursor-pointer hover:border-emerald-300 transition group p-4"
                            >
                                <div className="flex items-center gap-3 relative min-w-0">
                                    <NotificationBadge count={t.unread} className="absolute -top-2 -right-2" />
                                    {IconBadge && <IconBadge icon={IconToUse} variant={t.type === 'support' ? 'success' : 'warning'} size="md" />}
                                    <div className="min-w-0 flex-1 pr-2">
                                        <p className={`text-sm font-bold break-words leading-tight ${t.type === 'support' ? 'text-emerald-700' : 'text-amber-700'}`}>
                                            {t.title}
                                        </p>
                                        <p className="text-[10px] uppercase tracking-widest text-slate-500 font-bold break-words mt-0.5">{t.targetEmail}</p>
                                    </div>
                                </div>
                                <div className="pt-2 border-t border-slate-100 flex-1 min-w-0">
                                    <div className={`text-xs max-h-16 overflow-y-auto custom-scrollbar break-words block ${t.unread > 0 ? 'text-slate-800 font-bold' : 'text-slate-500'}`}>
                                        {lastMsg ? lastMsg.detail.replace(/\[ATTACHMENT:[^\]]+\]/g, '[Pièce jointe]').replace(/<[^>]*>?/gm, '') : <span className="italic text-slate-400">Nouvelle conversation...</span>}
                                    </div>
                                </div>
                            </DataCard>
                        );
                    })}
                    {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">Aucune interaction récente.</p>
                    )}
                </div>
            </div>
        );
    };

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

    const demoPanneau = allPanels.find(p => p.id === 'demo-panneau') || { id: 'demo-panneau', status: 'Actif', offerType: 'demo', name: 'Panneau de démonstration', location: 'Paris', themeColor: '#059669', hasNoAds: false };
    const demoHasDraft = demoPanneau.draft_data && Object.keys(demoPanneau.draft_data).length > 0;

    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">Tableau de bord</h1>
                        <p className="text-slate-500 font-medium break-words leading-relaxed">Bienvenue sur votre espace personnel <TextLogo className="text-sm" />.</p>
                    </div>
                    <div className="flex flex-wrap gap-2 w-full md:w-auto shrink-0">
                        <Button 
                            variant="secondary" 
                            icon={SlidersHorizontalIcon} 
                            onClick={(e) => openLocalDialog('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>
                        <Button 
                            variant="primary" 
                            icon={PlusIcon} 
                            onClick={handleCreateNewPanel} 
                            className="px-6 py-3 uppercase tracking-widest shadow-md flex-[2] justify-center text-xs"
                        >
                            Nouveau projet
                        </Button>
                    </div>
                </div>

                {visiblePanels.some(p => p.id === 'demo-panneau') && (
                    <div className="bg-purple-50 border border-purple-200 rounded-3xl p-5 flex flex-col sm:flex-row justify-between items-center gap-4 shadow-sm mb-6 min-w-0 w-full">
                        <div className="flex gap-4 items-center min-w-0 flex-1">
                            <IconBadge icon={BuildingIcon} variant="purple" size="lg" className="shrink-0" />
                            <div className="min-w-0">
                                <h3 className="font-black text-purple-900 text-lg flex flex-wrap items-center gap-2 break-words leading-tight">
                                    Panneau de démonstration
                                    {demoHasDraft && <span className="text-[10px] font-black uppercase tracking-widest bg-purple-200 text-purple-800 px-2 py-0.5 rounded shadow-sm">Modifié</span>}
                                </h3>
                                <p className="text-xs text-purple-700 font-medium break-words mt-1 leading-tight">Modifiez ce panneau pour mettre à jour la page d'accueil.</p>
                            </div>
                        </div>
                        
                        <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto shrink-0">
                            <Button variant="success" shape="square" icon={QrCodeIcon} onClick={() => { const livePanel = { ...demoPanneau }; delete livePanel.draft_data; if (setPreviewPanneau) setPreviewPanneau(livePanel); openLocalModal('preview', livePanel.id, false); }} className="bg-white shadow-sm flex-1 sm:flex-none" title="Voir le panneau en ligne" />
                            <Button variant="purple" icon={EditIcon} onClick={() => {
                                const panelToEdit = JSON.parse(JSON.stringify(demoPanneau));
                                if (panelToEdit.draft_data && Object.keys(panelToEdit.draft_data).length > 0) {
                                    const draft = panelToEdit.draft_data;
                                    delete panelToEdit.draft_data;
                                    Object.assign(panelToEdit, draft);
                                }
                                setManagingPanneau(panelToEdit);
                                setValidationErrors([]);
                                openLocalModal('editor', 'demo-panneau', false);
                            }} className="w-full sm:w-auto px-8 py-3.5 uppercase tracking-widest font-black shadow-md justify-center">
                                Édition
                            </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 GLOBALE */}
            {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/clients/_clients_dashboard.jsx] */