/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglets Panneaux, Logistique et Messagerie
 * =========================================================================
 */

const { useState, useEffect } = React;
const { 
    Building, Eye, AlertOctagon, CheckCircle, AlertTriangle, Power, 
    Package, MapPin, RefreshCw, Edit, FileText, Download, Plus, 
    MessageSquare, ArrowLeft, KeyRound, ShieldAlert, Shield, Mail, Trash2, X, Loader
} = window;

// =========================================================================
// 1. ONGLET : TOUS LES PANNEAUX
// =========================================================================

window.AdminPanneauxTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [previewPanneau, setPreviewPanneau] = useState(null);
    const [managingPanneau, setManagingPanneau] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalView, setModalView] = useState(null);
    const [editingEntity, setEditingEntity] = useState(null);
    const [draggedItem, setDraggedItem] = useState(null);
    const [moderationData, setModerationData] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);

    const clients = data.clients || [];
    const panneaux = data.panneaux || [];
    
    const demoPanneau = panneaux.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 regularPanneaux = panneaux.filter(p => p.id !== 'demo-panneau');
    const unseenPanels = regularPanneaux.filter(p => !p.admin_seen);
    const seenPanels = regularPanneaux.filter(p => p.admin_seen);

    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: [] };
        
        blacklist.forEach(word => { 
            if(textToSearch.includes(word)) { 
                blackCount++; 
                detected.black.push(word); 
            } 
        });
        
        greylist.forEach(word => { 
            if(textToSearch.includes(word)) { 
                greyCount++; 
                detected.grey.push(word); 
            } 
        });
        
        return { isViolation: blackCount > 0 || greyCount > 2, detected };
    };

    const handlePreviewAndMarkSeen = async (p) => {
        setPreviewPanneau(p);
        if (!p.admin_seen) {
            try {
                const payload = {
                    id: p.id, 
                    status: p.status, 
                    offerType: p.offerType, 
                    currentRate: p.currentRate, 
                    physicalPanels: p.physicalPanels,
                    details: { ...p, admin_seen: true }
                };
                await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux', { 
                    method: 'POST', 
                    body: JSON.stringify(payload) 
                });
                refreshData();
            } catch(e) {
                console.error("Erreur de marquage vu", e);
            }
        }
    };

    const togglePanneauStatus = (id, currentStatus) => {
        const newStatus = currentStatus === 'Actif' ? 'Hors ligne' : 'Actif';
        setConfirmDialog({
            title: "Changement de statut",
            message: `Êtes-vous sûr de vouloir passer ce panneau en statut : ${newStatus} ? Si le panneau possède un abonnement Stripe, celui-ci pourrait être affecté.`,
            confirmText: "Confirmer",
            isDestructive: newStatus === 'Hors ligne' || newStatus === 'Désactivé',
            onConfirm: async () => {
                setIsSaving(true);
                try {
                    await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux/status', { 
                        method: 'POST', 
                        body: JSON.stringify({ id, status: newStatus }) 
                    });
                    refreshData();
                    showToast(`Le panneau est maintenant ${newStatus}.`, "success");
                } catch (e) {
                    showToast("Erreur lors du changement de statut.", "error");
                } finally { 
                    setIsSaving(false); 
                }
            }
        });
    };

    const handleSavePanneau = async () => {
        setIsSaving(true);
        try {
            const payload = { 
                id: 'demo-panneau', 
                status: 'Actif', 
                offerType: 'demo', 
                currentRate: 0, 
                physicalPanels: 0, 
                details: managingPanneau 
            };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux', { 
                method: 'POST', 
                body: JSON.stringify(payload) 
            });
            const d = await res.json();
            if(d.status === 'success') { 
                showToast("Panneau de démonstration mis à jour !", "success"); 
                setIsModalOpen(false); 
                refreshData(); 
            } else {
                showToast(d.message, 'error');
            }
        } catch(e) { 
            showToast("Erreur de sauvegarde", "error"); 
        }
        setIsSaving(false);
    };

    const saveEditedEntity = () => {
        let newInter = [...(managingPanneau.intervenants || [])];
        let newLots = JSON.parse(JSON.stringify(managingPanneau.lots || []));
        const loc = editingEntity.location;

        if (loc.type === 'intervenant') {
            if (loc.index !== undefined) {
                newInter[loc.index] = editingEntity.data;
            } else {
                newInter.push({...editingEntity.data, id: crypto.randomUUID()});
            }
        } else if (loc.type === 'lot') {
            if (loc.index !== undefined) {
                newLots[loc.index] = {...newLots[loc.index], ...editingEntity.data};
            } else {
                newLots.push({...editingEntity.data, id: crypto.randomUUID(), entreprises: []});
            }
        } else if (loc.type === 'entreprise') {
            if (loc.index !== undefined) {
                newLots[loc.lotIndex].entreprises[loc.index] = editingEntity.data;
            } else {
                newLots[loc.lotIndex].entreprises.push({...editingEntity.data, id: crypto.randomUUID()});
            }
        }
        setManagingPanneau({ ...managingPanneau, intervenants: newInter, lots: newLots });
        setEditingEntity(null);
    };

    const deleteEntity = (loc) => {
        setConfirmDialog({
            title: "Supprimer l'élément",
            message: "Êtes-vous sûr de vouloir supprimer cet élément de l'équipe du projet ?",
            confirmText: "Supprimer",
            isDestructive: true,
            onConfirm: () => {
                let newInter = [...(managingPanneau.intervenants || [])];
                let newLots = JSON.parse(JSON.stringify(managingPanneau.lots || []));
                
                if (loc.type === 'intervenant') {
                    newInter.splice(loc.index, 1);
                } else if (loc.type === 'lot') {
                    newLots.splice(loc.index, 1);
                } else {
                    newLots[loc.lotIndex].entreprises.splice(loc.index, 1);
                }
                
                setManagingPanneau({ ...managingPanneau, intervenants: newInter, lots: newLots });
            }
        });
    };

    const handleDragStart = (e, location) => { 
        setDraggedItem(location); 
        e.dataTransfer.effectAllowed = 'move'; 
    };
    
    const handleDragOver = (e) => { 
        e.preventDefault(); 
        e.dataTransfer.dropEffect = 'move'; 
    };
    
    const handleDrop = (e, dropLocation) => {
        e.preventDefault();
        if (!draggedItem || draggedItem.type !== dropLocation.type) return;
        if (draggedItem.type === 'entreprise' && draggedItem.lotIndex !== dropLocation.lotIndex) return;
        
        let newInter = [...(managingPanneau.intervenants || [])]; 
        let newLots = JSON.parse(JSON.stringify(managingPanneau.lots || []));
        
        if (draggedItem.type === 'intervenant') { 
            const item = newInter.splice(draggedItem.index, 1)[0]; 
            newInter.splice(dropLocation.index, 0, item); 
        } else if (draggedItem.type === 'lot') { 
            const item = newLots.splice(draggedItem.index, 1)[0]; 
            newLots.splice(dropLocation.index, 0, item); 
        } else if (draggedItem.type === 'entreprise') { 
            const arr = newLots[dropLocation.lotIndex].entreprises; 
            const item = arr.splice(draggedItem.index, 1)[0]; 
            arr.splice(dropLocation.index, 0, item); 
        }
        
        setManagingPanneau({ ...managingPanneau, intervenants: newInter, lots: newLots });
        setDraggedItem(null);
    };

    const PanelCard = ({ c }) => {
        const client = clients.find(cl => cl.id === c.clientName);
        const { isViolation, detected } = checkPanelViolations(c);
        
        return (
            <div className={`bg-white rounded-3xl p-5 shadow-sm border flex flex-col gap-4 transition hover:shadow-md ${isViolation ? 'border-red-400 bg-red-50/30' : 'border-slate-200 hover:border-emerald-200'} group`}>
                <div className="flex justify-between items-start gap-2">
                    <div className="flex gap-3 min-w-0">
                        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${c.status === 'Actif' ? 'bg-emerald-50 text-emerald-600' : 'bg-slate-100 text-slate-400'}`}>
                            <Building size={24} />
                        </div>
                        <div className="min-w-0">
                            <p className="font-black text-base text-slate-800 truncate" title={c.name}>{c.name}</p>
                            <p className="text-xs text-slate-500 truncate" title={c.location}>{c.location}</p>
                            <div className="mt-1.5 flex flex-wrap gap-1">
                                <span className="text-[9px] font-bold text-emerald-700 bg-emerald-50 border border-emerald-100 px-2 py-0.5 rounded-md truncate max-w-full" title={`Client : ${client ? client.name : c.clientName}`}>
                                    Client : {client ? client.name : c.clientName}
                                </span>
                            </div>
                        </div>
                    </div>
                    {isViolation && (
                        <button onClick={() => setModerationData({ panneau: c, detected })} className="p-2 bg-red-100 text-red-600 rounded-xl hover:bg-red-200 transition shrink-0" title="Alerte modération détectée">
                            <AlertTriangle size={18}/>
                        </button>
                    )}
                </div>
                
                <div className="grid grid-cols-2 gap-2 mt-auto">
                    <div className="bg-slate-50 p-2 rounded-xl border border-slate-100 text-center">
                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Abonnement</p>
                        <p className="text-sm font-black text-slate-800 mt-0.5">
                            {c.offerType === 'rental' ? 'Loc.' : 'Achat'} 
                            <span className="text-xs text-slate-500 font-medium ml-1">({c.currentRate}€)</span>
                        </p>
                    </div>
                    <div className="bg-slate-50 p-2 rounded-xl border border-slate-100 text-center">
                        <p className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">Statut</p>
                        <p className={`text-sm font-black mt-0.5 ${c.status === 'Actif' ? 'text-emerald-600' : 'text-slate-600'}`}>
                            {c.status}
                        </p>
                    </div>
                </div>

                <div className="pt-4 border-t border-slate-100 flex gap-2">
                    <button 
                        onClick={() => handlePreviewAndMarkSeen(c)} 
                        title="Contrôler le panneau public" 
                        className="flex-1 py-2 bg-blue-50 text-blue-700 rounded-xl text-xs font-bold hover:bg-blue-100 transition flex justify-center items-center gap-2"
                    >
                        <Eye size={14}/> Contrôler
                    </button>
                    <button 
                        onClick={() => togglePanneauStatus(c.id, c.status)} 
                        title={c.status === 'Actif' ? 'Désactiver le panneau (coupe abonnement)' : 'Activer le panneau'} 
                        className={`flex-1 py-2 rounded-xl text-xs font-bold transition flex justify-center items-center gap-2 ${c.status === 'Actif' ? 'bg-red-50 text-red-600 hover:bg-red-100' : 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100'}`}
                    >
                        <Power size={14}/> {c.status === 'Actif' ? 'Désactiver' : 'Activer'}
                    </button>
                </div>
            </div>
        );
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Tous les panneaux</h1>
                    <p className="text-slate-500 font-medium">Supervision des affichages légaux de l'ensemble du parc.</p>
                </div>
            </div>
            
            <div className="bg-purple-50 border border-purple-200 rounded-3xl p-5 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 shadow-sm">
                <div className="flex gap-4 items-center">
                    <div className="w-12 h-12 bg-purple-200 text-purple-700 rounded-2xl flex items-center justify-center shrink-0">
                        <Eye size={24}/>
                    </div>
                    <div>
                        <h3 className="font-black text-purple-900 text-lg leading-tight">Panneau de démonstration</h3>
                        <p className="text-xs text-purple-700 font-medium mt-1">Gérez le contenu du faux panneau affiché sur la page d'accueil publique.</p>
                    </div>
                </div>
                
                <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                    <button 
                        onClick={() => setPreviewPanneau({...demoPanneau})} 
                        title="Aperçu du panneau de démonstration" 
                        className="w-full sm:w-auto bg-purple-100 text-purple-700 px-6 py-3 rounded-xl text-sm font-bold shadow-sm hover:bg-purple-200 transition flex items-center justify-center gap-2"
                    >
                        <Eye size={16}/> Aperçu
                    </button>
                    <button 
                        onClick={() => { setManagingPanneau({...demoPanneau}); setModalView('config_demo'); setIsModalOpen(true); }} 
                        title="Éditer le panneau de démonstration" 
                        className="w-full sm:w-auto bg-purple-600 text-white px-6 py-3 rounded-xl text-sm font-bold shadow-lg hover:bg-purple-700 transition flex items-center justify-center gap-2"
                    >
                        <Edit size={16}/> Éditer le panneau
                    </button>
                </div>
            </div>

            {unseenPanels.length > 0 && (
                <div className="space-y-4">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 pt-4">
                        <AlertOctagon size={20} className="text-amber-500"/> À contrôler (nouveaux ou modifiés)
                    </h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {unseenPanels.map(c => <PanelCard key={c.id} c={c} />)}
                    </div>
                </div>
            )}

            {seenPanels.length > 0 && (
                <div className="space-y-4">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 pt-4 border-t border-slate-200 mt-6">
                        <CheckCircle size={20} className="text-emerald-500"/> Déjà contrôlés
                    </h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 opacity-90 hover:opacity-100 transition-opacity">
                        {seenPanels.map(c => <PanelCard key={c.id} c={c} />)}
                    </div>
                </div>
            )}

            {regularPanneaux.length === 0 && (
                <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                    <Building size={48} className="mx-auto text-slate-300 mb-4" />
                    <p className="text-slate-500 italic">Aucun panneau client enregistré.</p>
                </div>
            )}

            {/* MODALES LOCALES DES PANNEAUX */}
            {isModalOpen && modalView === 'config_demo' && (
                <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-md z-[200] animate-in fade-in duration-300 flex items-center justify-center p-0 sm:p-4" onMouseDown={(e) => { if(e.target === e.currentTarget) setIsModalOpen(false); }}>
                    <div className="h-full sm:h-[95vh] w-full max-w-5xl mx-auto bg-white sm:rounded-3xl shadow-2xl flex flex-col relative overflow-hidden" onMouseDown={e => e.stopPropagation()}>
                        <div className="p-4 sm:p-6 border-b border-slate-100 flex justify-between items-center bg-purple-50 shrink-0">
                            <div>
                                <h2 className="text-xl font-black text-purple-900">Édition du panneau démo</h2>
                                <p className="text-xs text-purple-700 font-medium">Panneau public vitrine.</p>
                            </div>
                            <button onClick={() => setIsModalOpen(false)} title="Fermer" className="text-slate-400 hover:bg-white hover:text-slate-700 p-2 rounded-xl border border-transparent hover:border-slate-200 transition">
                                <X size={24}/>
                            </button>
                        </div>
                        <div className="flex-1 relative overflow-hidden">
                            <window.PanneauEditorForm 
                                panneau={managingPanneau} 
                                setPanneau={setManagingPanneau} 
                                managingPanneau={managingPanneau} 
                                onCancel={() => setIsModalOpen(false)} 
                                onSaveActive={handleSavePanneau} 
                                onEditEntity={(loc, data) => setEditingEntity({location: loc, data})} 
                                draggedItem={draggedItem} 
                                handleDragStart={handleDragStart} 
                                handleDragOver={handleDragOver} 
                                handleDrop={handleDrop} 
                                deleteEntity={deleteEntity} 
                                isSaving={isSaving} 
                                uiMode="professionnel" 
                            />
                        </div>
                        {editingEntity && (
                            <window.EntityEditorModal 
                                editingEntity={editingEntity} 
                                setEditingEntity={setEditingEntity} 
                                saveEditedEntity={saveEditedEntity} 
                                showToast={showToast} 
                            />
                        )}
                    </div>
                </div>
            )}

            {previewPanneau && (
                <window.PreviewModal 
                    panneau={previewPanneau} 
                    interactions={data.interactions || []} 
                    onClose={() => setPreviewPanneau(null)} 
                    showToast={showToast} 
                    refreshData={refreshData} 
                />
            )}

            {moderationData && (
                <window.Modal title="Alerte modération" onClose={() => setModerationData(null)} zIndex="z-[250]">
                    <div className="space-y-4">
                        <p className="text-sm font-bold text-slate-700 mb-2">
                            Mots détectés dans le panneau : <span className="text-slate-900">{moderationData.panneau.name}</span>
                        </p>
                        
                        {moderationData.detected.black.length > 0 && (
                            <div className="bg-red-100 text-red-800 p-3 rounded-lg text-sm border border-red-200">
                                <strong>Liste noire :</strong> {moderationData.detected.black.join(', ')}
                            </div>
                        )}
                        
                        {moderationData.detected.grey.length > 0 && (
                            <div className="bg-amber-100 text-amber-800 p-3 rounded-lg text-sm border border-amber-200">
                                <strong>Liste grise :</strong> {moderationData.detected.grey.join(', ')}
                            </div>
                        )}

                        <div className="flex flex-col gap-3 pt-4 border-t border-slate-100">
                            <button onClick={() => {
                                const u = new URL(window.location);
                                u.searchParams.set('chat_id', 'SUPPORT_' + moderationData.panneau.clientName);
                                window.history.replaceState({}, '', u);
                                setActiveTab('messages');
                                setModerationData(null);
                            }} className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold hover:bg-blue-700 flex items-center justify-center gap-2 transition">
                                <MessageSquare size={16}/> Contacter le client
                            </button>
                            <button onClick={() => {
                                togglePanneauStatus(moderationData.panneau.id, moderationData.panneau.status);
                                setModerationData(null);
                            }} className="w-full bg-red-600 text-white py-3 rounded-xl font-bold hover:bg-red-700 flex items-center justify-center gap-2 transition">
                                <Power size={16}/> Suspendre ce panneau
                            </button>
                            <button onClick={() => setModerationData(null)} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition">
                                Ignorer l'alerte
                            </button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {confirmDialog && (
                <window.ConfirmModal {...confirmDialog} zIndex="z-[250]" onCancel={() => setConfirmDialog(null)} />
            )}
        </div>
    );
};

// =========================================================================
// 2. ONGLET : LOGISTIQUE
// =========================================================================

window.AdminLogistiqueTab = ({ data, refreshData, showToast }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [shippingModal, setShippingModal] = useState(null);
    const [trackingData, setTrackingData] = useState({ number: '', link: '' });
    const [confirmDialog, setConfirmDialog] = useState(null);

    const clients = data.clients || [];
    const panneaux = data.panneaux || [];
    const logiPanneaux = panneaux.filter(p => p.physicalPanels > 0 && p.id !== 'demo-panneau');

    const updateShipping = async (id, status, tracking_number, tracking_link = '') => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux/shipping', { 
                method: 'POST', 
                body: JSON.stringify({ id, shipping_status: status, tracking_number, tracking_link }) 
            });
            const d = await res.json();
            
            if (d.status === 'success') {
                showToast(`Statut logistique mis à jour : ${status}`, "success");
                setShippingModal(null);
                refreshData();
            } else {
                showToast(d.message || "Erreur de mise à jour", "error");
            }
        } catch(e) {
            showToast("Erreur réseau", "error");
        } finally { 
            setIsSaving(false); 
        }
    };

    const handleA1Upload = async (c, e) => {
        const file = e.target.files[0];
        if(!file) return;
        
        setIsSaving(true);
        try {
            const id = await window.uploadFile(file, 'pdf');
            const payload = { 
                id: c.id, 
                status: c.status, 
                offerType: c.offerType, 
                currentRate: c.currentRate, 
                physicalPanels: c.physicalPanels, 
                details: { ...c, a1PdfId: id } 
            };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux', { 
                method: 'POST', 
                body: JSON.stringify(payload) 
            });
            const d = await res.json();
            if(d.status === 'success') { 
                showToast("Fichier A1 attaché avec succès !", "success"); 
                refreshData(); 
            } else {
                showToast(d.message, 'error');
            }
        } catch(err) { 
            showToast("Erreur d'upload", "error"); 
        }
        
        setIsSaving(false);
        e.target.value = null;
    };

    const handleA1Delete = (c) => {
        setConfirmDialog({
            title: "Retirer la maquette",
            message: "Voulez-vous vraiment retirer ce fichier A1 de la commande ?",
            confirmText: "Retirer",
            isDestructive: true,
            onConfirm: async () => {
                setIsSaving(true);
                try {
                    const payload = { 
                        id: c.id, 
                        status: c.status, 
                        offerType: c.offerType, 
                        currentRate: c.currentRate, 
                        physicalPanels: c.physicalPanels, 
                        details: { ...c, a1PdfId: '' } 
                    };
                    
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux', { 
                        method: 'POST', 
                        body: JSON.stringify(payload) 
                    });
                    const d = await res.json();
                    if (d.status === 'success') {
                        showToast("Fichier A1 retiré.", "success");
                        refreshData();
                    } else {
                        showToast(d.message, "error");
                    }
                } catch(e) {
                    showToast("Erreur lors de la suppression", "error");
                }
                setIsSaving(false);
            }
        });
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div>
                    <h1 className="text-3xl font-black text-slate-800">Logistique</h1>
                    <p className="text-slate-500 font-medium">Gestion des expéditions de panneaux physiques A1.</p>
                </div>
            </div>
            
            <div className="grid grid-cols-1 gap-4">
                {logiPanneaux.map(c => {
                    const client = clients.find(cl => cl.id === c.clientName);
                    
                    const status = c.shipping_status || 'Validation en cours';
                    const isValidation = status === 'Validation en cours';
                    const isPrinting = status === "Attente d'impression";
                    const isShipped = status === 'Expédié';
                    const isDelivered = status === 'Livré';

                    return (
                        <div key={c.id} className="bg-white rounded-3xl p-5 shadow-sm border border-slate-200 flex flex-col md:flex-row gap-4 md:items-center transition hover:shadow-md">
                            <div className="flex-1 min-w-0 flex items-start gap-4">
                                <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${isDelivered ? 'bg-emerald-50 text-emerald-600' : (isShipped ? 'bg-blue-50 text-blue-600' : 'bg-slate-100 text-slate-500')}`}>
                                    {isDelivered ? <CheckCircle size={24}/> : <Package size={24} />}
                                </div>
                                <div className="min-w-0 flex-1">
                                    <p className="font-black text-base text-slate-800 truncate" title={c.name}>{c.name}</p>
                                    <p className="text-xs font-bold text-emerald-600 mt-0.5 truncate" title={client?.name}>
                                        Client : {client?.name || 'Inconnu'}
                                    </p>
                                    <p className="text-xs text-slate-500 mt-1 flex items-start gap-1">
                                        <MapPin size={14} className="shrink-0 opacity-70" />
                                        <span className="line-clamp-2 leading-tight" title={c.shippingAddress || client?.address}>
                                            {c.shippingAddress || client?.address || 'Adresse non renseignée'}
                                        </span>
                                    </p>
                                </div>
                            </div>

                            <div className="md:w-24 shrink-0 flex flex-col items-start md:items-center border-t md:border-t-0 md:border-l border-slate-100 pt-4 md:pt-0 md:px-4">
                                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-2">Quantité</p>
                                <div className="w-12 h-12 flex items-center justify-center bg-emerald-50 text-emerald-600 rounded-xl font-black text-xl">
                                    {c.physicalPanels}
                                </div>
                            </div>

                            <div className="md:w-64 shrink-0 flex flex-col gap-2 border-t md:border-t-0 md:border-l border-slate-100 pt-4 md:pt-0 md:px-4">
                                <div className="flex justify-between items-center mb-1">
                                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Statut</p>
                                    <span className={`px-2 py-0.5 rounded-md text-[10px] font-black uppercase ${isDelivered ? 'bg-emerald-100 text-emerald-700' : (isShipped ? 'bg-blue-100 text-blue-700' : 'bg-amber-100 text-amber-700')}`}>
                                        {status}
                                    </span>
                                </div>
                                
                                {isValidation && (
                                    <button 
                                        onClick={() => updateShipping(c.id, "Attente d'impression", '', '')} 
                                        disabled={isSaving || !c.a1PdfId} 
                                        className="w-full py-2 bg-amber-50 text-amber-700 font-bold rounded-xl hover:bg-amber-100 transition text-xs flex justify-center items-center gap-1 disabled:opacity-50"
                                        title={!c.a1PdfId ? "Veuillez d'abord valider et attacher la maquette A1" : ""}
                                    >
                                        <RefreshCw size={14}/> Passer en impression
                                    </button>
                                )}
                                {isPrinting && (
                                    <button 
                                        onClick={() => { setShippingModal(c); setTrackingData({number: '', link: ''}); }} 
                                        disabled={isSaving} 
                                        className="w-full py-2 bg-blue-50 text-blue-700 font-bold rounded-xl hover:bg-blue-100 transition text-xs flex justify-center items-center gap-1 disabled:opacity-50"
                                    >
                                        <Package size={14}/> Déclarer expédié
                                    </button>
                                )}
                                {isShipped && (
                                    <div className="text-center bg-slate-50 p-3 rounded-xl border border-slate-100 flex flex-col gap-1">
                                        <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">En cours d'acheminement</p>
                                        <p className="text-sm font-mono text-blue-600 font-bold select-all">{c.tracking_number}</p>
                                        <button 
                                            onClick={() => { setShippingModal(c); setTrackingData({number: c.tracking_number || '', link: c.tracking_link || ''}); }} 
                                            disabled={isSaving} 
                                            className="mt-2 w-full py-1.5 bg-white border border-slate-200 text-slate-600 font-bold rounded-lg hover:bg-slate-50 transition text-[10px] flex justify-center items-center gap-1 shadow-sm"
                                        >
                                            <Edit size={12}/> Modifier le suivi
                                        </button>
                                    </div>
                                )}
                                {isDelivered && (
                                    <div className="text-center bg-emerald-50 p-2 rounded-xl border border-emerald-100 flex items-center justify-center gap-1">
                                        <CheckCircle size={14} className="text-emerald-600"/>
                                        <p className="text-xs font-bold text-emerald-700">Réception confirmée</p>
                                    </div>
                                )}
                            </div>

                            <div className="md:w-32 shrink-0 flex items-center justify-end md:justify-center border-t md:border-t-0 md:border-l border-slate-100 pt-4 md:pt-0 md:pl-4">
                                {c.a1PdfId ? (
                                    <div className="flex flex-col gap-2 w-full">
                                        <a href={`?api=file/download&type=pdf&id=${c.a1PdfId}`} target="_blank" className="flex flex-col items-center justify-center p-2 w-full bg-blue-50 text-blue-600 rounded-xl hover:bg-blue-100 transition group" title="Télécharger le fichier A1 validé">
                                            <FileText size={18} className="group-hover:scale-110 transition-transform mb-1 text-blue-600" />
                                            <span className="text-[10px] font-black uppercase tracking-wider mt-1 text-center">PDF Validé</span>
                                        </a>
                                        <button onClick={() => handleA1Delete(c)} disabled={isSaving} className="text-[10px] text-red-500 font-bold hover:text-red-700 transition w-full text-center">
                                            Retirer
                                        </button>
                                    </div>
                                ) : (
                                    <div className="flex flex-col gap-2 w-full">
                                        <div className="flex flex-col gap-1 w-full">
                                            <button 
                                                onClick={async () => {
                                                    setIsSaving(true);
                                                    try {
                                                        const blob = await window.generateA1PDF(c);
                                                        const link = document.createElement('a');
                                                        link.href = URL.createObjectURL(blob);
                                                        link.download = `Panneau_A1_${c.id}.pdf`;
                                                        link.click();
                                                    } catch(e) { 
                                                        showToast("Erreur PDF", "error"); 
                                                    }
                                                    setIsSaving(false);
                                                }} 
                                                disabled={isSaving} 
                                                className="py-1.5 px-2 bg-slate-100 text-slate-700 font-bold rounded-lg text-[10px] hover:bg-slate-200 transition w-full flex justify-center items-center gap-1 shadow-sm" 
                                                title="Télécharger le PDF généré automatiquement pour vérification"
                                            >
                                                <Download size={12}/> Contrôler
                                            </button>
                                            
                                            <button 
                                                onClick={() => {
                                                    setConfirmDialog({
                                                        title: "Validation de la maquette",
                                                        message: "Valider ce PDF généré automatiquement pour l'impression ?",
                                                        confirmText: "Valider",
                                                        onConfirm: async () => {
                                                            setIsSaving(true);
                                                            try {
                                                                const blob = await window.generateA1PDF(c);
                                                                const file = new File([blob], `A1_${c.id}.pdf`, { type: 'application/pdf' });
                                                                const id = await window.uploadFile(file, 'pdf');
                                                                const payload = { 
                                                                    id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, 
                                                                    details: { ...c, a1PdfId: id } 
                                                                };
                                                                const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'panneaux', { method: 'POST', body: JSON.stringify(payload) });
                                                                if((await res.json()).status === 'success') { 
                                                                    showToast("PDF généré et validé !", "success"); 
                                                                    refreshData(); 
                                                                } else {
                                                                    showToast("Erreur de sauvegarde", "error");
                                                                }
                                                            } catch(e) {
                                                                showToast("Erreur d'upload", "error");
                                                            }
                                                            setIsSaving(false);
                                                        }
                                                    });
                                                }} 
                                                disabled={isSaving} 
                                                className="py-1.5 px-2 bg-emerald-50 text-emerald-700 font-bold rounded-lg text-[10px] hover:bg-emerald-100 transition w-full flex justify-center items-center gap-1 shadow-sm" 
                                                title="Valider et attacher la maquette générée automatiquement"
                                            >
                                                <CheckCircle size={12}/> Valider
                                            </button>
                                        </div>
                                        
                                        <div className="relative w-full text-center my-0.5">
                                            <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-slate-200"></div></div>
                                            <div className="relative flex justify-center"><span className="bg-white px-1 text-[8px] uppercase tracking-widest text-slate-400">Ou</span></div>
                                        </div>

                                        <label className="cursor-pointer flex flex-col items-center justify-center p-2 w-full bg-white text-slate-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition border border-dashed border-slate-300 hover:border-blue-300" title="Uploader une maquette PDF modifiée manuellement">
                                            <Plus size={14} className="mb-0.5" />
                                            <span className="text-[9px] font-black uppercase tracking-wider">Manquant</span>
                                            <input type="file" accept="application/pdf" className="hidden" disabled={isSaving} onChange={(e) => handleA1Upload(c, e)} />
                                        </label>
                                    </div>
                                )}
                            </div>
                        </div>
                    );
                })}
                {logiPanneaux.length === 0 && (
                    <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <Package size={48} className="mx-auto text-slate-300 mb-4" />
                        <h3 className="text-lg font-black text-slate-700">Aucune commande</h3>
                        <p className="text-slate-500 text-sm mt-1">Les commandes de panneaux physiques apparaîtront ici.</p>
                    </div>
                )}
            </div>

            {shippingModal && (
                <window.Modal 
                    title={shippingModal.shipping_status === 'Expédié' ? "Mise à jour du suivi" : "Expédition de la commande"} 
                    onClose={() => setShippingModal(null)} 
                    preventClose={isSaving}
                >
                    <div className="space-y-4">
                        <div className="bg-blue-50 p-4 rounded-xl border border-blue-100 mb-4">
                            <p className="text-sm text-blue-800 font-medium">
                                {shippingModal.shipping_status === 'Expédié' 
                                    ? "Corrigez le numéro ou le lien de suivi. Le client recevra un e-mail avec les nouvelles informations."
                                    : "Saisissez les informations de suivi pour notifier le client. Le lien de suivi est obligatoire pour valider l'expédition."}
                            </p>
                        </div>
                        <div className="space-y-1">
                            <label className="text-xs font-bold text-slate-500 uppercase">Numéro de suivi *</label>
                            <input 
                                type="text" 
                                value={trackingData.number} 
                                onChange={e=>setTrackingData({...trackingData, number: e.target.value})} 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-blue-500 outline-none transition" 
                                placeholder="Ex : 6A123456789" 
                            />
                        </div>
                        <div className="space-y-1">
                            <label className="text-xs font-bold text-slate-500 uppercase">Lien de suivi transporteur *</label>
                            <input 
                                type="url" 
                                value={trackingData.link} 
                                onChange={e=>setTrackingData({...trackingData, link: e.target.value})} 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-blue-500 outline-none transition" 
                                placeholder="Ex : https://www.laposte.fr/outils/suivre-vos-envois?code=..." 
                            />
                        </div>
                        <div className="flex gap-3 mt-6">
                            <button 
                                onClick={() => setShippingModal(null)} 
                                disabled={isSaving} 
                                className="flex-1 py-3 bg-slate-100 text-slate-700 font-bold rounded-xl hover:bg-slate-200 transition disabled:opacity-50"
                            >
                                Annuler
                            </button>
                            <button 
                                onClick={() => updateShipping(shippingModal.id, 'Expédié', trackingData.number, trackingData.link)} 
                                disabled={isSaving || !trackingData.number.trim() || !trackingData.link.trim()} 
                                className="flex-1 py-3 bg-blue-600 text-white font-black uppercase tracking-widest rounded-xl hover:bg-blue-700 transition shadow-lg disabled:opacity-50"
                            >
                                {shippingModal.shipping_status === 'Expédié' ? "Mettre à jour" : "Confirmer l'expédition"}
                            </button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {confirmDialog && (
                <window.ConfirmModal {...confirmDialog} zIndex="z-[250]" onCancel={() => setConfirmDialog(null)} />
            )}
        </div>
    );
};

// =========================================================================
// 3. ONGLET : MESSAGERIE ET SUPPORT GLOBAL
// =========================================================================

window.AdminMessagesTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [mobileChatView, setMobileChatView] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [accessRequestModal, setAccessRequestModal] = useState(null);
    const [confirmDialog, setConfirmDialog] = useState(null);

    const clients = data.clients || [];
    const interactions = data.interactions || [];
    
    const threadsMap = {};
    interactions.forEach(m => {
        let threadId = null; 
        let title = ''; 
        let targetEmail = '';
        
        if (m.panneauId === 'CONTACT_PUBLIC') { 
            targetEmail = (m.target === 'Admin') ? m.author : m.target; 
            if (!targetEmail) return; 
            threadId = `CONTACT_PUBLIC_${targetEmail}`; 
            title = `Nous contacter : ${targetEmail}`; 
        } else if (m.panneauId.startsWith('SUPPORT_')) { 
            threadId = m.panneauId; 
            const cUid = m.panneauId.split('_')[1]; 
            const cName = clients.find(c => c.id === cUid)?.name || 'Client Inconnu'; 
            title = `Support : ${cName}`; 
            targetEmail = 'Client'; 
        }
        
        if (threadId) { 
            if (!threadsMap[threadId]) {
                threadsMap[threadId] = { id: threadId, title, targetEmail, messages: [], unread: 0 }; 
            }
            threadsMap[threadId].messages.push(m); 
            
            if (m.target === 'Admin' && !m.resolved) {
                threadsMap[threadId].unread++; 
            }
        }
    });

    const requestedChatId = new URLSearchParams(window.location.search).get('chat_id');
    
    if (requestedChatId && requestedChatId.startsWith('SUPPORT_') && !threadsMap[requestedChatId]) {
        const cUid = requestedChatId.split('_')[1];
        const clientObj = clients.find(c => c.id === cUid);
        if (clientObj) {
            threadsMap[requestedChatId] = {
                id: requestedChatId,
                title: `Support : ${clientObj.name || 'Client Inconnu'}`,
                targetEmail: 'Client',
                messages: [],
                unread: 0
            };
        }
    }

    const threads = Object.values(threadsMap).sort((a,b) => {
        const dateA = a.messages.length > 0 ? new Date(String(a.messages[0].created_at || '').replace(' ', 'T')).getTime() : 0;
        const dateB = b.messages.length > 0 ? new Date(String(b.messages[0].created_at || '').replace(' ', 'T')).getTime() : 0;
        return dateB - dateA;
    });
    
    const selectedThreadId = requestedChatId || (threads[0]?.id);
    
    const setChatId = (id) => { 
        const u = new URL(window.location); 
        u.searchParams.set('chat_id', id); 
        window.history.replaceState({}, '', u); 
        setMobileChatView(true);
        refreshData(); 
    };
    
    const selectedThread = threads.find(t => t.id === selectedThreadId);

    const handleSendAdmin = async (text) => {
        if (!selectedThread) return;
        
        const optimisticMsg = {
            id: 'temp_' + Date.now(),
            panneauId: selectedThread.id.startsWith('CONTACT_PUBLIC') ? 'CONTACT_PUBLIC' : selectedThread.id,
            author: 'Admin',
            target: selectedThread.targetEmail,
            detail: text,
            isAlert: 0,
            resolved: 0,
            created_at: new Date().toISOString()
        };
        window.dispatchEvent(new CustomEvent('optimistic_message', { detail: optimisticMsg }));

        const payload = { 
            panneauId: selectedThread.id.startsWith('CONTACT_PUBLIC') ? 'CONTACT_PUBLIC' : selectedThread.id, 
            detail: text, 
            author: 'Admin', 
            targetEmail: selectedThread.targetEmail 
        };
        
        try {
            await fetch(window.ECO_CONFIG.apiBaseUrl + 'interactions', { 
                method: 'POST', 
                body: JSON.stringify(payload) 
            });
        } catch(e) {
            console.error("Erreur lors de l'envoi", e);
        }
    };

    const sendAccessRequest = async (uid, mode) => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/request_access', { 
                method: 'POST', 
                body: JSON.stringify({ uid, mode }) 
            });
            if ((await res.json()).status === 'success') {
                showToast("Demande d'accès envoyée avec succès.", "success");
                setAccessRequestModal(null);
                refreshData();
            } else {
                showToast("Erreur lors de la demande", "error");
            }
        } catch (e) {
            showToast("Erreur réseau", "error");
        } finally { setIsSaving(false); }
    };

    const revokeAccess = async (uid) => {
        setConfirmDialog({
            title: "Révocation d'accès",
            message: "Êtes-vous sûr de vouloir révoquer l'autorisation d'accès technique pour ce client ?",
            confirmText: "Oui, révoquer",
            isDestructive: true,
            onConfirm: async () => {
                setIsSaving(true);
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/revoke_access', { 
                        method: 'POST', 
                        body: JSON.stringify({ uid }) 
                    });
                    if ((await res.json()).status === 'success') {
                        showToast("Accès révoqué.", "success");
                        refreshData();
                    } else showToast("Erreur lors de la révocation", "error");
                } finally { setIsSaving(false); }
            }
        });
    };

    const impersonateClient = async (uid) => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'auth/impersonate', { method: 'POST', body: JSON.stringify({ uid }) });
            if ((await res.json()).status === 'success') window.location.href = '?'; 
            else showToast("Erreur d'accès", "error");
        } finally { setIsSaving(false); }
    };

    const currentClient = selectedThread?.id.startsWith('SUPPORT_') 
        ? clients.find(c => c.id === selectedThread.id.split('_')[1]) 
        : null;
        
    const isImpersonable = currentClient && currentClient.admin_access_until && new Date(String(currentClient.admin_access_until || '').replace(' ', 'T')) > new Date();

    let chatClientName = 'Client';
    if (currentClient && currentClient.name) {
        chatClientName = currentClient.name;
    }

    const forceChatMobile = mobileChatView || !!requestedChatId || threads.length === 1;

    return (
        <div className="flex flex-col md:flex-row h-[calc(100vh-10rem)] min-h-[600px] bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden animate-in fade-in slide-in-from-bottom-4">
            <div className={`w-full h-full md:w-1/3 border-r border-slate-200 flex-col bg-slate-50/50 ${forceChatMobile ? 'hidden md:flex' : 'flex'}`}>
                <div className="p-4 border-b border-slate-200 bg-white flex justify-between items-center">
                    <h2 className="font-black text-slate-800 text-lg">Conversations</h2>
                </div>
                <div className="flex-1 overflow-y-auto p-2 space-y-1 custom-scrollbar">
                    {threads.map(t => (
                        <button key={t.id} onClick={() => setChatId(t.id)} className={`w-full text-left p-3 rounded-xl flex items-center justify-between transition ${selectedThreadId === t.id ? 'bg-emerald-50 border border-emerald-200' : 'hover:bg-white border border-transparent'}`}>
                            <div className="min-w-0 pr-2">
                                <p className="font-bold text-sm text-slate-800 truncate">{t.title}</p>
                                <p className="text-xs text-slate-500 truncate">{t.messages.length} messages</p>
                            </div>
                            {t.unread > 0 && <span className="bg-red-500 text-white text-[10px] px-2 py-0.5 rounded-full shrink-0">{t.unread}</span>}
                        </button>
                    ))}
                    {threads.length === 0 && <p className="text-center text-slate-400 text-sm mt-10 italic">Aucune conversation.</p>}
                </div>
            </div>
            
            <div className={`w-full h-full md:w-2/3 flex-col relative bg-slate-50 ${forceChatMobile ? 'flex' : 'hidden md:flex'}`}>
                {selectedThread ? (
                    <>
                        <div className="p-4 border-b border-slate-200 bg-white shrink-0 flex items-center gap-3">
                            {threads.length > 1 && (
                                <button onClick={() => {
                                    setMobileChatView(false);
                                    const u = new URL(window.location);
                                    u.searchParams.delete('chat_id');
                                    window.history.replaceState({}, '', u);
                                }} className="md:hidden p-2 -ml-2 text-slate-500 hover:bg-slate-100 rounded-lg transition shrink-0">
                                    <ArrowLeft size={18}/>
                                </button>
                            )}
                            <h3 className="font-black text-slate-800 truncate">{selectedThread.title}</h3>
                            {selectedThread.id.startsWith('SUPPORT_') && (
                                isImpersonable ? (
                                    <div className="flex items-center gap-2 shrink-0 ml-auto">
                                        <button onClick={() => impersonateClient(currentClient.id)} className="text-xs font-bold bg-emerald-600 text-white hover:bg-emerald-700 px-3 py-1.5 rounded-lg flex items-center gap-2 transition shadow-sm">
                                            <KeyRound size={14}/> <span className="hidden sm:inline">Contrôler</span>
                                        </button>
                                        <button onClick={() => revokeAccess(currentClient.id)} className="text-xs font-bold bg-orange-100 text-orange-600 hover:bg-orange-200 px-3 py-1.5 rounded-lg flex items-center gap-2 transition shadow-sm border border-orange-200">
                                            <ShieldAlert size={14}/> <span className="hidden sm:inline">Révoquer</span>
                                        </button>
                                    </div>
                                ) : (
                                    <button onClick={() => setAccessRequestModal(currentClient.id)} className="ml-auto text-xs font-bold bg-slate-100 text-slate-600 hover:bg-slate-200 px-3 py-1.5 rounded-lg flex items-center gap-2 transition shadow-sm border border-slate-200 shrink-0">
                                        <Shield size={14}/> <span className="hidden sm:inline">Demander l'accès</span>
                                    </button>
                                )
                            )}
                        </div>
                        
                        <div className="flex-1 min-h-0 relative">
                            <div className="absolute inset-0">
                                <window.ChatBox 
                                    messages={selectedThread.messages} 
                                    currentUserRole="admin" 
                                    panneauId={selectedThread.id.startsWith('CONTACT_PUBLIC') ? 'CONTACT_PUBLIC' : selectedThread.id} 
                                    refreshData={refreshData} 
                                    onSend={handleSendAdmin}
                                    clientName={chatClientName}
                                />
                            </div>
                        </div>
                    </>
                ) : (
                    <div className="flex-1 flex flex-col items-center justify-center text-slate-400">
                        <MessageSquare size={48} className="mb-4 opacity-50"/>
                        <p className="font-medium">Sélectionnez une conversation</p>
                    </div>
                )}
            </div>

            {/* MODALES LOCALES DE MESSAGERIE */}
            {accessRequestModal && (
                <window.Modal title="Demande d'accès" onClose={() => setAccessRequestModal(null)} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-blue-50 p-4 rounded-xl border border-blue-100 text-blue-800 text-sm leading-relaxed">
                            Comment souhaitez-vous envoyer la demande d'autorisation d'accès temporaire (24h) à ce client ?
                        </div>
                        <div className="flex flex-col gap-3">
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'chat')} disabled={isSaving} className="w-full py-3 bg-white border border-slate-200 text-slate-700 font-bold rounded-xl hover:bg-slate-50 transition text-sm flex items-center justify-center gap-2 shadow-sm">
                                <MessageSquare size={16}/> Dans la messagerie (Recommandé)
                            </button>
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'email')} disabled={isSaving} className="w-full py-3 bg-white border border-slate-200 text-slate-700 font-bold rounded-xl hover:bg-slate-50 transition text-sm flex items-center justify-center gap-2 shadow-sm">
                                <Mail size={16}/> Par e-mail
                            </button>
                            <button onClick={() => sendAccessRequest(accessRequestModal, 'both')} disabled={isSaving} className="w-full py-3 bg-emerald-600 text-white font-bold rounded-xl hover:bg-emerald-700 shadow-md transition text-sm flex items-center justify-center gap-2">
                                <CheckCircle size={16}/> Les deux
                            </button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {confirmDialog && (
                <window.ConfirmModal {...confirmDialog} zIndex="z-[250]" onCancel={() => setConfirmDialog(null)} />
            )}
        </div>
    );
};

/*
		EOF	========== [_www/_react/_admin_panneaux_logistique.jsx]
*/