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

// 1. - COMPOSANT CARTE INVITATION (MODE COMPACT ET STANDARD)
window.pano_ClientInviteCard = ({ 
    invite: p, 
    setPreviewPanneau, 
    refreshData,
    hasCollabFeature,
    isMini,
    onClick,
    // PROPS DE ROUTAGE INJECTÉES PAR LE PARENT
    openModal,
    openLocalModal,
    openChat
}) => {
    const { useState } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    const [isSaving, setIsSaving] = useState(false);
    const [isProcessed, setIsProcessed] = useState(false);

    // CORRECTION ZÉRO-DETTE : Fallbacks robustes si le parent omet de passer la fonction
    const handleOpenModal = (n, id, s) => {
        if (openModal) openModal(n, id, s);
        else if (openLocalModal) openLocalModal(n, id, s);
    };

    const handleOpenChat = (id, s) => {
        if (openChat) openChat(id, s);
        else {
            const prev = window.history.state || { panoStack: [], level: 0, currentTab: 'dashboard' };
            const newStack = (prev.panoStack || []).filter(l => l.type !== 'chat');
            newStack.push({ type: 'chat', name: 'chat', targetId: id });
            window.history.pushState({ ...prev, panoStack: newStack, level: newStack.length }, '', window.location.href);
            window.dispatchEvent(new Event('pano_stack_sync'));
        }
    };

    const { UsersIcon, EyeIcon, MessageSquareIcon, CheckCircleIcon, XIcon } = window.pano_getIcons();
    const { IconBadge, Button, DataCard } = window.pano_getComponents();

    const inviterDisplay = p.owner_name ? `${p.owner_company || 'Société'} (${p.owner_name})` : (p.owner_company || 'Société');

    const respondToInvite = async (action) => {
        setIsProcessed(true);
        const d = await safeFetch('panneaux/collaborators/respond', { 
            body: { panneau_id: p.id, action: action }, 
            setLoading: setIsSaving, 
            successMessage: action === 'accept' ? "Projet rejoint avec succès." : "Invitation refusée." 
        });
        
        if (!isMounted.current) return;

        if (d && refreshData) refreshData();
    };

    if (isProcessed) return null;

    if (isMini) {
        return (
            <DataCard 
                variant="info" 
                onClick={onClick} 
                className="cursor-pointer group hover:scale-[1.02] transition-transform min-w-0 p-3"
            >
                <div className="flex items-center gap-2 min-w-0">
                    <IconBadge icon={UsersIcon} variant="info" size="md" className="shrink-0" />
                    <div className="min-w-0 flex-1 pr-2">
                        <p className="font-bold text-sm break-words leading-tight text-blue-900">{p.name || 'Projet sans nom'}</p>
                        <div className="flex flex-wrap items-center gap-2 mt-1">
                            <span className="text-[10px] font-bold uppercase tracking-widest text-blue-700">Invitation de {inviterDisplay}</span>
                        </div>
                    </div>
                </div>
            </DataCard>
        );
    }

    return (
        <DataCard variant="info" className="gap-2 transition hover:shadow-md border-blue-200 shadow-sm min-w-0 group flex flex-col p-4">
            <div className="flex items-start gap-3 mb-2 min-w-0">
                <IconBadge icon={UsersIcon} variant="info" size="lg" className="shrink-0" />
                <div className="flex-1 min-w-0">
                    <h3 className="font-black text-lg text-blue-900 leading-tight break-words">{p.name}</h3>
                    <p className="text-xs text-slate-600 mt-1 break-words leading-tight">
                        Invitation de <strong className="font-bold text-slate-800">{inviterDisplay}</strong>
                    </p>
                </div>
            </div>
            <div className="flex flex-wrap items-center gap-2 mt-auto pt-2.5 border-t border-blue-100 min-w-0">
                <Button variant="secondary" icon={EyeIcon} onClick={(e) => { e.stopPropagation(); if (setPreviewPanneau) setPreviewPanneau(p); handleOpenModal('preview', p.id, false); }} className="flex-1 whitespace-nowrap bg-white border-blue-200 text-blue-700 hover:bg-blue-100">Aperçu</Button>
                {hasCollabFeature && (
                    <Button variant="info" icon={MessageSquareIcon} onClick={(e) => { 
                        e.stopPropagation();
                        handleOpenChat('GROUP_' + p.id, false);
                    }} className="flex-1 whitespace-nowrap bg-white">Messagerie</Button>
                )}
                <Button variant="primary" icon={CheckCircleIcon} onClick={(e) => { e.stopPropagation(); respondToInvite('accept'); }} disabled={isSaving} className="flex-1 whitespace-nowrap shadow-sm">Accepter</Button>
                <Button variant="danger" icon={XIcon} onClick={(e) => { e.stopPropagation(); respondToInvite('reject'); }} disabled={isSaving} className="flex-1 whitespace-nowrap bg-white text-red-600 hover:bg-red-50">Refuser</Button>
            </div>
        </DataCard>
    );
};

