/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Carte individuelle d'un panneau (Vue Client)
 * =========================================================================
 */

const FallbackNull = () => null;

const FallbackDataCard = ({children, className}) => (
    <div className={`bg-white rounded-3xl p-5 shadow-sm border flex flex-col gap-4 ${className}`}>
        {children}
    </div>
);

window.pano_ClientPanelCard = ({ 
    panel: c, 
    myClientData, 
    localPinned, 
    togglePin, 
    unreadMap, 
    setPreviewPanneau, 
    openLocalModal, 
    openLocalDialog, 
    setManagingPanneau, 
    setValidationErrors, 
    setConfirmDialog, 
    handleDeletePanelClick, 
    isSuspended, 
    hasNewsletterFeature, 
    hasCollabFeature, 
    hasMessagingFeature, 
    refreshData, 
    closeCurrentLayer 
}) => {
    // Récupération des icônes sécurisée
    const {
        BuildingIcon, QrCodeIcon, EyeIcon, MessageCircleIcon, 
        MessageSquareIcon, MailIcon, LockIcon, EditIcon, 
        Trash2Icon, ArchiveIcon
    } = window.pano_getIcons?.() || {};

    const PinIcon = window.pano_PinIcon || FallbackNull;
    const IconBadge = window.pano_IconBadge || FallbackNull;
    const StatusBadge = window.pano_StatusBadge || (({status}) => <span className="text-xs font-bold">{status}</span>);
    const Button = window.pano_Button || FallbackNull;
    const NotificationBadge = window.pano_NotificationBadge || FallbackNull;
    const DataCard = window.pano_DataCard || FallbackDataCard;

    // Calcul des droits et de l'état
    const isOwner = c.client_uid === myClientData.id;
    const myCollab = !isOwner ? c.collaborators?.find(col => col.uid === myClientData.id) : null;
    const canEdit = isOwner || myCollab?.rights?.can_edit;
    const canChat = isOwner || (myCollab && ['read', 'rw'].includes(myCollab.rights?.chat_access));
    const isPinned = localPinned.includes(c.id);
    
    const unreadRiverain = unreadMap[c.id]?.riverain || 0;
    const unreadGroup = unreadMap[c.id]?.group || 0;

    return (
        <DataCard className={`p-6 ${c.status === 'Actif' ? 'border-emerald-200' : 'border-slate-200'} flex flex-col relative overflow-hidden group transition-shadow hover:shadow-md`}>
            <div className="flex justify-between items-start mb-4 mt-2">
                <div className="flex items-center gap-3 min-w-0 pr-2">
                    <IconBadge icon={BuildingIcon} variant={c.status === 'Actif' ? 'success' : (c.status === 'Suspendu' || c.status === 'Attente validation' ? 'warning' : 'secondary')} size="lg" />
                    <div className="min-w-0">
                        <h3 className="font-black text-lg text-slate-800 break-words leading-tight">{c.name || 'Brouillon'}</h3>
                        <p className="text-xs text-slate-500 break-words leading-tight">{c.location || 'Localisation non définie'}</p>
                    </div>
                </div>
                <div className="flex flex-col items-end gap-2 shrink-0">
                    <div className="flex items-center gap-2">
                        {c.status === 'Actif' && c.draft_data && (
                            <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>
                        )}
                        <StatusBadge status={c.status} />
                    </div>
                    <button 
                        onClick={(e) => togglePin(c.id, e)} 
                        className={`p-1.5 rounded-full transition-colors ${isPinned ? 'bg-emerald-100 text-emerald-600 hover:bg-emerald-200' : 'bg-slate-100 text-slate-400 hover:bg-slate-200 hover:text-slate-600'}`}
                        title={isPinned ? "Désépingler" : "Épingler en haut"}
                    >
                        <PinIcon size={16} filled={isPinned} />
                    </button>
                </div>
            </div>
            
            <div className="flex-1"></div>
            
            <div className="flex flex-wrap gap-2 pt-4 border-t border-slate-100">
                {c.status === 'Actif' && (
                    <Button variant="success" icon={QrCodeIcon} onClick={() => { 
                        const livePanel = { ...c };
                        delete livePanel.draft_data; 
                        setPreviewPanneau(livePanel); 
                        openLocalModal('preview', c.id); 
                    }} className="flex-1 py-2 whitespace-nowrap bg-white" title="Voir le panneau en ligne tel qu'il apparaît aux riverains">
                        Voir
                    </Button>
                )}

                {(c.draft_data || c.status !== 'Actif') && (
                    <Button variant="info" icon={EyeIcon} onClick={() => { 
                        setPreviewPanneau(c.draft_data ? { ...c, ...c.draft_data } : c); 
                        openLocalModal('preview', c.id); 
                    }} className="flex-1 py-2 whitespace-nowrap bg-white" title={c.status === 'Actif' ? "Aperçu de vos modifications non publiées" : "Aperçu de votre brouillon de travail"}>
                        Aperçu
                    </Button>
                )}
                
                {c.status === 'Actif' && (
                    <>
                        {canChat && hasMessagingFeature && (
                            <Button variant="secondary" icon={MessageCircleIcon} onClick={() => openLocalModal('riverains_list', c.id)} className="flex-1 py-2 whitespace-nowrap relative bg-white" title="Voir les messages des riverains">
                                Riverains
                                <NotificationBadge count={unreadRiverain} className="absolute -top-2 -right-2 scale-75" />
                            </Button>
                        )}

                        {hasCollabFeature && (
                            <Button variant="secondary" icon={MessageSquareIcon} onClick={() => { 
                                const u = new URL(window.location);
                                u.searchParams.set('chat_id', 'GROUP_' + c.id);
                                window.history.pushState({ chat_id: 'GROUP_' + c.id }, '', u);
                                window.dispatchEvent(new Event('popstate'));
                            }} className="flex-1 py-2 whitespace-nowrap relative bg-white">
                                Équipe
                                <NotificationBadge count={unreadGroup} className="absolute -top-2 -right-2 scale-75" />
                            </Button>
                        )}

                        {hasNewsletterFeature && (
                            <Button variant="warning" icon={MailIcon} onClick={() => { setManagingPanneau(c); openLocalModal('newsletter', c.id); }} className="flex-1 py-2 whitespace-nowrap bg-white" title="Envoyer une information aux riverains">
                                Info riverains {c.newsletterSubscribers > 0 && `(${c.newsletterSubscribers})`}
                            </Button>
                        )}

                        {canEdit && (
                            <Button variant="purple" icon={LockIcon} onClick={() => { setManagingPanneau(c); openLocalModal('vault', c.id); }} className="flex-1 py-2 whitespace-nowrap bg-white">Coffre-fort</Button>
                        )}
                    </>
                )}

                {canEdit && !isSuspended && (
                    <Button variant={c.status === 'Suspendu' ? 'warning' : 'outline'} icon={EditIcon} onClick={() => { setManagingPanneau(c.draft_data ? { ...c, ...c.draft_data } : { ...c }); setValidationErrors([]); openLocalModal('editor', c.id); }} className="flex-1 py-2 whitespace-nowrap bg-white">
                        {c.status === 'Suspendu' ? "Corriger" : "Modifier"}
                    </Button>
                )}
                
                {canEdit && c.draft_data && !isSuspended && (
                    <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => {
                        setConfirmDialog({
                            title: "Annuler les modifications", 
                            message: "Voulez-vous annuler toutes les modifications non publiées ?", 
                            confirmText: "Annuler", 
                            isDestructive: true,
                            onConfirm: async () => {
                                await window.pano_apiFetch('panneaux', { body: { id: c.id, status: c.status, offerType: c.offerType, currentRate: c.currentRate, physicalPanels: c.physicalPanels, details: { ...c, draft_data: null } } });
                                refreshData(); closeCurrentLayer();
                            }
                        });
                        openLocalDialog('confirm');
                    }} className="p-2 shadow-none shrink-0 bg-white" title="Annuler les modifications" />
                )}

                {isOwner && c.status === 'Actif' && (
                    <Button variant="danger" shape="square" icon={ArchiveIcon} onClick={() => openLocalModal('end_life', c.id)} className="flex-1 py-2 whitespace-nowrap bg-white">
                        Clôturer / Supprimer
                    </Button>
                )}

                {isOwner && c.status !== 'Actif' && (
                    <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => handleDeletePanelClick(c)} className="p-2 shadow-none shrink-0 bg-white" title="Supprimer" />
                )}
            </div>
        </DataCard>
    );
};

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