/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Client - Onglets : Mes Panneaux et Livraisons
 * =========================================================================
 */

// =========================================================================
// 1. ONGLET : MES PANNEAUX
// =========================================================================

window.ClientPanelsTab = ({ 
    data, 
    myClientData, 
    refreshData, 
    showToast, 
    setActiveTab, 
    setManagingPanneau, 
    setValidationErrors, 
    setModalStep, 
    setIsModalOpen, 
    setPreviewPanneau, 
    setPanelTeamModal, 
    setArchiveConfig, 
    handleDeletePanelClick, 
    setConfirmDialog 
}) => {
    const { useState } = React;
    const [isSaving, setIsSaving] = useState(false);

    // RÉCUPÉRATION SÉCURISÉE DES ICÔNES ET COMPOSANTS
    const BuildingIcon = window.BuildingIcon || (() => null);
    const PlusIcon = window.PlusIcon || (() => null);
    const AlertTriangleIcon = window.AlertTriangleIcon || (() => null);
    const UsersIcon = window.UsersIcon || (() => null);
    const CheckCircleIcon = window.CheckCircleIcon || (() => null);
    const Trash2Icon = window.Trash2Icon || (() => null);
    const MessageSquareIcon = window.MessageSquareIcon || (() => null);
    const EyeIcon = window.EyeIcon || (() => null);
    const QrCodeIcon = window.QrCodeIcon || (() => null);
    const Share2Icon = window.Share2Icon || (() => null);
    const LockIcon = window.LockIcon || (() => null);
    const EditIcon = window.EditIcon || (() => null);
    const ArchiveIcon = window.ArchiveIcon || (() => null);
    const PowerIcon = window.PowerIcon || (() => null);
    const CopyIcon = window.CopyIcon || (() => null);
    const XIcon = window.XIcon || (() => null);

    const StatusBadge = window.StatusBadge || (({status}) => <span className="text-xs font-bold">{status}</span>);
    
    // Fallback robuste avec restauration de la soumission native au clavier
    const Button = window.Button || (({children, onClick, className, disabled, title, icon: Icon, type}) => {
        const handleAction = (e) => {
            if (disabled) return;
            if (onClick) onClick(e);
            if (type === 'submit') {
                const form = e.currentTarget.closest('form');
                if (form && typeof form.requestSubmit === 'function') form.requestSubmit();
            }
        };
        return (
            <div 
                role="button" 
                tabIndex={disabled ? -1 : 0} 
                onClick={handleAction} 
                onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleAction(e); } }}
                className={`flex items-center justify-center gap-2 cursor-pointer transition ${className || ''} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`} 
                title={title}
            >
                {Icon && <Icon size={16} className="shrink-0" />}
                {children}
                {type === 'submit' && <input type="submit" className="hidden" disabled={disabled} tabIndex="-1" />}
            </div>
        );
    });

    // FACTORISATION : Logique métier d'accès aux panneaux
    const { pendingInvites, visiblePanels } = window.getPanelAccessRights 
        ? window.getPanelAccessRights(data.panneaux || [], myClientData.id) 
        : { pendingInvites:[], visiblePanels:[] };

    const isSuspended = myClientData.paymentStatus === 'suspended';
    const purchasesAllowed = data.settings?.allow_new_purchases !== '0';

    const respondToInvite = async (panneauId, action) => {
        const d = await window.apiFetch('panneaux/collaborators/respond', {
            body: { panneau_id: panneauId, action },
            setLoading: setIsSaving,
            successMessage: "Invitation " + (action === 'accept' ? 'acceptée' : 'refusée') + " avec succès."
        });
        if (d) refreshData();
    };

    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">Mes panneaux</h1>
                    <p className="text-slate-500 font-medium">Gestion de vos affichages et de vos collaborations.</p>
                </div>
                <div className="flex gap-2">
                    {!isSuspended && (
                        <Button variant="primary" icon={PlusIcon} onClick={() => { 
                            setManagingPanneau({ name: '', location: '', permitNumber: '', status: 'Brouillon', offerType: 'rental', currentRate: data.prices?.rentalMo ?? 180, physicalPanels: 0, hasNoAds: false, privateDocs: [], shippingAddress: '', client_uid: myClientData.id }); 
                            setValidationErrors([]); 
                            setModalStep('config_full'); 
                            setIsModalOpen(true); 
                        }} className="px-4 py-2">
                            Nouveau panneau
                        </Button>
                    )}
                </div>
            </div>

            {(!purchasesAllowed) && (
                <div className="bg-blue-50 text-blue-800 p-4 rounded-2xl border border-blue-200 shadow-sm flex items-center gap-3">
                    <AlertTriangleIcon size={24} className="shrink-0" />
                    <p className="text-sm font-bold">La validation de nouvelles commandes est temporairement suspendue. Vous pouvez toujours préparer vos brouillons.</p>
                </div>
            )}

            {pendingInvites.length > 0 && (
                <div className="space-y-4 mb-8">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 border-b border-slate-200 pb-2">
                        <UsersIcon size={20} className="text-blue-600"/> Invitations en attente
                    </h2>
                    {/* 3 colonnes décalées à 2xl */}
                    <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-4">
                        {pendingInvites.map((p, i) => {
                            const collab = p.collaborators?.find(c => c.uid === myClientData.id);
                            return (
                                <div key={i} className="bg-blue-50 border border-blue-200 rounded-3xl p-6 shadow-sm flex flex-col">
                                    <div className="flex items-start gap-4 mb-4">
                                        <div className="w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 bg-blue-100 text-blue-600">
                                            <UsersIcon size={24} />
                                        </div>
                                        <div>
                                            <h3 className="font-black text-lg text-blue-900 leading-tight">{p.name}</h3>
                                            <p className="text-xs font-bold text-blue-700 mt-1">
                                                Invitation à collaborer envoyée par {collab?.inviter_name || 'le propriétaire'} ({collab?.inviter_company || 'Société'})
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex flex-wrap gap-2 mt-auto">
                                        <Button variant="primary" icon={CheckCircleIcon} onClick={() => respondToInvite(p.id, 'accept')} disabled={isSaving} className="flex-1 py-2">Accepter</Button>
                                        <Button variant="danger" icon={XIcon} onClick={() => respondToInvite(p.id, 'reject')} disabled={isSaving} className="flex-1 py-2">Refuser</Button>
                                        <Button variant="outline" icon={MessageSquareIcon} onClick={() => {
                                            const u = new URL(window.location);
                                            u.searchParams.set('chat_id', `GROUP_${p.id}`);
                                            window.history.replaceState({}, '', u);
                                            setActiveTab('messages');
                                        }} className="flex-1 text-blue-700 hover:bg-blue-50 py-2">Messagerie</Button>
                                        <Button variant="outline" icon={EyeIcon} onClick={() => setPreviewPanneau(p)} className="flex-1 py-2">Aperçu</Button>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {/* 3 colonnes décalées à 2xl */}
            <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-4">
                {visiblePanels.map((c, i) => {
                    const isOwner = c.client_uid === myClientData.id;
                    const myCollabData = !isOwner ? c.collaborators?.find(col => col.uid === myClientData.id) : null;
                    const canEdit = isOwner || myCollabData?.rights?.can_edit;
                    
                    // Calcul robuste du délai d'expiration des brouillons
                    let draftCountdown = 100;
                    if (c.status === 'Brouillon') {
                        const timeStr = c.updated_at || c.created_at;
                        if (timeStr) {
                            const parsedTime = new Date(String(timeStr).replace(' ', 'T')).getTime();
                            if (!isNaN(parsedTime)) {
                                const diffDays = Math.floor((Date.now() - parsedTime) / (1000 * 3600 * 24));
                                draftCountdown = Math.max(0, 100 - diffDays);
                            }
                        }
                    }

                    return (
                        <div key={i} className={`bg-white rounded-3xl p-6 shadow-sm border ${c.status === 'Actif' ? 'border-emerald-200' : 'border-slate-200'} flex flex-col relative overflow-hidden group`}>
                            {!isOwner && (
                                <div className="absolute top-0 right-0 bg-blue-100 text-blue-800 text-[9px] font-black px-3 py-1 rounded-bl-xl uppercase tracking-widest shadow-sm">
                                    Collaboration
                                </div>
                            )}
                            <div className="flex justify-between items-start mb-4 mt-2">
                                <div className="flex items-center gap-3 min-w-0 pr-2">
                                    <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${c.status === 'Actif' ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-400'}`}><BuildingIcon size={24}/></div>
                                    <div className="min-w-0">
                                        <h3 className="font-black text-lg text-slate-800 leading-tight truncate" title={c.name}>{c.name || 'Brouillon sans nom'}</h3>
                                        <p className="text-xs text-slate-500 font-medium mt-0.5 truncate" title={c.location}>{c.location || 'Localisation non définie'}</p>
                                    </div>
                                </div>
                                <StatusBadge status={c.status} className="shrink-0" />
                            </div>
                            
                            <div className="flex-1"></div>

                            {c.status === 'Actif' && (
                                <div className="grid grid-cols-2 gap-2 mb-4 bg-slate-50 p-3 rounded-xl border border-slate-100">
                                    <div className="text-center"><p className="text-[10px] font-bold text-slate-400 uppercase">Scans QR</p><p className="font-black text-slate-800">{c.views}</p></div>
                                    <div className="text-center border-l border-slate-200"><p className="text-[10px] font-bold text-slate-400 uppercase">Abonnement</p><p className="font-black text-slate-800">{c.offerType === 'rental' ? 'Location' : 'Achat'}</p></div>
                                </div>
                            )}
                            
                            {c.status === 'Brouillon' && (
                                <div className="w-full text-center py-2 bg-amber-50 text-amber-700 rounded-xl text-xs font-bold mb-4 border border-amber-100">
                                    Suppression automatique dans {draftCountdown} jour(s)
                                </div>
                            )}

                            {c.status === 'Suppression programmée' && (
                                <div className="w-full text-center py-2 bg-slate-100 text-slate-500 rounded-xl text-xs font-bold mb-4">
                                    Suppression complète à la fin de la période
                                </div>
                            )}

                            <div className="flex flex-wrap gap-2 pt-4 border-t border-slate-100">
                                {c.status === 'Actif' && (
                                    <>
                                        <Button variant="secondary" icon={QrCodeIcon} onClick={() => setPreviewPanneau(c)} title="Aperçu du panneau" className="flex-1 sm:flex-none justify-center text-emerald-700 bg-emerald-50 hover:bg-emerald-100 py-2">Voir le panneau</Button>
                                        
                                        <div role="button" tabIndex={0} onClick={() => {
                                            const u = new URL(window.location);
                                            u.searchParams.set('chat_id', 'GROUP_' + c.id);
                                            window.history.replaceState({}, '', u);
                                            setActiveTab('messages');
                                        }} title="Discussion de l'équipe du projet" className="flex-1 sm:flex-none justify-center bg-blue-50 text-blue-700 hover:bg-blue-100 px-4 py-2 rounded-xl text-xs font-bold transition flex items-center gap-2 shadow-sm cursor-pointer">
                                            <MessageSquareIcon size={16} className="shrink-0" />
                                            Équipe
                                        </div>

                                        {isOwner && (
                                            <Button variant="purple" icon={UsersIcon} onClick={() => setPanelTeamModal(c)} title="Gérer l'équipe du panneau" className="flex-1 sm:flex-none justify-center py-2">Collaborateurs</Button>
                                        )}

                                        {canEdit && (
                                            <>
                                                <Button variant="secondary" icon={Share2Icon} onClick={() => { setManagingPanneau(c); setModalStep('share'); setIsModalOpen(true); }} title="Lien de saisie déléguée externe" className="flex-1 sm:flex-none justify-center py-2">Saisie tierce</Button>
                                                
                                                <div role="button" tabIndex={0} onClick={() => { setManagingPanneau(c); setModalStep('legal_vault'); setIsModalOpen(true); }} title="Documents d'huissier" className="flex-1 sm:flex-none justify-center px-4 py-2 rounded-xl text-xs font-bold bg-slate-900 text-white hover:bg-slate-800 flex items-center gap-2 transition shadow-sm cursor-pointer">
                                                    <LockIcon size={16}/> Coffre-fort
                                                </div>
                                                
                                                {!isSuspended && (
                                                    <Button variant="outline" icon={EditIcon} onClick={() => { setManagingPanneau({...c}); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} title="Éditer le panneau" className="flex-1 sm:flex-none justify-center py-2">Modifier</Button>
                                                )}
                                            </>
                                        )}
                                        
                                        {isOwner && (
                                            <>
                                                <Button variant="secondary" icon={ArchiveIcon} onClick={() => {
                                                    setConfirmDialog({
                                                        title: "Clôturer le panneau",
                                                        message: "Clôturer ce panneau ? Cette action va générer l'archive D.O.E.",
                                                        confirmText: "Clôturer et archiver",
                                                        type: 'confirm',
                                                        onConfirm: () => setArchiveConfig({ type: 'doe', panelId: c.id })
                                                    });
                                                }} disabled={archiveConfig !== null} title="Clôturer et archiver le panneau" className="flex-1 sm:flex-none justify-center py-2">Clôturer (D.O.E)</Button>
                                                
                                                <Button variant="warning" icon={PowerIcon} onClick={() => {
                                                    setConfirmDialog({
                                                        title: "Désactiver le panneau",
                                                        message: "Désactiver temporairement ce panneau ? Il ne sera plus visible publiquement, mais la facturation continuera. Vous pourrez le réactiver à tout moment.",
                                                        confirmText: "Désactiver",
                                                        isDestructive: true,
                                                        type: 'error',
                                                        onConfirm: async () => {
                                                            const d = await window.apiFetch('panneaux/status', { body: {id: c.id, status: 'Désactivé'} });
                                                            if (d) refreshData();
                                                        }
                                                    });
                                                }} title="Désactiver temporairement (Pause de l'affichage)" className="flex-1 sm:flex-none justify-center py-2">Désactiver</Button>
                                                
                                                <Button variant="danger" icon={Trash2Icon} onClick={() => handleDeletePanelClick(c)} title="Supprimer le panneau" className="flex-1 sm:flex-none justify-center py-2">Supprimer</Button>
                                            </>
                                        )}
                                    </>
                                )}
                                
                                {c.status === 'Brouillon' && !isSuspended && (
                                    <>
                                        <Button variant="info" icon={EyeIcon} onClick={() => setPreviewPanneau(c)} title="Aperçu du panneau" className="flex-1 sm:flex-none justify-center py-2">Aperçu</Button>
                                        {(isOwner || canEdit) && (
                                            <Button variant="primary" icon={EditIcon} onClick={() => { setManagingPanneau({...c}); setValidationErrors([]); setModalStep('config_full'); setIsModalOpen(true); }} title="Éditer ce brouillon" className="flex-1 justify-center py-2">Reprendre l'édition</Button>
                                        )}
                                        {isOwner && (
                                            <Button variant="danger" icon={Trash2Icon} onClick={() => {
                                                setConfirmDialog({
                                                    title: "Supprimer le brouillon",
                                                    message: "Voulez-vous vraiment supprimer définitivement ce brouillon ?",
                                                    confirmText: "Supprimer",
                                                    type: 'error',
                                                    isDestructive: true,
                                                    onConfirm: async () => {
                                                        const d = await window.apiFetch('panneaux/delete', { body: {id: c.id, force_immediate: true} });
                                                        if (d) refreshData();
                                                    }
                                                });
                                            }} title="Supprimer ce brouillon" className="py-2" />
                                        )}
                                    </>
                                )}

                                {(c.status === 'Désactivé' || c.status === 'Hors ligne' || c.status === 'Suppression programmée') && !isSuspended && isOwner && (
                                    <>
                                        {c.status !== 'Suppression programmée' && (
                                            <Button variant="secondary" icon={PowerIcon} onClick={() => {
                                                setConfirmDialog({
                                                    title: "Réactiver le panneau",
                                                    message: "Voulez-vous réactiver ce panneau pour le rendre à nouveau visible publiquement ?",
                                                    confirmText: "Réactiver",
                                                    type: 'success',
                                                    isDestructive: false,
                                                    onConfirm: async () => {
                                                        const d = await window.apiFetch('panneaux/status', { body: {id: c.id, status: 'Actif'} });
                                                        if (d) refreshData();
                                                    }
                                                });
                                            }} title="Réactiver le panneau" className="flex-1 sm:flex-none justify-center text-emerald-700 bg-emerald-50 hover:bg-emerald-100 py-2">Réactiver</Button>
                                        )}
                                        
                                        <Button variant="danger" icon={Trash2Icon} onClick={() => handleDeletePanelClick(c)} title="Supprimer le panneau" className="flex-1 sm:flex-none justify-center py-2">Supprimer</Button>
                                    </>
                                )}

                                {isOwner && c.status !== 'Suppression programmée' && (
                                    <Button variant="outline" icon={CopyIcon} onClick={() => { 
                                        const deepClone = JSON.parse(JSON.stringify(c));
                                        const cleanIntervenants = (deepClone.intervenants || []).map(i => ({...i, id: crypto.randomUUID(), logoId: '', logoUrl: ''}));
                                        const cleanLots = (deepClone.lots || []).map(l => ({...l, id: crypto.randomUUID(), entreprises: (l.entreprises || []).map(e => ({...e, id: crypto.randomUUID(), logoId: '', logoUrl: ''}))}));
                                        setManagingPanneau(null); 
                                        setManagingPanneau({ 
                                            ...c, 
                                            id: undefined, 
                                            delegate_links: [],
                                            name: c.name + ' (Copie)', 
                                            location: '', 
                                            permitNumber: '', 
                                            status: 'Brouillon', 
                                            offerType: 'rental', 
                                            physicalPanels: 0, 
                                            hasNoAds: false, 
                                            privateDocs: [], 
                                            shippingAddress: c.shippingAddress || '',
                                            imageId: '', 
                                            imageUrl: '', 
                                            pdfId: '',
                                            maitreOuvrageLogoId: '', 
                                            maitreOuvrageLogoUrl: '',
                                            intervenants: cleanIntervenants,
                                            lots: cleanLots
                                        }); 
                                        setValidationErrors([]);
                                        setModalStep('config_full'); 
                                        setIsModalOpen(true); 
                                    }} title="Dupliquer le panneau" className="flex-1 sm:flex-none justify-center py-2">Dupliquer</Button>
                                )}
                            </div>
                        </div>
                    );
                })}
                
                {visiblePanels.length === 0 && (
                    <div className="col-span-full text-center p-12 bg-white rounded-3xl border border-slate-200 border-dashed">
                        <BuildingIcon size={48} className="mx-auto text-slate-300 mb-4" />
                        <h3 className="text-lg font-black text-slate-700">Aucun panneau</h3>
                        <p className="text-slate-500 text-sm mt-1">Créez votre premier panneau pour démarrer ou attendez une invitation à collaborer.</p>
                    </div>
                )}
            </div>
        </div>
    );
};

// =========================================================================
// 2. ONGLET : LIVRAISONS
// =========================================================================

window.ClientLivraisonsTab = ({ data, myClientData, refreshData, showToast }) => {
    const { useState, useEffect } = React;
    const [deliveryConfirmModal, setDeliveryConfirmModal] = useState(null);
    const [isSaving, setIsSaving] = useState(false);

    // RÉCUPÉRATION SÉCURISÉE DES ICÔNES ET COMPOSANTS
    const PackageIcon = window.PackageIcon || (() => null);
    const MapPinIcon = window.MapPinIcon || (() => null);
    const CheckCircleIcon = window.CheckCircleIcon || (() => null);
    const ExternalLinkIcon = window.ExternalLinkIcon || (() => null);
    const LoaderIcon = window.LoaderIcon || (() => null);
    const Modal = window.Modal || (() => null);
    const StatusBadge = window.StatusBadge || (({status}) => <span className="text-xs font-bold">{status}</span>);
    
    // Fallback robuste avec restauration de la soumission native au clavier
    const Button = window.Button || (({children, onClick, className, disabled, title, icon: Icon, type}) => {
        const handleAction = (e) => {
            if (disabled) return;
            if (onClick) onClick(e);
            if (type === 'submit') {
                const form = e.currentTarget.closest('form');
                if (form && typeof form.requestSubmit === 'function') form.requestSubmit();
            }
        };
        return (
            <div 
                role="button" 
                tabIndex={disabled ? -1 : 0} 
                onClick={handleAction} 
                onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleAction(e); } }}
                className={`flex items-center justify-center gap-2 cursor-pointer transition ${className || ''} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`} 
                title={title}
            >
                {Icon && <Icon size={16} className="shrink-0" />}
                {children}
                {type === 'submit' && <input type="submit" className="hidden" disabled={disabled} tabIndex="-1" />}
            </div>
        );
    });

    // FACTORISATION : Logique métier d'accès aux panneaux
    const { visiblePanels } = window.getPanelAccessRights 
        ? window.getPanelAccessRights(data.panneaux || [], myClientData.id) 
        : { visiblePanels:[] };

    const deliveries = visiblePanels.filter(c => c.physicalPanels > 0);
    const activeDeliveriesList = deliveries.filter(c => c.shipping_status !== 'Livré');
    const historyDeliveriesList = deliveries.filter(c => c.shipping_status === 'Livré');

    useEffect(() => {
        const url = new URL(window.location);
        const confirmDelivery = url.searchParams.get('confirm_delivery');
        if (confirmDelivery) {
            setDeliveryConfirmModal(confirmDelivery);
            url.searchParams.delete('confirm_delivery');
            window.history.replaceState({}, '', url);
        }
    }, []);

    const handleConfirmDelivery = async () => {
        if (!deliveryConfirmModal) return;
        
        const d = await window.apiFetch('panneaux/shipping', {
            body: { id: deliveryConfirmModal, shipping_status: 'Livré' },
            setLoading: setIsSaving,
            successMessage: "Réception confirmée, merci !"
        });

        if (d) {
            refreshData();
            setDeliveryConfirmModal(null);
        }
    };

    const DeliveryCard = ({ c, isHistory }) => {
        const isShipped = c.shipping_status === 'Expédié';
        const isWaiting = c.shipping_status === 'Validation en cours' || c.shipping_status === "Attente d'impression";
        const displayStatus = c.shipping_status === "Attente d'impression" ? "Validée (en attente d'impression)" : c.shipping_status;
        
        return (
            <div className={`bg-white rounded-3xl p-5 shadow-sm border ${isShipped ? 'border-blue-200' : 'border-slate-200'} flex flex-col gap-4 transition hover:shadow-md`}>
                <div className="flex gap-4 items-start">
                    <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${isShipped ? 'bg-blue-50 text-blue-600' : (isHistory ? 'bg-emerald-50 text-emerald-600' : 'bg-slate-100 text-slate-500')}`}>
                        {isHistory ? <CheckCircleIcon size={24} /> : <PackageIcon 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 text-slate-500 flex items-center gap-1 mt-0.5"><MapPinIcon size={12}/> {c.shippingAddress || c.location}</p>
                    </div>
                    <div className="text-right shrink-0">
                        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Quantité</p>
                        <p className="text-lg font-black text-slate-800 leading-none">{c.physicalPanels}</p>
                    </div>
                </div>
                <div className={`p-3 rounded-xl border ${isShipped ? 'bg-blue-50/50 border-blue-100' : 'bg-slate-50 border-slate-100'}`}>
                    <div className="flex justify-between items-center mb-1">
                        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Statut de la commande</p>
                        <StatusBadge status={displayStatus} />
                    </div>
                    {c.tracking_number && (
                        <div className="mt-3 pt-3 border-t border-slate-200/60">
                            <p className="text-xs font-bold text-slate-700">N° de suivi : <span className="font-bold text-blue-600 ml-1 select-all">{c.tracking_number}</span></p>
                            {c.tracking_link && (
                                <a href={c.tracking_link.startsWith('http') ? c.tracking_link : `https://${c.tracking_link}`} target="_blank" rel="noopener noreferrer" className="text-[11px] font-bold text-blue-600 hover:text-blue-800 flex items-center gap-1 mt-1.5 transition">
                                    <ExternalLinkIcon size={12}/> Suivre mon colis sur le site du transporteur
                                </a>
                            )}
                        </div>
                    )}
                    {isWaiting && (
                        <p className="text-[11px] text-slate-500 mt-2 font-medium">Votre commande est en cours de traitement par nos équipes. Vous recevrez un lien de suivi dès l'expédition.</p>
                    )}
                </div>
                {isShipped && !isHistory && (
                    <Button variant="primary" icon={CheckCircleIcon} onClick={() => setDeliveryConfirmModal(c.id)} disabled={isSaving} className="w-full py-3 text-sm">
                        Confirmer la réception
                    </Button>
                )}
            </div>
        );
    };

    return (
        <div className="space-y-8 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">Livraisons</h1>
                    <p className="text-slate-500 font-medium">Suivi de vos commandes de panneaux physiques sur <a href="https://eco-panneau.fr" className="text-emerald-600 hover:underline font-bold" target="_blank" rel="noopener noreferrer">eco-panneau.fr</a>.</p>
                </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-slate-500 text-sm mt-1">Aucune commande de panneaux physiques associée à vos chantiers.</p>
                </div>
            ) : (
                <>
                    {activeDeliveriesList.length > 0 && (
                        <div className="space-y-4">
                            <h3 className="font-black text-slate-800 text-lg flex items-center gap-2"><PackageIcon size={20} className="text-blue-600"/> En cours ({activeDeliveriesList.length})</h3>
                            {/* 3 colonnes décalées à 2xl */}
                            <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-4">
                                {activeDeliveriesList.map(c => <DeliveryCard key={c.id} c={c} isHistory={false} />)}
                            </div>
                        </div>
                    )}
                    
                    {historyDeliveriesList.length > 0 && (
                        <div className="space-y-4">
                            <h3 className="font-black text-slate-800 text-lg flex items-center gap-2 pt-4 border-t border-slate-200"><CheckCircleIcon size={20} className="text-emerald-600"/> Historique ({historyDeliveriesList.length})</h3>
                            {/* 3 colonnes décalées à 2xl */}
                            <div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-4 opacity-80 hover:opacity-100 transition-opacity">
                                {historyDeliveriesList.map(c => <DeliveryCard key={c.id} c={c} isHistory={true} />)}
                            </div>
                        </div>
                    )}
                </>
            )}

            {/* MODALE DE CONFIRMATION DE LIVRAISON */}
            {deliveryConfirmModal && Modal && (
                <Modal title="Confirmation de réception" type="success" onClose={() => setDeliveryConfirmModal(null)} preventClose={isSaving}>
                    <div className="space-y-4">
                        <div className="bg-emerald-50 text-emerald-800 p-5 rounded-2xl border border-emerald-200 text-sm leading-relaxed shadow-sm">
                            <p className="font-black mb-2 flex items-center gap-2">{PackageIcon && <PackageIcon size={18} className="shrink-0"/>} Colis livré ?</p>
                            <p>En confirmant, vous indiquez avoir bien reçu l'intégralité de votre commande de panneaux physiques pour ce chantier.</p>
                        </div>
                        
                        <div className="flex flex-col sm:flex-row gap-3 mt-6">
                            <Button variant="secondary" onClick={() => setDeliveryConfirmModal(null)} disabled={isSaving} className="w-full sm:flex-1 py-3 justify-center">
                                Annuler
                            </Button>
                            <Button variant="primary" onClick={handleConfirmDelivery} disabled={isSaving} icon={isSaving ? LoaderIcon : CheckCircleIcon} className="w-full sm:flex-1 py-3 uppercase tracking-wider text-xs sm:text-sm leading-tight justify-center">
                                <span className="text-center">Oui, j'ai reçu mon colis</span>
                            </Button>
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
};

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