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

// ============================================================================
// 1. COMPOSANT CARTE ISOLÉ ET RÉUTILISABLE CLIENT (LIVRAISONS)
// ============================================================================
window.pano_ClientDeliveryCard = ({ 
    delivery: c, 
    isPinned, 
    toggleDashboardPin, 
    refreshData, 
    isMini = false,
    limitShippingForce = 90,
    openModal, 
    closeCurrentLayer, 
    openDialog, 
    activeDialog, 
    dialogId, 
    activeModal, 
    targetId
}) => {
    const { useState } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    const [isSaving, setIsSaving] = useState(false);
    const [rejectReason, setRejectReason] = useState('');
    const [confirmConfig, setConfirmConfig] = useState(null);

    const {
        PackageIcon, CheckCircleIcon, ExternalLinkIcon, LoaderIcon, 
        AlertTriangleIcon, EyeIcon, XIcon, PinIcon, Trash2Icon
    } = window.pano_getIcons();

    const {
        Modal, StatusBadge, IconBadge, Button, DataCard, FormTextarea, ConfirmModal, UniversalViewer
    } = window.pano_getComponents();

    const currentStatus = c.shipping_status || 'En attente de validation';
    
    let variant = 'default';
    if (currentStatus === 'Attente validation client') variant = 'warning';
    if (currentStatus === 'Annulé') variant = 'slate';

    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É : Coupe-circuit
        
        if (d) { 
            if (refreshData) refreshData(); 
            closeCurrentLayer(); 
        }
    };

    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É : Coupe-circuit
        
        if (d && refreshData) refreshData();
    };

    // ------------------------------------------------------------------------
    // 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">Qté: {c.physicalPanels}</span> • {currentStatus}
                                </p>
                            </div>
                        </div>
                        <div className="flex gap-1 shrink-0">
                            {c.a1PdfId && (
                                <Button 
                                    variant="secondary" 
                                    shape="square" 
                                    icon={EyeIcon} 
                                    onClick={(e) => { e.stopPropagation(); openModal('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 () => {
                                            closeCurrentLayer();
                                            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); closeCurrentLayer(); }
                                    });
                                    openDialog('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={closeCurrentLayer}
                    />
                )}
            </>
        );
    }

    // ------------------------------------------------------------------------
    // Rendu : Mode Standard (Cartes complètes pour l'action requise / en cours)
    // ------------------------------------------------------------------------
    
    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;
    }

    return (
        <>
            <DataCard variant={variant} className="relative group p-4 min-w-0 flex flex-col h-full">
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); toggleDashboardPin && toggleDashboardPin('pinned_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="flex items-start 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' : (currentStatus === 'Attente validation client' ? 'warning' : 'info'))} 
                            size="lg" 
                            className="shrink-0" 
                        />
                        <div className="min-w-0 flex-1 pr-2">
                            <h3 className={`font-black text-base break-words leading-tight ${c.name ? 'text-slate-800' : 'text-slate-400 italic'}`}>
                                {c.name || 'Projet sans nom'}
                            </h3>
                            {(c.shippingAddress || c.location) && (
                                <p className="text-xs text-slate-500 mt-1 flex items-start gap-1">
                                    <PackageIcon size={12} className="shrink-0 mt-0.5 text-slate-400"/>
                                    <span className="break-words leading-tight">{c.shippingAddress || c.location}</span>
                                </p>
                            )}
                        </div>
                    </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-[50px] mt-1">
                            <span className="text-lg 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-100 mt-2 flex items-center justify-center min-w-0">
                    <StatusBadge status={currentStatus} className="scale-90 shrink-0" />
                </div>

                <div className="mt-auto">
                    {/* Bloc : Annulé */}
                    {currentStatus === 'Annulé' && (
                        <div className="text-center bg-slate-100 text-slate-500 p-3 rounded-xl border border-slate-200 mt-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>
                    )}

                    {/* Bloc : Attente validation client */}
                    {currentStatus === 'Attente validation client' && (
                        <div className="mt-3 pt-3 border-t border-slate-100 space-y-3" onClick={e => e.stopPropagation()}>
                            <div className="bg-amber-50 text-amber-800 p-3 rounded-xl border border-amber-200 text-xs">
                                <p className="font-bold flex items-center gap-1.5"><AlertTriangleIcon size={14}/> Maquette à valider</p>
                                <p className="mt-1.5 leading-relaxed break-words">Le support technique a généré une nouvelle maquette pour votre projet. Veuillez la contrôler et la valider formellement pour lancer l'impression.</p>
                            </div>
                            {c.a1PdfId && (
                                <Button variant="secondary" onClick={(e) => { e.stopPropagation(); openModal('view_a1_pdf', c.id, false); }} className="w-full py-2 bg-white text-xs justify-center shadow-sm" icon={EyeIcon}>Consulter le PDF</Button>
                            )}
                            <div className="flex gap-2">
                                <Button variant="danger" icon={XIcon} onClick={() => { setRejectReason(''); openModal('reject_a1', c.id); }} disabled={isSaving} className="flex-1 py-2 text-xs justify-center shadow-none bg-white border-none">Refuser</Button>
                                <Button variant="successSolid" icon={CheckCircleIcon} onClick={async () => {
                                    const d = await safeFetch('panneaux/client_validate_a1', { 
                                        body: { id: c.id, action: 'accept' }, 
                                        setLoading: setIsSaving, 
                                        successMessage: "Maquette validée !" 
                                    });
                                    if (!isMounted.current) return; // SÉCURITÉ
                                    if (d && refreshData) refreshData();
                                }} disabled={isSaving} className="flex-[2] py-2 text-xs justify-center shadow-md text-center">Valider l'impression</Button>
                            </div>
                        </div>
                    )}

                    {/* Bloc : Expédié */}
                    {currentStatus === 'Expédié' && (
                        <div className="mt-3 pt-3 border-t border-slate-100 space-y-3" onClick={e => e.stopPropagation()}>
                            <div className="text-center bg-white p-3 rounded-xl border border-slate-200 shadow-inner">
                                <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" 
                                        />
                                    )}
                                </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>
                            <Button variant="primary" icon={CheckCircleIcon} onClick={() => openModal('delivery_confirm', c.id)} disabled={isSaving} className="w-full py-2.5 text-xs uppercase tracking-widest justify-center shadow-md">Confirmer la réception</Button>
                        </div>
                    )}

                    {/* Bloc : Réception confirmée */}
                    {currentStatus.startsWith('Réception confirmée') && (
                        <div className="text-center bg-emerald-50 text-emerald-700 p-3 rounded-xl border border-emerald-200 mt-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>
                    )}

                    <div className="flex flex-wrap items-center justify-end gap-2 pt-3 border-t border-slate-100 mt-4 min-w-0">
                        {c.a1PdfId && currentStatus !== 'Attente validation client' && (
                            <Button 
                                variant="secondary" shape="square" icon={EyeIcon} 
                                onClick={(e) => { e.stopPropagation(); openModal('view_a1_pdf', c.id, false); }} 
                                className="p-2 shadow-sm bg-white" 
                                title="Voir la maquette A1"
                            />
                        )}
                        {currentStatus !== 'Annulé' && !currentStatus.startsWith('Réception confirmée') && currentStatus !== 'Expédié' && currentStatus !== 'Attente validation client' && (
                            <div className="text-xs text-slate-400 font-medium italic py-1">En cours de traitement par notre équipe...</div>
                        )}

                        {/* Actions de masquage */}
                        {(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé') && (
                            <Button variant="ghost" 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 () => {
                                        closeCurrentLayer();
                                        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); closeCurrentLayer(); }
                                });
                                openDialog('confirm', c.id, false);
                            }} disabled={isSaving} className="w-full mt-2 py-1.5 text-[10px] justify-center text-slate-400 hover:text-slate-600 hover:bg-slate-100 shadow-none border-none text-center">
                                Masquer de l'historique
                            </Button>
                        )}
                    </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={closeCurrentLayer} 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={closeCurrentLayer} 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(); closeCurrentLayer(); }
                    }} 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 === '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={closeCurrentLayer}
                />
            )}
        </>
    );
};

