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

// 1. - COMPOSANT CARTE ISOLÉ ET RÉUTILISABLE (100% ENCAPSULÉ / ZÉRO-DETTE)
window.pano_AdminLogisticsCard = ({ 
    delivery: c, clients, isPinned, toggleDashboardPin, refreshData, isMini = false, limitShippingForce = 90,
    // PROPS DE ROUTAGE INJECTÉES PAR LE PARENT
    openModal, openDialog, closeCurrentLayer, activeModal, activeDialog, targetId, dialogId
}) => {
    const { useState } = React;
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // CORRECTION ZÉRO-DETTE : Fallbacks de navigation robustes
    const handleOpenModal = (n, id, s) => { if (openModal) openModal(n, id, s); };
    const handleOpenDialog = (n, id, s) => { if (openDialog) openDialog(n, id, s); };
    const handleCloseLayer = () => { if (closeCurrentLayer) closeCurrentLayer(); };

    const [isSaving, setIsSaving] = useState(false);
    const [rejectReason, setRejectReason] = useState('');
    const [adminPwd, setAdminPwd] = useState('');
    const [trackingData, setTrackingData] = useState({ number: c.tracking_number || '', link: c.tracking_link || '' });
    const [manualUploadData, setManualUploadData] = useState(null);
    const [confirmConfig, setConfirmConfig] = useState(null);
    const [hasBeenControlled, setHasBeenControlled] = useState(false);

    const { PackageIcon, CheckCircleIcon, ExternalLinkIcon, LoaderIcon, AlertTriangleIcon, EyeIcon, XIcon, PinIcon, UploadIcon, Trash2Icon, DownloadIcon, EditIcon } = window.pano_getIcons();
    const { StatusBadge, IconBadge, Button, DataCard, Modal, ConfirmModal, FormTextarea, FormInput, UniversalViewer } = window.pano_getComponents();

    const computeFileHash = async (blobOrFile) => {
        try {
            const buffer = await blobOrFile.arrayBuffer();
            const digest = await crypto.subtle.digest('SHA-256', buffer);
            const array = Array.from(new Uint8Array(digest));
            return array.map(b => b.toString(16).padStart(2, '0')).join('').substring(0, 32);
        } catch (e) {
            return Date.now().toString(16); 
        }
    };

    const owner = clients.find(cl => cl.id === c.clientName);
    const currentStatus = c.shipping_status || 'En attente de validation';
    const canModifyMaquette = ['En attente de validation', 'Attente validation client', 'Maquette refusée'].includes(currentStatus);

    let isForceDeliveryAvailable = false;
    if (currentStatus === 'Expédié' && c.updated_at) {
        const updateTime = new Date(c.updated_at.replace(' ', 'T')).getTime();
        const daysSince = (Date.now() - updateTime) / (1000 * 3600 * 24);
        if (daysSince > limitShippingForce) isForceDeliveryAvailable = true;
    }

    let variant = 'default';
    if (currentStatus === 'Maquette refusée') variant = 'danger';
    else if (['En attente de validation', 'En attente de commande au fournisseur', "En attente d'impression"].includes(currentStatus) || isForceDeliveryAvailable) variant = 'warning';
    else if (currentStatus === 'Annulé') variant = 'slate';

    const pdfFileName = `A1_${c.id}_${c.a1PdfHash || 'gen'}.pdf`;

    const handleA1Delete = () => {
        setConfirmConfig({
            title: "Retirer la maquette",
            message: "Voulez-vous retirer le fichier PDF A1 de ce panneau ?",
            confirmText: "Retirer",
            isDestructive: true,
            onConfirm: async () => {
                handleCloseLayer();
                const d = await safeFetch('panneaux', {
                    body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, a1PdfId: '', a1PdfHash: '' }, a1PdfId: '' },
                    setLoading: setIsSaving,
                    successMessage: "Maquette retirée avec succès."
                });
                if (!isMounted.current) return; // SÉCURITÉ
                if (d && refreshData) refreshData();
                setConfirmConfig(null);
            },
            onCancel: () => { setConfirmConfig(null); handleCloseLayer(); }
        });
        handleOpenDialog('confirm', c.id, false);
    };

    const updateShippingStatus = async (newStatus) => {
        const d = await safeFetch('panneaux/shipping', {
            body: { id: c.id, shipping_status: newStatus },
            setLoading: setIsSaving,
            successMessage: "Statut logistique mis à jour."
        });
        if (!isMounted.current) return; // SÉCURITÉ
        if (d && refreshData) refreshData();
    };

    const handleConfirmDelivery = async () => {
        const d = await safeFetch('panneaux/shipping', { 
            body: { id: c.id, shipping_status: 'Réception confirmée' }, 
            setLoading: setIsSaving, 
            successMessage: "Réception confirmée !" 
        });
        if (!isMounted.current) return; // SÉCURITÉ
        if (d) { 
            if (refreshData) refreshData(); 
            handleCloseLayer(); 
        }
    };

    // ------------------------------------------------------------------------
    // Rendu : Mode Mini (Historique compact)
    // ------------------------------------------------------------------------
    if (isMini) {
        return (
            <>
                <DataCard variant={variant} className="relative group p-3 min-w-0 hover:border-slate-300 transition">
                    <div className="flex justify-between items-center gap-3 min-w-0">
                        <div className="flex items-center gap-3 min-w-0 flex-1">
                            <IconBadge 
                                icon={currentStatus.startsWith('Réception confirmée') ? CheckCircleIcon : (currentStatus === 'Annulé' ? XIcon : PackageIcon)} 
                                variant={currentStatus.startsWith('Réception confirmée') ? 'success' : (currentStatus === 'Annulé' ? 'secondary' : 'info')} 
                                size="md" 
                                className="shrink-0" 
                            />
                            <div className="min-w-0 flex-1">
                                <h3 className={`font-black text-sm break-words leading-tight ${c.name ? 'text-slate-800' : 'text-slate-400 italic'}`}>
                                    {c.name || 'Projet sans nom'}
                                </h3>
                                <p className="text-[10px] text-slate-500 mt-0.5 break-words leading-tight flex items-center gap-1">
                                    <span className="font-bold text-slate-700">{owner?.name || c.clientName}</span> • Qté: {c.physicalPanels} • {currentStatus}
                                </p>
                            </div>
                        </div>
                        <div className="flex gap-1 shrink-0">
                            {c.a1PdfId && (
                                <Button 
                                    variant="secondary" 
                                    shape="square" 
                                    icon={EyeIcon} 
                                    onClick={(e) => { e.stopPropagation(); handleOpenModal('view_a1_pdf', c.id, false); }} 
                                    className="p-1.5 shadow-sm bg-white" 
                                    title="Voir le PDF" 
                                />
                            )}
                            {(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé') && (
                                <Button variant="ghost" shape="square" icon={Trash2Icon} onClick={(e) => { 
                                    e.stopPropagation();
                                    setConfirmConfig({
                                        title: "Masquer la commande",
                                        message: "Voulez-vous masquer définitivement cette commande de votre historique logistique ?",
                                        confirmText: "Masquer",
                                        isDestructive: true,
                                        onConfirm: async () => {
                                            handleCloseLayer();
                                            const newPhysicalPanels = currentStatus === 'Annulé' ? 0 : c.physicalPanels;
                                            const newShippingStatus = currentStatus === 'Annulé' ? '' : 'Archivé';
                                            
                                            const d = await safeFetch('panneaux', {
                                                body: { 
                                                    id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: newPhysicalPanels, 
                                                    details: { ...c, shipping_status: newShippingStatus, physicalPanels: newPhysicalPanels } 
                                                },
                                                setLoading: setIsSaving,
                                                successMessage: "Commande masquée avec succès."
                                            });
                                            
                                            if (!isMounted.current) return; // SÉCURITÉ
                                            
                                            if (d && refreshData) refreshData();
                                            setConfirmConfig(null);
                                        },
                                        onCancel: () => { setConfirmConfig(null); handleCloseLayer(); }
                                    });
                                    handleOpenDialog('confirm', c.id, false);
                                }} disabled={isSaving} className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 border-none shadow-none" title="Masquer de l'historique" />
                            )}
                        </div>
                    </div>
                </DataCard>

                {activeDialog === 'confirm' && dialogId === c.id && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} />}
                
                {activeModal === 'view_a1_pdf' && targetId === c.id && UniversalViewer && (
                    <UniversalViewer 
                        fileUrl={`${window.pano_CONFIG.apiBaseUrl}file/download&type=pdf&id=${c.a1PdfId}`}
                        fileType="pdf"
                        fileName={`Maquette ${c.name || 'Projet'}`}
                        positionClass="fixed"
                        useSafePdfMode={false}
                        onClose={handleCloseLayer}
                    />
                )}
            </>
        );
    }

    // ------------------------------------------------------------------------
    // Rendu : Mode Standard (Cartes complètes pour l'action requise / en cours)
    // ------------------------------------------------------------------------
    
    return (
        <>
            <DataCard variant={variant} className="min-w-0 w-full p-4 relative group flex flex-col h-full">
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); toggleDashboardPin && toggleDashboardPin('deliveries', c.id, e); }} 
                    className={`absolute top-2 right-2 z-20 p-1 cursor-pointer transition-all duration-200 ${isPinned ? 'text-amber-500 opacity-100 hover:scale-110' : 'text-slate-300 opacity-0 group-hover:opacity-100 hover:text-slate-500 hover:scale-110'}`}
                    style={{ transform: 'rotate(30deg)' }}
                    title={isPinned ? "Désépingler" : "Épingler au tableau de bord"}
                >
                    <PinIcon size={18} filled={isPinned} />
                </div>

                <div className="flex justify-between items-start gap-3 mb-2 min-w-0">
                    <div className="min-w-0 flex-1">
                        <h3 className={`font-black text-lg break-words leading-tight ${c.name ? 'text-slate-800' : 'text-slate-400 italic'}`}>{c.name || 'Projet sans nom'}</h3>
                        
                        {(owner?.name || c.clientName) && (
                            <p className="text-sm font-bold text-emerald-700 break-words leading-tight mt-1">{owner ? owner.name : c.clientName}</p>
                        )}
                        
                        {(c.shippingAddress || c.location) && (
                            <p className="text-xs text-slate-500 mt-1 flex items-start gap-1">
                                <PackageIcon size={14} className="shrink-0 mt-0.5 text-slate-400"/> 
                                <span className="break-words leading-tight">{c.shippingAddress || c.location}</span>
                            </p>
                        )}
                    </div>
                    <div className="flex flex-col items-end gap-2 shrink-0">
                        <div className="shrink-0 text-center bg-white p-2 rounded-xl border border-slate-200 shadow-sm min-w-[60px] mt-1">
                            <span className="text-xl font-black text-slate-800 leading-none">{c.physicalPanels}</span>
                            <span className="block text-[9px] uppercase tracking-widest text-slate-400 font-bold mt-1">Qté</span>
                        </div>
                    </div>
                </div>
                
                <div className="pt-2.5 border-t border-slate-200 flex items-center justify-center min-w-0">
                    <StatusBadge status={currentStatus} className="scale-90 shrink-0" />
                </div>
                
                {/* BLOC ACTIONS / CONTENU */}
                <div className="mt-auto">
                    {/* Gestion PDF (seulement si la commande n'est pas clôturée) */}
                    {!(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé') && (
                        <div className="pt-2.5 border-t border-slate-200 min-w-0">
                            <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-2 break-words">Maquette A1 pour impression</span>
                            
                            {c.a1PdfId ? (
                                <div className="flex flex-col gap-2 min-w-0">
                                    <div className="flex gap-2 min-w-0">
                                        <Button variant="secondary" onClick={() => handleOpenModal('view_a1_pdf', c.id, false)} className="flex-1 py-2 text-xs justify-center shadow-sm bg-white" icon={EyeIcon}>Voir le PDF</Button>
                                        {canModifyMaquette && (
                                            <Button variant="danger" shape="round" icon={Trash2Icon} onClick={handleA1Delete} disabled={isSaving} className="p-2 shadow-none shrink-0" title="Retirer" />
                                        )}
                                    </div>
                                    {canModifyMaquette && (
                                        <label className="flex items-center justify-center gap-2 bg-white border border-slate-200 text-slate-700 hover:bg-slate-100 hover:border-slate-300 py-2 rounded-xl text-xs font-bold cursor-pointer transition shadow-sm mt-1">
                                            <UploadIcon size={14} className="shrink-0"/> <span className="break-words text-center">Proposer une nouvelle version</span>
                                            <input type="file" accept="application/pdf" className="hidden" onChange={(e) => {
                                                const file = e.target.files[0];
                                                if(!file) return;
                                                setManualUploadData({ file: file, message: '' });
                                                handleOpenDialog('manual_upload_message', c.id, false);
                                                e.target.value = null;
                                            }} disabled={isSaving} />
                                        </label>
                                    )}
                                </div>
                            ) : (
                                <div className="flex flex-col gap-2 min-w-0">
                                    {canModifyMaquette ? (
                                        <>
                                            <div className="flex gap-2 min-w-0">
                                                <Button variant="secondary" icon={DownloadIcon} onClick={async () => {
                                                    const blob = await window.pano_generateA1PDF(c);
                                                    const hash = await computeFileHash(blob);
                                                    const link = document.createElement('a'); 
                                                    link.href = URL.createObjectURL(blob); 
                                                    link.download = `A1_${c.id}_${hash}.pdf`; 
                                                    link.click();
                                                    if (!hasBeenControlled) setHasBeenControlled(true);
                                                }} disabled={isSaving} className="py-2 text-xs flex-1 justify-center bg-white shadow-sm">
                                                    Contrôler
                                                </Button>
                                                
                                                <Button variant="success" icon={CheckCircleIcon} onClick={(e) => {
                                                    e.preventDefault(); e.stopPropagation();
                                                    
                                                    setConfirmConfig({
                                                        title: "Validation de la maquette", 
                                                        message: "Valider ce PDF contrôlé et passer à la commande ?", 
                                                        confirmText: "Valider",
                                                        onConfirm: async () => {
                                                            handleCloseLayer();
                                                            try {
                                                                const blob = await window.pano_generateA1PDF(c);
                                                                const hash = await computeFileHash(blob);
                                                                const file = new File([blob], `A1_${c.id}_${hash}.pdf`, { type: 'application/pdf' });
                                                                const idObj = await window.pano_uploadFile(file, 'pdf', null, false, false, c.clientName, c.id);
                                                                const actualId = idObj.id || idObj;
                                                                
                                                                const d1 = await safeFetch('panneaux', { 
                                                                    body: { 
                                                                        id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, 
                                                                        details: { ...c, a1PdfId: actualId, a1PdfHash: hash }, a1PdfId: actualId
                                                                    } 
                                                                });
                                                                if (!isMounted.current) return;
                                                                
                                                                const d2 = await safeFetch('panneaux/shipping', { 
                                                                    body: { id: c.id, shipping_status: "En attente de commande au fournisseur" }, 
                                                                    setLoading: setIsSaving, 
                                                                    successMessage: "Maquette validée !" 
                                                                });
                                                                if (!isMounted.current) return;
                                                                
                                                                if (d2 && refreshData) refreshData(); 
                                                            } catch (err) {
                                                                if (window.pano_showToast) window.pano_showToast(err.message || "Erreur lors de la validation", "error");
                                                            } finally { 
                                                                if (isMounted.current) setConfirmConfig(null); 
                                                            }
                                                        }
                                                    });
                                                    handleOpenDialog('confirm', c.id, false);
                                                }} disabled={isSaving || !hasBeenControlled} className="py-2 text-xs flex-1 justify-center shadow-md">
                                                    Valider
                                                </Button>
                                            </div>
                                            <label className="flex items-center justify-center gap-2 bg-white border border-slate-200 text-slate-700 hover:bg-slate-100 hover:border-slate-300 py-2 rounded-xl text-xs font-bold cursor-pointer transition shadow-sm mt-1">
                                                <UploadIcon size={14} className="shrink-0"/> <span className="break-words text-center">Attacher un fichier manuellement</span>
                                                <input type="file" accept="application/pdf" className="hidden" onChange={(e) => {
                                                    const file = e.target.files[0];
                                                    if(!file) return;
                                                    setManualUploadData({ file: file, message: '' });
                                                    handleOpenDialog('manual_upload_message', c.id, false);
                                                    e.target.value = null;
                                                }} disabled={isSaving} />
                                            </label>
                                        </>
                                    ) : (
                                        <div className="p-3 bg-red-50 text-red-800 text-xs rounded-xl border border-red-200 flex items-center gap-2 min-w-0">
                                            {AlertTriangleIcon && <AlertTriangleIcon size={14} className="shrink-0"/>} <span className="break-words">Maquette indisponible (Anomalie)</span>
                                        </div>
                                    )}
                                </div>
                            )}

                            <div className="pt-2.5 mt-2 flex flex-col gap-1 min-w-0">
                                <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold break-words">Nom du fichier</span>
                                <span className="text-xs font-bold text-slate-700 break-all block min-w-0" title={c.a1PdfId ? pdfFileName : 'Aucun'}>
                                    {c.a1PdfId ? pdfFileName : <span className="italic text-slate-400">Aucun fichier joint</span>}
                                </span>
                            </div>
                        </div>
                    )}

                    <div className="pt-2.5 border-t border-slate-200 mt-3 min-w-0">
                        {currentStatus === 'Annulé' && (
                            <div className="text-center bg-slate-100 text-slate-500 p-3 rounded-xl border border-slate-200 mb-3 min-w-0">
                                <XIcon size={20} className="mx-auto mb-1 shrink-0" />
                                <p className="text-xs font-bold uppercase tracking-widest break-words">Commande Annulée</p>
                            </div>
                        )}

                        {currentStatus === 'Attente validation client' && (
                            <div className="text-center bg-amber-50 text-amber-700 p-3 rounded-xl border border-amber-200 mb-3 min-w-0">
                                <p className="text-xs font-bold break-words">En attente de la validation du client</p>
                            </div>
                        )}

                        {currentStatus === 'Maquette refusée' && (
                            <div className="text-center bg-red-50 text-red-700 p-3 rounded-xl border border-red-200 mb-3 min-w-0">
                                {AlertTriangleIcon && <AlertTriangleIcon size={16} className="mx-auto mb-1 shrink-0" />}
                                <p className="text-xs font-bold break-words">Veuillez proposer une nouvelle maquette</p>
                            </div>
                        )}

                        {currentStatus === 'En attente de validation' && c.a1PdfId && (
                            <Button variant="successSolid" icon={CheckCircleIcon} onClick={() => updateShippingStatus("En attente de commande au fournisseur")} disabled={isSaving} className="w-full py-2.5 text-sm justify-center uppercase tracking-widest mb-3 shadow-md text-center">
                                Valider la maquette
                            </Button>
                        )}

                        {currentStatus === 'En attente de commande au fournisseur' && (
                            <Button variant="warningSolid" icon={PackageIcon} onClick={() => updateShippingStatus("En attente d'impression")} disabled={isSaving || !c.a1PdfId} className="w-full py-2.5 text-sm justify-center uppercase tracking-widest mb-3 shadow-md text-center">
                                Commander au fournisseur
                            </Button>
                        )}

                        {currentStatus === "En attente d'impression" && (
                            <Button variant="primary" icon={PackageIcon} onClick={() => { setTrackingData({number: c.tracking_number || '', link: c.tracking_link || ''}); handleOpenDialog('shipping', c.id, false); }} disabled={isSaving || !c.a1PdfId} className="w-full py-2.5 text-sm justify-center uppercase tracking-widest mb-3 shadow-md text-center">
                                Expédier la commande
                            </Button>
                        )}

                        {currentStatus === 'Expédié' && (
                            <div className="text-center bg-white p-3 rounded-xl border border-slate-200 shadow-inner mb-3 min-w-0">
                                <div className="flex items-center justify-center gap-2 min-w-0">
                                    {c.tracking_number ? (
                                        <p className="text-sm font-mono text-blue-600 font-bold break-all select-all" title="Numéro de suivi">{c.tracking_number}</p>
                                    ) : (
                                        <p className="text-xs font-bold text-slate-500 uppercase tracking-widest break-words">En cours de livraison</p>
                                    )}
                                    {c.tracking_link && (
                                        <Button variant="info" shape="square" icon={ExternalLinkIcon} onClick={() => window.open(c.tracking_link.startsWith('http') ? c.tracking_link : `https://${c.tracking_link}`, '_blank')} className="p-1.5 shadow-none shrink-0" title="Suivre mon colis en ligne" />
                                    )}
                                    <Button variant="ghost" shape="square" icon={EditIcon} onClick={() => { setTrackingData({number: c.tracking_number || '', link: c.tracking_link || ''}); handleOpenDialog('shipping', c.id, false); }} className="p-1.5 shadow-none shrink-0 text-slate-500 hover:text-slate-800 hover:bg-slate-100 border-none" title="Modifier le suivi" />
                                </div>

                                {isForceDeliveryAvailable && (
                                    <Button variant="outline" icon={CheckCircleIcon} onClick={() => updateShippingStatus("Réception confirmée par le suivi")} disabled={isSaving} className="mt-3 w-full py-2 text-[10px] uppercase justify-center text-slate-500 border-dashed hover:bg-emerald-50 hover:text-emerald-700 hover:border-emerald-200 text-center" title="Le colis est indiqué comme expédié depuis longtemps. Forcer le statut à réceptionné.">
                                        Forcer Livraison ({limitShippingForce}j+)
                                    </Button>
                                )}
                            </div>
                        )}

                        {currentStatus.startsWith('Réception confirmée') && (
                            <div className="text-center bg-emerald-50 text-emerald-700 p-3 rounded-xl border border-emerald-200 mb-3 min-w-0">
                                <CheckCircleIcon size={20} className="mx-auto mb-1 shrink-0" />
                                <p className="text-xs font-bold uppercase tracking-widest break-words">Colis Livré</p>
                            </div>
                        )}

                        {!(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé') && (
                            <div className="border-t border-slate-100 pt-3 min-w-0">
                                <Button variant="ghost" icon={Trash2Icon} onClick={() => { setAdminPwd(''); handleOpenDialog('cancel_order', c.id, false); }} disabled={isSaving} className="w-full py-1.5 text-[10px] justify-center text-red-400 hover:text-red-600 hover:bg-red-50 shadow-none border-none text-center">
                                    Annuler la commande et rembourser
                                </Button>
                            </div>
                        )}
                    </div>
                </div>
            </DataCard>

            {/* Modales Encapsulées Zéro-Dette */}
            {activeModal === 'delivery_confirm' && targetId === c.id && Modal && (
                <Modal title="Confirmation de réception" type="success" onClose={handleCloseLayer} preventClose={isSaving} actions={(close) => (
                    <>
                        <Button variant="secondary" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                        <Button variant="primary" onClick={() => { handleConfirmDelivery(); }} disabled={isSaving} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs text-center">Oui, j'ai reçu mon colis</Button>
                    </>
                )}>
                    <div className="space-y-4 min-w-0">
                        <div className="bg-emerald-50 text-emerald-800 p-5 rounded-2xl border border-emerald-200 text-sm min-w-0"><p className="font-black break-words leading-tight">Confirmez-vous la bonne réception de la commande logistique associée à ce panneau ?</p></div>
                    </div>
                </Modal>
            )}

            {activeModal === 'reject_a1' && targetId === c.id && Modal && (
                <Modal title="Refuser la maquette" onClose={handleCloseLayer} preventClose={isSaving} actions={(close) => (
                    <>
                        <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                        <Button type="submit" form={`reject-a1-form-${c.id}`} variant="dangerSolid" disabled={isSaving || !rejectReason.trim()} className="flex-[2] py-3 uppercase tracking-widest justify-center text-xs shadow-md text-center">Confirmer le refus</Button>
                    </>
                )}>
                    <form id={`reject-a1-form-${c.id}`} onSubmit={async (e) => {
                        e.preventDefault();
                        const d = await safeFetch('panneaux/client_validate_a1', { body: { id: c.id, action: 'reject', reason: rejectReason }, setLoading: setIsSaving, successMessage: "Refus transmis au support technique." });
                        if (!isMounted.current) return; // SÉCURITÉ
                        if (d) { if (refreshData) refreshData(); handleCloseLayer(); }
                    }} className="space-y-4 min-w-0">
                        {FormTextarea && <FormTextarea label="Motif du refus (Explications) *" required rows={4} value={rejectReason} onChange={e => setRejectReason(e.target.value)} placeholder="Ex: Le numéro de permis est incorrect, la couleur de la bordure ne correspond pas..." autoFocus className="min-w-0 w-full" />}
                    </form>
                </Modal>
            )}

            {activeDialog === 'manual_upload_message' && dialogId === c.id && manualUploadData && Modal && (
                <Modal title="Demande de validation au client" onClose={() => { setManualUploadData(null); handleCloseLayer(); }} preventClose={isSaving} actions={(close) => (
                    <>
                        <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                        <Button type="submit" form={`manual-upload-form-${c.id}`} variant="primary" disabled={isSaving || !manualUploadData.message.trim()} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs text-center">Envoyer la demande</Button>
                    </>
                )}>
                    <form id={`manual-upload-form-${c.id}`} onSubmit={async (e) => {
                        e.preventDefault();
                        setIsSaving(true);
                        try {
                            const { file, message } = manualUploadData;
                            const hash_str = await computeFileHash(file);
                            if (!isMounted.current) return; // SÉCURITÉ
                            
                            const idObj = await window.pano_uploadFile(file, 'pdf', null, false, false, c.clientName, c.id);
                            if (!isMounted.current) return; // SÉCURITÉ
                            const actualId = idObj.id || idObj;
                            
                            if (actualId) {
                                const d1 = await safeFetch('panneaux', { body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, a1PdfHash: hash_str } } });
                                if (!isMounted.current) return; // SÉCURITÉ
                                const d2 = await safeFetch('panneaux/manual_a1', { body: { id: c.id, a1PdfId: actualId, message: message }, successMessage: "Fichier envoyé." });
                                if (!isMounted.current) return; // SÉCURITÉ
                                if (d2) { if (refreshData) refreshData(); setManualUploadData(null); handleCloseLayer(); }
                            }
                        } catch (err) {
                            if (!isMounted.current) return; // SÉCURITÉ
                            if (window.pano_showToast) window.pano_showToast(err.message || "Erreur d'envoi", "error");
                        } finally { if (isMounted.current) setIsSaving(false); }
                    }} className="space-y-4 min-w-0">
                        <div className="bg-amber-50 text-amber-800 p-3 rounded-xl text-sm mb-4 border border-amber-200 min-w-0">
                            <p className="font-bold break-words leading-tight">Vous allez soumettre un PDF modifié au client.</p>
                            <p className="text-xs mt-1 break-words leading-relaxed">Le client devra valider formellement ce fichier depuis son espace avant de passer commande.</p>
                        </div>
                        {FormTextarea && <FormTextarea label="Message pour le client" required rows={4} value={manualUploadData.message} onChange={e => setManualUploadData({...manualUploadData, message: e.target.value})} placeholder="Ex: Bonjour, nous avons ajusté..." className="min-w-0 w-full" />}
                    </form>
                </Modal>
            )}

            {activeDialog === 'cancel_order' && dialogId === c.id && Modal && (
                <Modal title="Annuler et rembourser" onClose={handleCloseLayer} preventClose={isSaving} actions={(close) => (
                    <>
                        <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                        <Button type="submit" form={`cancel-order-form-${c.id}`} variant="dangerSolid" disabled={isSaving || !adminPwd} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs text-center">Confirmer l'annulation</Button>
                    </>
                )}>
                    <form id={`cancel-order-form-${c.id}`} onSubmit={async (e) => {
                        e.preventDefault();
                        const d = await safeFetch('panneaux/cancel_order', { body: { id: c.id, password: adminPwd }, setLoading: setIsSaving, successMessage: "Commande annulée." });
                        if (!isMounted.current) return; // SÉCURITÉ
                        if (d) { if (refreshData) refreshData(); handleCloseLayer(); }
                    }} className="space-y-4 min-w-0">
                        <div className="bg-red-50 text-red-800 p-3 rounded-xl text-sm mb-4 border border-red-200 min-w-0">
                            <p className="font-bold break-words leading-tight">Vous allez annuler cette commande logistique.</p>
                            <p className="text-xs mt-1 break-words leading-relaxed">Le montant sera automatiquement recrédité (Avoir) au client.</p>
                        </div>
                        {FormInput && <FormInput label="Mot de passe administrateur" type="password" required value={adminPwd} onChange={e => setAdminPwd(e.target.value)} className="min-w-0 w-full" />}
                    </form>
                </Modal>
            )}

            {activeDialog === 'shipping' && dialogId === c.id && Modal && (
                <Modal title={c.shipping_status === 'Expédié' ? "Mise à jour du suivi" : "Expédition de la commande"} onClose={handleCloseLayer} preventClose={isSaving} actions={(close) => (
                    <>
                        <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center text-xs">Annuler</Button>
                        <Button type="submit" form={`shipping-form-${c.id}`} variant="primary" disabled={isSaving} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs text-center">Confirmer</Button>
                    </>
                )}>
                    <form id={`shipping-form-${c.id}`} onSubmit={async (e) => {
                        e.preventDefault();
                        let link = trackingData.link.trim();
                        if (link && !/^https?:\/\//i.test(link)) link = 'https://' + link;
                        const d = await safeFetch('panneaux/shipping', { body: { id: c.id, shipping_status: 'Expédié', tracking_number: trackingData.number, tracking_link: link }, setLoading: setIsSaving, successMessage: "Suivi mis à jour !" });
                        if (!isMounted.current) return; // SÉCURITÉ
                        if(d) { if(refreshData) refreshData(); handleCloseLayer(); }
                    }} className="space-y-4 min-w-0">
                        {FormInput && <FormInput label="Numéro de suivi (facultatif)" type="text" value={trackingData.number} onChange={e => setTrackingData({...trackingData, number: e.target.value})} placeholder="Ex: 8J009088..." className="min-w-0 w-full" />}
                        {FormInput && <FormInput label="Lien web du suivi (facultatif)" type="text" value={trackingData.link} onChange={e => setTrackingData({...trackingData, link: e.target.value})} placeholder="www.transporteur.com/suivi/..." className="min-w-0 w-full" />}
                    </form>
                </Modal>
            )}

            {activeDialog === 'confirm' && dialogId === c.id && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} />}
            
            {activeModal === 'view_a1_pdf' && targetId === c.id && UniversalViewer && (
                <UniversalViewer 
                    fileUrl={`${window.pano_CONFIG.apiBaseUrl}file/download&type=pdf&id=${c.a1PdfId}`}
                    fileType="pdf"
                    fileName={`Maquette ${c.name || 'Projet'}`}
                    positionClass="fixed"
                    useSafePdfMode={false}
                    onClose={handleCloseLayer}
                />
            )}
        </>
    );
};