// 2. - COMPOSANT CARTE PANNEAU CLIENT AUTONOME
window.pano_ClientPanelCard = ({ 
    panel: c, 
    data, 
    myClientData, 
    localPinned, 
    togglePin, 
    unreadMap, 
    setPreviewPanneau, 
    setManagingPanneau, 
    setValidationErrors, 
    isSuspended, 
    hasNewsletterFeature, 
    hasCollabFeature, 
    hasMessagingFeature, 
    refreshData, 
    setPanelTeamModal,
    setArchiveConfig,
    // PROPS DE ROUTAGE INJECTÉES PAR LE PARENT
    openModal,
    openLocalModal,
    openDialog,
    openLocalDialog,
    closeCurrentLayer,
    openChat,
    activeDialog,
    dialogId
}) => {
    const { useState, useEffect } = React;
    
    // SÉCURITÉ ANTI-FUITE DE MÉMOIRE : Utilisation du Hook Global Zéro-Dette
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    const [isConfirming, setIsConfirming] = useState(false);
    const [deleteMode, setDeleteMode] = useState(c.offerType === 'purchase' ? 'immediate' : 'scheduled');
    const [deleteWaiver, setDeleteWaiver] = useState(c.offerType === 'purchase');
    const [deletePassword, setDeletePassword] = useState('');
    const [isSaving, setIsSaving] = useState(false);
    const [confirmConfig, setConfirmConfig] = useState(null);

    // CORRECTION ZÉRO-DETTE : Fallbacks robustes au cas où le parent (comme le Dashboard) omette de fournir la prop
    const handleOpenModal = (n, id, s) => {
        if (openModal) openModal(n, id, s);
        else if (openLocalModal) openLocalModal(n, id, s);
    };

    const handleOpenDialog = (n, id, s) => {
        if (openDialog) openDialog(n, id, s);
        else if (openLocalDialog) openLocalDialog(n, id, s);
    };

    const handleCloseLayer = () => {
        if (closeCurrentLayer) closeCurrentLayer();
    };

    const handleOpenChat = (id, s) => {
        if (openChat) openChat(id, s);
        else {
            const prev = window.history.state || { panoStack: [], level: 0, currentTab: 'dashboard' };
            const newStack = (prev.panoStack || []).filter(l => l.type !== 'chat');
            newStack.push({ type: 'chat', name: 'chat', targetId: id });
            window.history.pushState({ ...prev, panoStack: newStack, level: newStack.length }, '', window.location.href);
            window.dispatchEvent(new Event('pano_stack_sync'));
        }
    };

    // Ajout des icônes ShoppingCartIcon / PackageIcon
    const {
        BuildingIcon, BuildingTeamIcon, QrCodeIcon, EyeIcon, MessageSquareIcon, MailIcon, LockIcon, EditIcon, 
        Trash2Icon, ArchiveIcon, AlertTriangleIcon, CheckCircleIcon, LoaderIcon, UsersIcon, RefreshCwIcon, PinIcon, DownloadIcon, ShoppingCartIcon, PackageIcon
    } = window.pano_getIcons();

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

    // RÈGLES DE GESTION DU STATUT (DOE, Suppression Programmée, etc.)
    const isDOE = c.status === 'DOE';
    const isScheduledDelete = c.status === 'Suppression programmée';
    
    const isUnreadDOE = isDOE && !c.doe_downloaded;

    // CORRECTION UX : Calcul dynamique des jours restants avant suppression légale
    let doeDaysLeft = 0;
    if (isDOE) {
        const retention = parseInt(data?.settings?.doe_retention_days || 30, 10);
        const updateTime = c.updated_at ? new Date(c.updated_at.replace(' ', 'T')).getTime() : Date.now();
        const daysElapsed = Math.floor((Date.now() - updateTime) / (1000 * 3600 * 24));
        doeDaysLeft = Math.max(0, retention - daysElapsed);
    }

    const isOwner = c.client_uid === myClientData.id;
    const isMe = (uid) => uid === myClientData.id || uid === myClientData.email_hash;
    const myCollab = !isOwner ? c.collaborators?.find(col => isMe(col.uid)) : null;
    
    // Verrouillage total de l'édition si le panneau est en D.O.E.
    const canEdit = !isDOE && (isOwner || myCollab?.rights?.can_edit);
    const canChat = !isDOE && (isOwner || (myCollab && ['read', 'rw'].includes(myCollab.rights?.chat_access)));
    const isPinned = localPinned.includes(c.id);
    
    const hasDraft = c.draft_data && Object.keys(c.draft_data).length > 0;
    
    const unreadRiverain = unreadMap[c.id]?.riverain || 0;
    const unreadGroup = unreadMap[c.id]?.group || 0;

    useEffect(() => {
        // Verrouillage du useEffect sur la carte concernée
        if (activeDialog === 'delete_advanced' && dialogId === c.id) {
            if (c.offerType === 'purchase') {
                setDeleteMode('immediate');
                setDeleteWaiver(true);
            } else {
                setDeleteMode('scheduled');
                setDeleteWaiver(false);
            }
        }
    }, [activeDialog, dialogId, c.id, c.offerType]);

    const handleConfirmActivity = async (e) => {
        e.stopPropagation();
        setIsConfirming(true);
        const d = await safeFetch('panneaux/confirm_activity', {
            body: { id: c.id },
            successMessage: "Activité confirmée avec succès. Le délai est réinitialisé."
        });
        if (!isMounted.current) return; 
        setIsConfirming(false);
        if (d && refreshData) refreshData();
    };

    const handleDeleteSubmit = async (e) => {
        e.preventDefault();

        // Forçage immédiat -> Redirection vers l'Archive D.O.E
        if (deleteMode === 'immediate' && (c.status === 'Actif' || c.status === 'Suppression programmée')) {
            handleCloseLayer();
            if (setArchiveConfig) setArchiveConfig({ type: 'doe', panelId: c.id });
            setTimeout(() => {
                handleOpenDialog('archive_config', c.id, false);
            }, 150);
            return;
        }

        const payload = { id: c.id, force_immediate: deleteMode === 'immediate' };
        if (c.status === 'Actif' || c.status === 'Suppression programmée') payload.password = deletePassword;

        const d = await safeFetch('panneaux/delete', { 
            body: payload, 
            setLoading: setIsSaving,
            successMessage: "Opération réussie." 
        });
        
        if (!isMounted.current) return;
        
        if (d) { 
            handleCloseLayer(); 
            if (refreshData) refreshData(); 
        }
    };

    const handleDoeDelete = (e) => {
        e.stopPropagation();
        setConfirmConfig({
            title: "Suppression définitive de l'archive",
            message: "Êtes-vous sûr de vouloir détruire définitivement cette archive D.O.E ? Toutes les données (fichiers, factures) liées à ce panneau seront effacées du serveur.",
            confirmText: "Oui, détruire",
            isDestructive: true,
            onConfirm: async () => {
                setConfirmConfig(null);
                const d = await safeFetch('archives/doe_delete', { 
                    body: { id: c.id }, 
                    setLoading: setIsSaving, 
                    successMessage: "Archive détruite avec succès." 
                });
                if (!isMounted.current) return;
                if (d && refreshData) refreshData();
            },
            onCancel: () => setConfirmConfig(null)
        });
        handleOpenDialog('confirm', c.id, false);
    };

    const handleCancelDeletion = async (e) => {
        e.stopPropagation();
        const d = await safeFetch('panneaux/cancel_deletion', {
            body: { id: c.id },
            setLoading: setIsSaving,
            successMessage: "La suppression a été annulée. La facturation et le panneau reprennent normalement."
        });
        if (!isMounted.current) return;
        if (d && refreshData) refreshData();
    };

    return (
        <>
            <DataCard className={`p-4 ${isDOE ? 'border-slate-800 bg-slate-50' : (c.status === 'Actif' ? 'border-emerald-200' : 'border-slate-200')} flex flex-col relative group transition-shadow hover:shadow-md min-w-0 h-full`}>
                
                {/* Épingle */}
                <div 
                    role="button" 
                    tabIndex={0} 
                    onClick={(e) => { e.stopPropagation(); togglePin(c.id, e); }} 
                    className={`absolute top-2 right-2 z-20 p-1 cursor-pointer transition-all duration-200 ${isPinned ? 'text-emerald-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 en haut"}
                >
                    <PinIcon size={18} filled={isPinned} />
                </div>

                <div className="flex justify-between items-start mb-3 mt-1">
                    <div className="flex items-center gap-3 min-w-0 pr-2 flex-1">
                        <div title={isOwner ? "Vous êtes le propriétaire du panneau" : "Vous êtes collaborateur sur ce panneau"}>
                            <IconBadge 
                                icon={isDOE ? ArchiveIcon : (isOwner ? BuildingIcon : BuildingTeamIcon)} 
                                variant={isDOE ? 'dark' : (c.status === 'Actif' ? 'success' : (c.status === 'Suspendu' || c.status === 'Attente validation' ? 'warning' : 'secondary'))} 
                                size="lg" 
                                className="shrink-0" 
                            />
                        </div>
                        
                        <div className="min-w-0 flex-1">
                            <h3 className={`font-black text-lg break-words leading-tight ${c.name ? (isDOE ? 'text-slate-600' : 'text-slate-800') : 'text-slate-400 italic'}`} title={c.name}>{c.name || 'Projet sans nom'}</h3>
                            {c.location && <p className="text-xs text-slate-500 break-words leading-tight mt-1" title={c.location}>{c.location}</p>}
                        </div>
                    </div>
                    
                    <div className="flex flex-col items-end gap-2 shrink-0 ml-2 mt-2">
                        <div className="flex items-center gap-2">
                            {c.status === 'Actif' && hasDraft && (
                                <span className="text-[10px] font-black uppercase tracking-widest bg-purple-100 text-purple-700 px-2 py-0.5 rounded shadow-sm">Modifié</span>
                            )}
                            {c.status !== 'Actif' && c.status !== 'DOE' && <StatusBadge status={c.status} />}
                        </div>
                    </div>
                </div>
                
                <div className="flex-1"></div>

                {/* BANDEAU D.O.E. */}
                {isDOE && (
                    <div className={`p-3 rounded-xl mb-3 flex items-center justify-between shadow-inner ${isUnreadDOE ? 'bg-orange-50 text-orange-800 border border-orange-200' : 'bg-slate-800 text-white'}`}>
                        <div>
                            {isUnreadDOE ? (
                                <>
                                    <p className="text-[10px] font-black uppercase tracking-widest text-orange-600 flex items-center gap-1.5"><AlertTriangleIcon size={12}/> Action requise</p>
                                    <p className="text-sm font-bold mt-0.5">Téléchargez votre archive légale D.O.E</p>
                                </>
                            ) : (
                                <>
                                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">Archive D.O.E générée</p>
                                    <p className="text-sm font-bold mt-0.5">Suppression automatique dans {doeDaysLeft} {window.pano_formatPlural(doeDaysLeft, "jour", "jours")}</p>
                                </>
                            )}
                        </div>
                        <ArchiveIcon size={24} className={`${isUnreadDOE ? 'text-orange-500' : 'text-slate-500'} opacity-50 shrink-0`} />
                    </div>
                )}

                {/* BANDEAU SUPPRESSION PROGRAMMÉE */}
                {isScheduledDelete && (
                    <div className="bg-orange-50 border border-orange-200 p-3 rounded-xl mb-3">
                        <p className="text-xs font-bold text-orange-800 flex items-start gap-2 break-words leading-relaxed">
                            <AlertTriangleIcon size={14} className="shrink-0 mt-0.5"/>
                            <span>Ce panneau restera actif et sera converti en archive D.O.E {(c.cancel_at || c.delete_at) ? <>le <strong className="font-black">{window.pano_formatDate(c.cancel_at || c.delete_at)}</strong></> : "à la fin de la période facturée"}.</span>
                        </p>
                    </div>
                )}

                {/* BANDEAU INACTIVITÉ */}
                {c.inactivity_alert_level > 0 && c.status === 'Actif' && (
                    <div className="pt-2.5 border-t border-slate-100 mt-2 mb-2 min-w-0">
                        <div className="bg-red-50 border border-red-200 p-3 rounded-xl flex flex-col gap-2 shadow-inner">
                            <p className="text-xs text-red-800 font-bold flex items-start gap-2 leading-tight break-words">
                                <AlertTriangleIcon size={16} className="shrink-0 mt-0.5 text-red-600"/> 
                                Alerte inactivité : Sans confirmation de votre part, ce panneau sera supprimé sous {c.inactivity_alert_level} {c.inactivity_alert_level > 1 ? 'jours' : 'jour'}.
                            </p>
                            <Button 
                                variant="dangerSolid" 
                                icon={isConfirming ? LoaderIcon : CheckCircleIcon} 
                                disabled={isConfirming} 
                                onClick={handleConfirmActivity} 
                                className="w-full justify-center text-[10px] uppercase tracking-widest py-2 shadow-md"
                            >
                                {isConfirming ? 'Confirmation...' : 'Confirmer que le chantier est actif'}
                            </Button>
                        </div>
                    </div>
                )}
                
                {/* BARRE D'ACTIONS INFERIEURE */}
                {isDOE ? (
                    <div className="flex flex-col sm:flex-row items-center justify-end gap-2 pt-3 border-t border-slate-100 mt-4 min-w-0">
                        <Button variant="danger" shape="square" icon={Trash2Icon} onClick={handleDoeDelete} disabled={isSaving} className="bg-white hover:bg-red-50 shadow-sm shrink-0 p-2.5" title="Supprimer définitivement l'archive" />
                        
                        <Button variant="secondary" shape="square" icon={LockIcon} onClick={(e) => { e.stopPropagation(); handleOpenDialog('pwd_arc', c.doe_filename || 'DOE_' + c.id, false); }} disabled={isSaving} className="bg-white hover:bg-slate-100 shadow-sm shrink-0 p-2.5" title="Afficher le mot de passe" />

                        <Button variant="secondary" shape="square" icon={MailIcon} onClick={async (e) => { 
                            e.stopPropagation(); 
                            await safeFetch('archives/send_password', { body: { filename: c.doe_filename || 'DOE_' + c.id }, setLoading: setIsSaving, successMessage: "Mot de passe envoyé par e-mail !" });
                        }} disabled={isSaving} className="bg-white hover:bg-slate-100 shadow-sm shrink-0 p-2.5" title="Recevoir le mot de passe par e-mail" />
                        
                        <a 
                            href={`${window.pano_CONFIG.apiBaseUrl}archives/download&file=${c.doe_filename || 'DOE_' + c.id}`} 
                            download 
                            onClick={(e) => { 
                                e.stopPropagation(); 
                                if (isUnreadDOE && refreshData) {
                                    setTimeout(() => refreshData(), 2000); 
                                } 
                            }}
                            className={`flex-1 w-full py-2.5 text-xs uppercase tracking-widest justify-center shadow-md text-center rounded-xl transition flex items-center gap-2 font-bold ${isUnreadDOE ? 'bg-orange-500 hover:bg-orange-600 text-white' : 'bg-slate-800 hover:bg-slate-900 text-white'}`}
                        >
                            <DownloadIcon size={16} /> <span className="truncate">Télécharger D.O.E</span>
                        </a>
                    </div>
                ) : (
                    <div className="flex flex-wrap items-center justify-end gap-2 pt-3 border-t border-slate-100 mt-auto min-w-0">
                        {c.status === 'Actif' && (
                            <Button 
                                variant="success" 
                                shape="square"
                                icon={QrCodeIcon} 
                                onClick={(e) => { 
                                    e.stopPropagation();
                                    const livePanel = { ...c };
                                    delete livePanel.draft_data; 
                                    setPreviewPanneau(livePanel); 
                                    handleOpenModal('preview', c.id); 
                                }} 
                                className="bg-white shadow-sm hover:border-emerald-300" 
                                title="Voir le panneau en ligne" 
                            />
                        )}

                        {(hasDraft || c.status !== 'Actif') && (
                            <Button 
                                variant="info" 
                                shape="square"
                                icon={EyeIcon} 
                                onClick={(e) => { 
                                    e.stopPropagation();
                                    setPreviewPanneau(hasDraft ? { ...c, ...c.draft_data } : c); 
                                    handleOpenModal('preview', c.id); 
                                }} 
                                className="bg-white shadow-sm hover:border-blue-300" 
                                title="Aperçu du projet" 
                            />
                        )}
                        
                        {c.status === 'Actif' && (
                            <>
                                {canChat && hasMessagingFeature && c.status !== 'Suppression programmée' && (
                                    <Button 
                                        variant="secondary" 
                                        shape="square"
                                        icon={MessageSquareIcon} 
                                        onClick={(e) => { e.stopPropagation(); handleOpenModal('riverains_list', c.id); }} 
                                        className="relative bg-white shadow-sm hover:border-slate-300" 
                                        title="Messages des riverains"
                                    >
                                        <NotificationBadge count={unreadRiverain} className="absolute -top-2 -right-2 scale-75" />
                                    </Button>
                                )}

                                {hasCollabFeature && (
                                    <Button 
                                        variant="secondary" 
                                        shape="square"
                                        icon={UsersIcon} 
                                        onClick={(e) => { 
                                            e.stopPropagation();
                                            if (setPanelTeamModal) setPanelTeamModal(c);
                                            setManagingPanneau(c);
                                            handleOpenDialog('team', c.id);
                                        }} 
                                        className="relative bg-white shadow-sm hover:border-slate-300" 
                                        title="Gérer l'équipe"
                                    >
                                        <NotificationBadge count={unreadGroup} className="absolute -top-2 -right-2 scale-75" />
                                    </Button>
                                )}

                                {hasNewsletterFeature && (
                                    <Button 
                                        variant="warning" 
                                        shape="square"
                                        icon={MailIcon} 
                                        onClick={(e) => { e.stopPropagation(); setManagingPanneau(c); handleOpenModal('newsletter', c.id); }} 
                                        className="relative bg-white shadow-sm hover:border-amber-300" 
                                        title={`Info riverains ${c.newsletterSubscribers > 0 ? `(${c.newsletterSubscribers})` : ''}`}
                                    >
                                        {c.newsletterSubscribers > 0 && <NotificationBadge count={c.newsletterSubscribers} className="absolute -top-2 -right-2 scale-75" />}
                                    </Button>
                                )}

                                {canEdit && c.status !== 'Suppression programmée' && (
                                    <Button 
                                        variant="purple" 
                                        shape="square"
                                        icon={LockIcon} 
                                        onClick={(e) => { e.stopPropagation(); setManagingPanneau(c); handleOpenModal('vault', c.id); }} 
                                        className="bg-white shadow-sm hover:border-purple-300" 
                                        title="Coffre-fort légal" 
                                    />
                                )}
                            </>
                        )}

                        {isOwner && c.status === 'Actif' && !isSuspended && c.status !== 'Suppression programmée' && (
                            <Button 
                                variant="warning" 
                                shape="square"
                                icon={ShoppingCartIcon || PackageIcon} 
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setManagingPanneau(c); 
                                    handleOpenDialog('select_offer', c.id);
                                }} 
                                className="bg-white shadow-sm hover:border-amber-400 text-amber-600 hover:bg-amber-50"
                                title="Commander des panneaux physiques (A1)"
                            />
                        )}

                        {canEdit && !isSuspended && c.status !== 'Suppression programmée' && (
                            <Button 
                                variant={c.status === 'Suspendu' ? 'warning' : 'outline'} 
                                shape="square"
                                icon={EditIcon} 
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setManagingPanneau(c); 
                                    setValidationErrors([]); 
                                    handleOpenModal('editor', c.id); 
                                }} 
                                className="bg-white shadow-sm hover:border-emerald-300"
                                title={c.status === 'Suspendu' ? "Corriger le panneau" : "Modifier le panneau"}
                            />
                        )}
                        
                        {canEdit && c.status === 'Actif' && hasDraft && !isSuspended && c.status !== 'Suppression programmée' && (
                            <Button 
                                variant="danger" 
                                shape="round" 
                                icon={RefreshCwIcon} 
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setConfirmConfig({
                                        title: "Annuler les modifications", 
                                        message: "Voulez-vous annuler toutes les modifications non publiées et restaurer la version en ligne ?", 
                                        confirmText: "Annuler les modifications", 
                                        isDestructive: true,
                                        onConfirm: async () => {
                                            const d = await safeFetch('panneaux', { 
                                                body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, draft_data: {} } },
                                                setLoading: setIsSaving
                                            });
                                            if (!isMounted.current) return;
                                            if (refreshData) refreshData(); 
                                            handleCloseLayer();
                                        }
                                    });
                                    handleOpenDialog('confirm', c.id, false);
                                }} 
                                className="shadow-none shrink-0 bg-white hover:bg-red-50 border-red-100 text-red-500 hover:text-red-700" 
                                title="Annuler les modifications" 
                            />
                        )}

                        {isOwner && c.status === 'Actif' && c.status !== 'Suppression programmée' && (
                            <Button 
                                variant="danger" 
                                shape="round" 
                                icon={ArchiveIcon} 
                                onClick={(e) => { e.stopPropagation(); setDeletePassword(''); handleOpenDialog('delete_advanced', c.id, false); }} 
                                className="shadow-none shrink-0 bg-white hover:bg-red-50" 
                                title="Clôturer / Supprimer" 
                            />
                        )}

                        {isOwner && c.status !== 'Actif' && !isScheduledDelete && (
                            <Button 
                                variant="danger" 
                                shape="round" 
                                icon={Trash2Icon} 
                                onClick={(e) => { e.stopPropagation(); setDeletePassword(''); handleOpenDialog('delete_advanced', c.id, false); }} 
                                className="shadow-none shrink-0 bg-white hover:bg-red-50" 
                                title="Supprimer" 
                            />
                        )}

                        {isScheduledDelete && isOwner && (
                            <Button 
                                variant="outline" 
                                icon={RefreshCwIcon} 
                                onClick={handleCancelDeletion} 
                                disabled={isSaving} 
                                className="w-full mt-2 py-1.5 text-[10px] uppercase justify-center text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 border-emerald-200 shadow-sm text-center"
                            >
                                Annuler la suppression
                            </Button>
                        )}
                    </div>
                )}
            </DataCard>

            {/* Modales Encapsulées Zéro-Dette */}
            {activeDialog === 'delete_advanced' && dialogId === c.id && Modal && (
                <Modal 
                    title="Supprimer le panneau" 
                    type="error" 
                    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={`delete-advanced-form-${c.id}`} variant={deleteMode === 'immediate' ? 'dangerSolid' : 'primary'} disabled={isSaving || (deleteMode === 'immediate' && !deleteWaiver && c.offerType === 'rental') || ((c.status === 'Actif' || c.status === 'Suppression programmée') && !deletePassword)} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">Confirmer</Button>
                        </>
                    )}
                >
                    <form id={`delete-advanced-form-${c.id}`} onSubmit={handleDeleteSubmit} className="space-y-4 min-w-0">
                        <p className="text-sm text-slate-600 mb-4 break-words">Choisissez comment supprimer <strong className="break-all">{c.name}</strong>.</p>
                        
                        {c.offerType === 'rental' ? (
                            <>
                                <div className="bg-amber-50 text-amber-800 p-3 rounded-xl border border-amber-200 text-sm mb-4">
                                    <p className="font-bold flex items-center gap-1.5"><AlertTriangleIcon size={14}/> Attention</p>
                                    <p className="mt-1 leading-relaxed">Masquer un panneau depuis votre tableau de bord ne suspend pas sa facturation.</p>
                                </div>
                                
                                <label className={`flex items-start gap-3 p-3 border rounded-xl cursor-pointer transition shadow-sm ${deleteMode === 'scheduled' ? 'border-emerald-500 bg-emerald-50 shadow-sm' : 'border-slate-200 hover:bg-slate-50'}`}>
                                    <input type="radio" checked={deleteMode === 'scheduled'} onChange={() => setDeleteMode('scheduled')} className="mt-0.5 w-5 h-5 accent-emerald-600 shrink-0" />
                                    <div className="min-w-0 flex-1">
                                        <p className="font-bold text-sm text-slate-800 break-words leading-tight">Supprimer à l'échéance (Recommandée)</p>
                                        <p className="text-xs text-slate-600 mt-1 break-words leading-tight">Le panneau restera actif jusqu'à la fin de la période facturée, puis sera converti en archive D.O.E.</p>
                                    </div>
                                </label>
                                
                                <label className={`flex items-start gap-3 p-3 border rounded-xl cursor-pointer transition shadow-sm ${deleteMode === 'immediate' ? 'border-red-500 bg-red-50' : 'border-slate-200 hover:bg-slate-50'}`}>
                                    <input type="radio" checked={deleteMode === 'immediate'} onChange={() => setDeleteMode('immediate')} className="mt-0.5 w-5 h-5 accent-red-600 shrink-0" />
                                    <div className="min-w-0 flex-1">
                                        <p className="font-bold text-sm text-slate-800 break-words leading-tight">Supprimer immédiatement</p>
                                        <p className="text-xs text-slate-600 mt-1 break-words leading-tight">Détruit le panneau immédiatement pour générer l'archive D.O.E (aucun remboursement au prorata ne sera appliqué).</p>
                                    </div>
                                </label>
                                
                                {deleteMode === 'immediate' && (
                                    <label className="flex items-start gap-3 p-3 bg-orange-50 border border-orange-200 rounded-xl cursor-pointer mt-2 shadow-sm min-w-0">
                                        <input type="checkbox" checked={deleteWaiver} onChange={(e) => setDeleteWaiver(e.target.checked)} className="mt-0.5 w-5 h-5 accent-orange-600 shrink-0" />
                                        <span className="text-xs font-bold text-orange-900 break-words leading-tight block flex-1">Je force la clôture immédiate et je reconnais qu'aucun remboursement au prorata ne sera effectué.</span>
                                    </label>
                                )}
                            </>
                        ) : (
                            <label className={`flex items-start gap-3 p-3 border rounded-xl cursor-pointer transition shadow-sm border-red-500 bg-red-50`}>
                                <input type="radio" checked={true} readOnly className="mt-0.5 w-5 h-5 accent-red-600 shrink-0" />
                                <div className="min-w-0 flex-1">
                                    <p className="font-bold text-sm text-slate-800 break-words leading-tight">Supprimer et archiver immédiatement</p>
                                    <p className="text-xs text-slate-600 mt-1 break-words leading-tight">Le panneau sera converti en archive D.O.E immédiatement.</p>
                                </div>
                            </label>
                        )}

                        {(c.status === 'Actif' || c.status === 'Suppression programmée') && (
                            <div className="mt-3 p-3 bg-slate-50 border border-slate-200 rounded-xl space-y-2 min-w-0">
                                <FormInput 
                                    label="Mot de passe requis (Sécurité)" 
                                    type="password" 
                                    value={deletePassword} 
                                    onChange={e => setDeletePassword(e.target.value)} 
                                    placeholder="Saisissez votre mot de passe..." 
                                    className="w-full min-w-0"
                                />
                                <p className="text-[10px] text-slate-500 break-words leading-tight">Par mesure de sécurité, la suppression d'un panneau actif nécessite votre mot de passe.</p>
                            </div>
                        )}
                    </form>
                </Modal>
            )}

            {activeDialog === 'confirm' && dialogId === c.id && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} onCancel={handleCloseLayer} />}
        </>
    );
};

/* EOF ========== [_react/clients/_clients_panneaux_card.jsx] */