// ============================================================================
// 2. ONGLET PRINCIPAL LOGISTIQUE CLIENT
// ============================================================================
window.pano_ClientLivraisonsTab = ({ 
    data, 
    myClientData, 
    refreshData, 
    activeModal,
    activeDialog,
    targetId, 
    dialogId,
    openLocalModal, 
    openLocalDialog,
    closeCurrentLayer, 
    clientOpts, 
    toggleDashboardPin 
}) => {
    const { useState, useEffect } = React;
    
    // Icônes et Composants
    const { PackageIcon, AlertTriangleIcon, PinIcon, CheckCircleIcon, TruckIcon } = window.pano_getIcons();
    const { CardGrid, SearchBar, EmptySearch, PaginationFooter, ClientDeliveryCard } = window.pano_getComponents();

    // Données et filtrage
    const { visiblePanels } = window.pano_getPanelAccessRights 
        ? window.pano_getPanelAccessRights(data.panneaux || [], myClientData.id, myClientData.email_hash) 
        : { visiblePanels:[] };
    
    // Ne lister que les commandes de panneaux physiques (hors brouillons/archivés)
    const deliveries = visiblePanels.filter(c => c.physicalPanels > 0 && c.status !== 'Brouillon' && c.shipping_status !== 'Archivé');

    const { 
        searchQuery, setSearchQuery, 
        visibleCount, setVisibleCount, 
        filteredData: filteredDeliveries 
    } = window.pano_useSearchAndPagination(deliveries, (c, q) => {
        const n = window.pano_normalizeString;
        return n(c.name).includes(q) ||
               n(c.shippingAddress).includes(q) ||
               n(c.location).includes(q) ||
               n(c.tracking_number).includes(q) ||
               n(c.shipping_status).includes(q); 
    });

    const pinnedIds = clientOpts?.pinned_deliveries || [];

    const attentionDeliveries = [];
    const pinnedDeliveries = [];
    const activeDeliveries = [];
    const otherDeliveries = [];

    // LIMITES DYNAMIQUES
    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
    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 = currentStatus === 'Attente validation client' || isForceDeliveryAvailable;
        const isPinned = pinnedIds.includes(c.id);
        const isActive = !(currentStatus.startsWith('Réception confirmée') || currentStatus === 'Annulé');

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

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

    // Navigation URL Deep Linking
    useEffect(() => {
        const url = new URL(window.location);
        const confirmDelivery = url.searchParams.get('confirm_delivery');
        if (confirmDelivery) {
            url.searchParams.delete('confirm_delivery');
            window.history.replaceState(window.history.state || {}, '', url);
            if (openLocalModal) openLocalModal('delivery_confirm', confirmDelivery);
        }
    }, [openLocalModal]);

    // Rendu UI global
    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>
                    <h1 className="text-3xl font-black text-slate-800">Livraisons</h1>
                    <p className="text-slate-500 font-medium break-words leading-relaxed mt-1">Suivez l'état de vos commandes physiques.</p>
                </div>
                
                {deliveries.length > 0 && SearchBar && (
                    <div className="w-full sm:w-auto flex-1 flex justify-end gap-2">
                        <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">
                    <PackageIcon size={48} className="mx-auto text-slate-300 mb-4" />
                    <h3 className="text-lg font-black text-slate-700">Aucune livraison</h3>
                    <p className="text-sm text-slate-500 mt-2">Vous n'avez passé aucune commande de panneaux physiques.</p>
                </div>
            ) : filteredDeliveries.length === 0 ? (
                EmptySearch && <EmptySearch searchQuery={searchQuery} />
            ) : (
                <>
                    {/* 1. Priorités */}
                    {attentionDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <AlertTriangleIcon size={20} className="text-amber-500" /> Action requise
                            </h2>
                            <CardGrid minWidth="300px">
                                {ClientDeliveryCard && attentionDeliveries.map(c => (
                                    <ClientDeliveryCard 
                                        key={`att_${c.id}`} 
                                        delivery={c} 
                                        isPinned={pinnedIds.includes(c.id)} 
                                        toggleDashboardPin={toggleDashboardPin} 
                                        refreshData={refreshData} 
                                        limitShippingForce={limitShippingForce}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}
                            </CardGrid>
                        </div>
                    )}

                    {/* 2. Favoris */}
                    {pinnedDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <PinIcon size={20} className="text-blue-600" filled /> Favoris (Épinglés)
                            </h2>
                            <CardGrid minWidth="300px">
                                {ClientDeliveryCard && pinnedDeliveries.map(c => (
                                    <ClientDeliveryCard 
                                        key={`pin_${c.id}`} 
                                        delivery={c} 
                                        isPinned={pinnedIds.includes(c.id)} 
                                        toggleDashboardPin={toggleDashboardPin} 
                                        refreshData={refreshData} 
                                        limitShippingForce={limitShippingForce}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}
                            </CardGrid>
                        </div>
                    )}

                    {/* 3. Commandes en cours */}
                    {activeDeliveries.length > 0 && (
                        <div className="mb-10 space-y-4">
                            <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">
                                {ClientDeliveryCard && activeDeliveries.map(c => (
                                    <ClientDeliveryCard 
                                        key={`act_${c.id}`} 
                                        delivery={c} 
                                        isPinned={pinnedIds.includes(c.id)} 
                                        toggleDashboardPin={toggleDashboardPin} 
                                        refreshData={refreshData} 
                                        limitShippingForce={limitShippingForce}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}
                            </CardGrid>
                        </div>
                    )}

                    {/* 4. Historique (Compacté) */}
                    {otherDeliveries.length > 0 && (
                        <div className="space-y-4">
                            <h2 className="text-lg font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                                <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">
                                {ClientDeliveryCard && displayedOtherDeliveries.map(c => (
                                    <ClientDeliveryCard 
                                        key={`oth_${c.id}`} 
                                        delivery={c} 
                                        isPinned={pinnedIds.includes(c.id)} 
                                        toggleDashboardPin={toggleDashboardPin} 
                                        refreshData={refreshData} 
                                        isMini={true} 
                                        limitShippingForce={limitShippingForce}
                                        openModal={openLocalModal}
                                        openDialog={openLocalDialog}
                                        closeCurrentLayer={closeCurrentLayer}
                                        activeModal={activeModal}
                                        activeDialog={activeDialog}
                                        targetId={targetId}
                                        dialogId={dialogId}
                                    />
                                ))}
                            </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/clients/_clients_livraisons.jsx] */