// ============================================================================
// 2. ONGLET PRINCIPAL LOGISTIQUE ADMIN
// ============================================================================
window.pano_AdminLogisticsTab = ({ data, refreshData, adminOpts, toggleDashboardPin }) => {
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

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

    // CORRECTION ZÉRO-DETTE : Retrait du <UniversalViewer> et du setPreviewConfig parent
    const { SearchBar, EmptySearch, PaginationFooter, CardGrid, AdminLogisticsCard } = window.pano_getComponents();
    const { PackageIcon, AlertTriangleIcon, PinIcon, LoaderIcon, CheckCircleIcon, TruckIcon } = window.pano_getIcons();

    const deliveries = (data.panneaux || []).filter(p => p.physicalPanels > 0 && p.status !== 'Brouillon' && p.id !== 'demo-panneau' && p.shipping_status !== 'Archivé');
    const clients = data.clients || [];

    const { visibleCount, setVisibleCount, searchQuery, setSearchQuery, filteredData: filteredDeliveries } = window.pano_useSearchAndPagination(deliveries, (p, q) => {
        const n = window.pano_normalizeString;
        const owner = clients.find(cl => cl.id === p.clientName);
        const ownerName = n(owner ? owner.name : p.clientName);
        return n(p.name).includes(q) || ownerName.includes(q) || n(p.tracking_number).includes(q) || n(p.shipping_status).includes(q) || n(p.location).includes(q) || n(p.shippingAddress).includes(q);
    });

    const pinnedIds = adminOpts?.deliveries || [];
    
    const attentionDeliveries = [];
    const pinnedDeliveries = [];
    const activeDeliveries = [];
    const otherDeliveries = [];

    // Dynamisation des règles métier
    const limitShippingForce = parseInt(data.settings?.limit_shipping_force || 90, 10);
    const MAX_HISTORY = parseInt(data.settings?.limit_history_max || 500, 10);

    // Répartition des commandes en 4 catégories pour l'admin
    filteredDeliveries.forEach(c => {
        const currentStatus = c.shipping_status || 'En attente de validation';
        
        let isForceDeliveryAvailable = false;
        if (currentStatus === 'Expédié' && c.updated_at) {
            const updateTime = new Date(c.updated_at.replace(' ', 'T')).getTime();
            const daysSince = (Date.now() - updateTime) / (1000 * 3600 * 24);
            if (daysSince > limitShippingForce) isForceDeliveryAvailable = true;
        }

        const needsAttention = ['En attente de validation', 'Maquette refusée', 'En attente de commande au fournisseur', "En attente d'impression"].includes(currentStatus) || isForceDeliveryAvailable;
        const isPinned = pinnedIds.includes(c.id);
        const isActive = !needsAttention && !(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé');

        // Distribution des props du routeur
        const cardProps = {
            delivery: c, clients, isPinned, toggleDashboardPin, refreshData, limitShippingForce,
            openModal, openDialog, closeCurrentLayer, activeModal, activeDialog, targetId, dialogId
        };

        if (needsAttention) {
            attentionDeliveries.push(cardProps);
        } else if (isPinned) {
            pinnedDeliveries.push(cardProps);
        } else if (isActive) {
            activeDeliveries.push(cardProps);
        } else {
            otherDeliveries.push(cardProps);
        }
    });

    const hasMoreHistory = otherDeliveries.length > MAX_HISTORY;
    const historyToDisplay = hasMoreHistory ? otherDeliveries.slice(0, MAX_HISTORY) : otherDeliveries;
    const displayedOtherDeliveries = historyToDisplay.slice(0, visibleCount);

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 min-w-0 w-full">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div className="min-w-0"><h1 className="text-3xl font-black text-slate-800 break-words">Logistique</h1></div>
                
                {deliveries.length > 0 && SearchBar && (
                    <div className="w-full md:w-auto flex-1 flex justify-end gap-2 shrink-0">
                        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} placeholder="Rechercher (Projet, Suivi, Statut)..." />
                    </div>
                )}
            </div>
            
            {deliveries.length === 0 ? (
                <div className="text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed min-w-0 w-full">
                    <PackageIcon size={48} className="mx-auto text-slate-300 mb-4" />
                    <h3 className="text-lg font-black text-slate-700 break-words">Aucune livraison</h3>
                </div>
            ) : filteredDeliveries.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* 10.1 - Priorités */}
                    {attentionDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <AlertTriangleIcon size={20} className="text-amber-500" /> Action requise
                            </h2>
                            <CardGrid minWidth="300px">
                                {attentionDeliveries.map(props => <AdminLogisticsCard key={`att_${props.delivery.id}`} {...props} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* 10.2 - Favoris */}
                    {pinnedDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <PinIcon size={20} className="text-blue-600" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="300px">
                                {pinnedDeliveries.map(props => <AdminLogisticsCard key={`pin_${props.delivery.id}`} {...props} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* 10.3 - Commandes en cours */}
                    {activeDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <TruckIcon size={20} className="text-blue-600" /> Commandes en cours
                            </h2>
                            <CardGrid minWidth="300px">
                                {activeDeliveries.map(props => <AdminLogisticsCard key={`act_${props.delivery.id}`} {...props} />)}
                            </CardGrid>
                        </div>
                    )}

                    {/* 10.4 - Historique (Compacté) */}
                    {otherDeliveries.length > 0 && (
                        <div className="space-y-4 min-w-0 w-full">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <CheckCircleIcon size={20} className="text-slate-500" /> Historique des commandes
                            </h2>
                            
                            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 min-w-0">
                                {displayedOtherDeliveries.map(props => <AdminLogisticsCard key={`oth_${props.delivery.id}`} {...props} isMini={true} />)}
                            </div>

                            {hasMoreHistory && visibleCount >= MAX_HISTORY && (
                                <div className="p-5 mt-4 bg-blue-50 border border-blue-200 rounded-xl text-center shadow-inner min-w-0">
                                    <p className="text-sm text-blue-900 font-black mb-1 break-words">L'affichage est limité aux {MAX_HISTORY} résultats les plus récents pour garantir les performances.</p>
                                    <p className="text-xs text-blue-700 font-medium break-words leading-relaxed">Veuillez utiliser la barre de recherche ci-dessus pour affiner les résultats et trouver des commandes plus anciennes.</p>
                                </div>
                            )}

                            {PaginationFooter && !hasMoreHistory && <PaginationFooter visibleCount={visibleCount} setVisibleCount={setVisibleCount} totalCount={otherDeliveries.length} itemName="commandes" />}
                            {PaginationFooter && hasMoreHistory && visibleCount < MAX_HISTORY && <PaginationFooter visibleCount={visibleCount} setVisibleCount={setVisibleCount} totalCount={MAX_HISTORY} itemName="commandes" />}
                        </div>
                    )}
                </>
            )}
        </div>
    );
};

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