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

const { useState } = React;

window.pano_ClientSettingsTeam = ({ data, showToast, refreshData, openLocalDialog, closeCurrentLayer, activeDialog, onClose }) => {
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

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

    // 1. - Composants et Icônes
    const { UsersIcon, Trash2Icon } = window.pano_getIcons();
    const { Button, ConfirmModal, CardGrid, DataCard, Modal } = window.pano_getComponents();

    const teamHistory = data.team || [];

    // 2. - Actions métier
    const handleRemoveGlobalCollaborator = (targetEmail) => {
        setConfirmConfig({
            title: "Supprimer le contact",
            message: "Voulez-vous supprimer définitivement ce contact de votre carnet d'adresses et de votre historique ?",
            confirmText: "Supprimer",
            cancelText: "Annuler",
            isDestructive: true,
            onConfirm: async () => {
                // ZÉRO-DETTE : Dépilement propre via le retour arrière de l'historique
                closeCurrentLayer(); 
                const d = await safeFetch('clients/team/remove', {
                    body: { email: targetEmail },
                    setLoading: setIsSaving,
                    successMessage: "Contact supprimé de l'historique."
                });
                
                if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
                
                if (d && refreshData) refreshData();
            }
        });
        openLocalDialog('confirm_team');
    };

    // 3. - Rendu UI
    return (
        <Modal 
            title="Carnet d'adresses global" 
            type="info" 
            onClose={onClose} 
            maxWidth="max-w-3xl"
            actions={(close) => (
                <Button variant="secondary" onClick={close} className="w-full py-3 justify-center text-xs">
                    Fermer
                </Button>
            )}
        >
            <div className="space-y-6 min-w-0 w-full overflow-x-hidden">
                
                <div className="bg-blue-50 border border-blue-200 p-4 rounded-xl text-blue-800 text-sm break-words leading-relaxed">
                    Cet onglet liste l'intégralité des collaborateurs passés ou présents sur tous vos panneaux. 
                    <strong> La gestion des accès actifs s'effectue individuellement pour chaque panneau depuis l'onglet "Mes panneaux" (bouton "Équipe").</strong>
                </div>

                <div className="flex justify-between items-center min-w-0 w-full border-b border-slate-100 pb-2">
                    <h4 className="font-bold text-slate-700 text-sm break-words">Contacts enregistrés</h4>
                    <span className="text-xs font-bold bg-slate-100 text-slate-600 px-3 py-1 rounded-lg border border-slate-200 shadow-sm shrink-0">
                        {window.pano_formatPlural(teamHistory.length, 'contact', 'contacts')}
                    </span>
                </div>

                {teamHistory.length === 0 ? (
                    <div className="p-12 text-center text-slate-500 border border-slate-200 border-dashed rounded-2xl bg-slate-50 min-w-0">
                        {UsersIcon && <UsersIcon size={48} className="mx-auto mb-4 opacity-50" />}
                        <p className="font-medium break-words">Aucun collaborateur dans votre historique.</p>
                        <p className="text-xs mt-2 break-words">Invitez des collaborateurs depuis la gestion de vos panneaux.</p>
                    </div>
                ) : (
                    <CardGrid minWidth="240px" className="min-w-0 w-full">
                        {/* CORRECTION SÉCURITÉ REACT : Deep Copy + Vérification des undefined pour empêcher le crash localeCompare */}
                        {[...teamHistory].sort((a,b) => (a.company || '').localeCompare(b.company || '')).map((member, i) => (
                            <DataCard key={i} variant="slate" className="p-4 gap-3 transition hover:shadow-md min-w-0">
                                <div className="flex justify-between items-start min-w-0">
                                    <div className="min-w-0 pr-2 flex-1">
                                        <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Société / Contact</span>
                                        <p className="text-sm font-black text-slate-800 break-words leading-tight">{member.company}</p>
                                        <p className="text-xs text-slate-500 break-words leading-tight">{member.name}</p>
                                    </div>
                                    <div className="shrink-0 text-right">
                                        <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">Panneaux</span>
                                        {member.active_panels > 0 ? (
                                            <span className="bg-emerald-100 text-emerald-800 text-[10px] font-black uppercase px-2 py-1 rounded-md shadow-sm border border-emerald-200 inline-block">
                                                {window.pano_formatPlural(member.active_panels, 'Actif', 'Actifs')}
                                            </span>
                                        ) : (
                                            <span className="bg-slate-100 text-slate-500 text-[10px] font-bold uppercase px-2 py-1 rounded-md border border-slate-200 inline-block">
                                                Aucun
                                            </span>
                                        )}
                                    </div>
                                </div>
                                
                                <div className="pt-2 border-t border-slate-200 min-w-0">
                                    <span className="text-[10px] uppercase tracking-widest text-slate-400 font-bold block mb-1">E-mail</span>
                                    <span className="text-sm text-slate-600 break-words leading-tight block">{member.email}</span>
                                </div>
                                
                                <div className="flex justify-end gap-2 pt-3 mt-auto border-t border-slate-200 min-w-0">
                                    <Button 
                                        variant="danger" 
                                        shape="round"
                                        icon={Trash2Icon} 
                                        onClick={() => handleRemoveGlobalCollaborator(member.email)} 
                                        disabled={isSaving || member.active_panels > 0}
                                        title={member.active_panels > 0 ? "Impossible de supprimer un contact ayant des accès actifs." : "Supprimer de l'historique"}
                                        className="p-2 shadow-none bg-white hover:bg-red-50" 
                                    />
                                </div>
                            </DataCard>
                        ))}
                    </CardGrid>
                )}
            </div>

            {/* Sécurité anti boucle infinie sur l'annulation */}
            {activeDialog === 'confirm_team' && confirmConfig && ConfirmModal && (
                <ConfirmModal 
                    {...confirmConfig} 
                    onCancel={() => {
                        setConfirmConfig(null);
                        closeCurrentLayer();
                    }} 
                />
            )}
        </Modal>
    );
};

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