/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Paramètres du compte client - Sous-onglet : Carnet d'adresses (Équipe)
 * =========================================================================
 */

const FallbackNull = () => null;

const FallbackButton = ({ children, onClick, className, disabled, title, type = "button" }) => (
    <button type={type} onClick={onClick} className={className} disabled={disabled} title={title}>
        {children}
    </button>
);

const FallbackCardGrid = ({children, className}) => (
    <div className={`grid gap-4 ${className}`}>{children}</div>
);

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

window.pano_ClientSettingsTeam = ({ data, showToast, refreshData, openLocalDialog, closeCurrentLayer, activeDialog }) => {
    const { useState } = React;

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

    const { UsersIcon, Trash2Icon } = window.pano_getIcons();

    const Button = window.pano_Button || FallbackButton;
    const ConfirmModal = window.pano_ConfirmModal || FallbackNull;
    const CardGrid = window.pano_CardGrid || FallbackCardGrid;
    const DataCard = window.pano_DataCard || FallbackDataCard;

    const teamHistory = data.team || [];

    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 () => {
                closeCurrentLayer();
                const d = await window.pano_apiFetch('clients/team/remove', {
                    body: { email: targetEmail },
                    setLoading: setIsSaving,
                    successMessage: "Contact supprimé de l'historique."
                });
                if (d && refreshData) refreshData();
            }
        });
        openLocalDialog('confirm_team');
    };

    return (
        <div className="space-y-6 max-w-4xl animate-in fade-in">
            <div className="bg-blue-50 border border-blue-200 p-4 rounded-xl text-blue-800 text-sm">
                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 "Collaborateurs").</strong>
            </div>

            <div className="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden flex flex-col">
                <div className="p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50 shrink-0">
                    <h3 className="font-black text-slate-800 text-lg flex items-center gap-2">
                        {UsersIcon && <UsersIcon size={20} className="text-blue-600"/>} Carnet d'adresses global
                    </h3>
                    <span className="text-xs font-bold bg-slate-200 text-slate-600 px-3 py-1 rounded-lg">
                        {teamHistory.length} contact(s)
                    </span>
                </div>

                {teamHistory.length === 0 ? (
                    <div className="p-12 text-center text-slate-500">
                        {UsersIcon && <UsersIcon size={48} className="mx-auto mb-4 opacity-50" />}
                        <p className="font-medium">Aucun collaborateur dans votre historique.</p>
                        <p className="text-xs mt-2">Invitez des collaborateurs depuis la gestion de vos panneaux.</p>
                    </div>
                ) : (
                    <CardGrid minWidth="240px" className="p-4">
                        {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">
                                <div className="flex justify-between items-start">
                                    <div className="min-w-0 pr-2">
                                        <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">{member.active_panels} Actif(s)</span>
                                        ) : (
                                            <span className="bg-slate-100 text-slate-500 text-[10px] font-bold uppercase px-2 py-1 rounded-md border border-slate-200">Aucun</span>
                                        )}
                                    </div>
                                </div>
                                
                                <div className="pt-2 border-t border-slate-200">
                                    <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">
                                    <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>

            {activeDialog === 'confirm_team' && confirmConfig && ConfirmModal && (
                <ConfirmModal 
                    {...confirmConfig} 
                    onCancel={() => {
                        setConfirmConfig(null);
                        closeCurrentLayer();
                    }} 
                    zIndex="z-[350]" 
                />
            )}
        </div>
    );
};

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