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

const { useState, useEffect, useMemo } = React;

// 1. - MODALE : GESTION DE L'ÉQUIPE DU PANNEAU
window.pano_ClientPanelTeamModal = ({ panneau, myClientData, teamMembers, onClose, refreshData, showToast }) => {
    
    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // 1.1 - États locaux
    const [inviteEmail, setInviteEmail] = useState('');
    const [selectedTeamMember, setSelectedTeamMember] = useState('');
    const [canEdit, setCanEdit] = useState(false);
    const [chatAccess, setChatAccess] = useState('none'); 
    const [lockedFields, setLockedFields] = useState([]);
    const [isSaving, setIsSaving] = useState(false);
    const [confirmDialog, setConfirmDialog] = useState(null);
    const [tempFullName, setTempFullName] = useState('');
    const [optimisticCollabs, setOptimisticCollabs] = useState(panneau.collaborators || []);

    const isDirty = inviteEmail.trim() !== '' || selectedTeamMember !== '' || canEdit || chatAccess !== 'none' || lockedFields.length > 0 || tempFullName.trim() !== '';

    // 1.2 - Composants et Icônes
    const { 
        UsersIcon, MailIcon, PlusIcon, Trash2Icon, LoaderIcon, 
        ShieldIcon, LogOutIcon, AlertTriangleIcon, SaveIcon, LockIcon, CheckCircleIcon, RefreshCwIcon 
    } = window.pano_getIcons();
    
    const { AlertBox, ConfirmModal, Button, Modal } = window.pano_getComponents();

    // 2. - Logique métier et permissions
    useEffect(() => {
        setOptimisticCollabs(panneau.collaborators || []);
    }, [panneau.collaborators]);

    const isOwner = panneau.client_uid === myClientData.id;
    const isMe = (uid) => uid === myClientData.id || uid === myClientData.email_hash;
    
    // CORRECTION SÉCURITÉ : Application de la fonction `isMe` pour autoriser le vrai UID
    const visibleCollaborators = isOwner 
        ? optimisticCollabs 
        : optimisticCollabs.filter(c => isMe(c.uid));

    const hasFullName = !!(myClientData.full_name && myClientData.full_name.trim());

    // Filtrage dynamique : on retire les contacts déjà invités
    const availableTeamMembers = useMemo(() => {
        return (teamMembers || []).filter(tm => 
            !optimisticCollabs.some(c => c.email.toLowerCase() === tm.email.toLowerCase())
        );
    }, [teamMembers, optimisticCollabs]);

    // Formatage propre du nom du propriétaire "Société (Nom)"
    const myCollabRecord = !isOwner ? optimisticCollabs.find(c => isMe(c.uid)) : null;
    const ownerCompanyName = isOwner ? myClientData.name : (panneau.owner_company || myCollabRecord?.inviter_company || 'Propriétaire');
    const ownerPersonName = isOwner ? myClientData.full_name : (panneau.owner_name || myCollabRecord?.inviter_name || '');
    const formattedOwnerName = ownerPersonName ? `${ownerCompanyName} (${ownerPersonName})` : ownerCompanyName;
    const ownerDisplayName = isOwner ? `Vous - ${formattedOwnerName}` : formattedOwnerName;

    const AVAILABLE_FIELDS = [
        { id: 'name', label: 'Nom du chantier' }, { id: 'location', label: 'Lieu' },
        { id: 'maitreOuvrage', label: "Maître d'ouvrage" }, { id: 'permitNumber', label: 'N° de permis' },
        { id: 'description', label: 'Description' }, { id: 'promoterLink', label: 'Lien promoteur' },
        { id: 'emergencyPhone', label: 'N° d\'urgence' }, { id: 'noiseSchedule', label: 'Horaires' },
        { id: 'intervenants', label: 'Intervenants' }, { id: 'lots', label: 'Lots' }, { id: 'pdfId', label: 'Arrêté (PDF)' }
    ];

    const handleSaveFullName = async (e) => {
        e.preventDefault();
        if (!tempFullName.trim()) return;

        const payload = {
            ...myClientData,
            full_name: tempFullName
        };
        
        const d = await safeFetch('clients/profile/update', {
            body: payload,
            setLoading: setIsSaving,
            successMessage: "Identité enregistrée avec succès."
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d) {
            setTempFullName(''); // Reset après succès
            if (refreshData) refreshData();
        }
    };

    const handleInvite = async (e) => {
        e.preventDefault();
        const targetEmail = (selectedTeamMember || inviteEmail).trim();
        if (!targetEmail) return;

        // VERROU ANTI-DOUBLON
        if (optimisticCollabs.some(c => c.email.toLowerCase() === targetEmail.toLowerCase())) {
            if (showToast) showToast("Ce contact fait déjà partie de l'équipe ou a déjà été invité.", "warning");
            return;
        }
        
        const tempUid = 'temp_' + Date.now();
        setOptimisticCollabs(prev => [...prev, {
            uid: tempUid,
            email: targetEmail,
            company: 'En cours...',
            name: 'Invitation',
            status: 'pending',
            rights: { can_edit: canEdit, chat_access: chatAccess, locked_fields: lockedFields }
        }]);

        const d = await safeFetch('panneaux/collaborators/invite', {
            body: { panneau_id: panneau.id, email: targetEmail, can_edit: canEdit, chat_access: chatAccess, locked_fields: lockedFields },
            setLoading: setIsSaving,
            successMessage: "Invitation envoyée avec succès."
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d) {
            setInviteEmail('');
            setSelectedTeamMember('');
            setCanEdit(false);
            setChatAccess('none');
            setLockedFields([]);
            if (refreshData) refreshData();
        } else {
            setOptimisticCollabs(prev => prev.filter(c => c.uid !== tempUid));
        }
    };

    const handleResendInvite = async (collab) => {
        const d = await safeFetch('panneaux/collaborators/invite', {
            body: { 
                panneau_id: panneau.id, 
                email: collab.email, 
                can_edit: collab.rights?.can_edit || false, 
                chat_access: collab.rights?.chat_access || 'none', 
                locked_fields: collab.rights?.locked_fields || [],
                resend: true
            },
            setLoading: setIsSaving,
            successMessage: "L'invitation a été renvoyée avec succès."
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d && refreshData) refreshData();
    };

    const handleRemove = (uid) => {
        setConfirmDialog({
            title: "Retirer l'accès",
            message: "Êtes-vous sûr de vouloir retirer ce collaborateur du projet ?",
            confirmText: "Oui, retirer",
            isDestructive: true,
            onConfirm: async () => {
                setConfirmDialog(null);
                setOptimisticCollabs(prev => prev.filter(c => c.uid !== uid));

                const d = await safeFetch('panneaux/collaborators/remove', {
                    body: { panneau_id: panneau.id, target_uid: uid },
                    setLoading: setIsSaving,
                    successMessage: "Collaborateur retiré du panneau."
                });
                
                if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
                
                if (d && refreshData) refreshData();
            }
        });
    };

    const handleUpdateRights = async (uid, can_edit, chat_access, locked_fields) => {
        setOptimisticCollabs(prev => prev.map(c => 
            c.uid === uid ? { ...c, rights: { can_edit, chat_access, locked_fields } } : c
        ));

        const d = await safeFetch('panneaux/collaborators/update', {
            body: { panneau_id: panneau.id, target_uid: uid, rights: { can_edit, chat_access, locked_fields } },
            setLoading: setIsSaving,
            successMessage: "Droits mis à jour avec succès."
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d && refreshData) refreshData();
    };

    const handleLeave = () => {
        setConfirmDialog({
            title: "Quitter le projet",
            message: "Êtes-vous sûr de vouloir quitter ce projet ? Vous perdrez l'accès à ce panneau et à son groupe de discussion.",
            confirmText: "Oui, quitter",
            isDestructive: true,
            onConfirm: async () => {
                setConfirmDialog(null);
                const d = await safeFetch('panneaux/collaborators/leave', {
                    body: { panneau_id: panneau.id },
                    setLoading: setIsSaving,
                    successMessage: "Vous avez quitté le projet."
                });
                
                if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
                
                if (d) {
                    onClose();
                    if (refreshData) refreshData();
                }
            }
        });
    };

    // 3. - Rendu UI
    return (
        <>
            <Modal 
                title={`Équipe du panneau : ${panneau.name}`} 
                type="info" 
                onClose={onClose} 
                
                // Smart Props pour l'auto-verrouillage
                isSaving={isSaving} 
                isDirty={isDirty} 
                zIndex="z-[300]"

                // Custom Actions car pas de bouton 'Enregistrer' global
                actions={(close) => (
                    <Button variant="secondary" onClick={close} disabled={isSaving} className="w-full py-3 justify-center text-xs shadow-sm">
                        Fermer
                    </Button>
                )}
            >
                <div className="space-y-6 min-w-0 w-full overflow-x-hidden">
                    
                    <AlertBox type="info" icon={UsersIcon}>
                        Gérez les accès à ce panneau. Chaque membre invité aura accès au groupe de discussion intégré.
                    </AlertBox>

                    {!hasFullName && isOwner && (
                        <div className="bg-orange-50 p-5 rounded-xl border border-orange-200 shadow-sm space-y-4 animate-in fade-in min-w-0 w-full">
                            <div className="flex items-start gap-3 min-w-0">
                                <AlertTriangleIcon size={24} className="text-orange-600 shrink-0" />
                                <div className="min-w-0">
                                    <h4 className="font-black text-orange-900 break-words leading-tight">Identité requise</h4>
                                    <p className="text-sm text-orange-800 mt-1 break-words leading-relaxed">
                                        Pour inviter des collaborateurs, vous devez renseigner votre nom complet afin qu'ils puissent vous identifier dans l'e-mail d'invitation.
                                    </p>
                                </div>
                            </div>
                            <form onSubmit={handleSaveFullName} className="flex flex-col sm:flex-row gap-3 pt-2 min-w-0 w-full">
                                <input 
                                    type="text" 
                                    value={tempFullName} 
                                    onChange={e => setTempFullName(e.target.value)} 
                                    placeholder="Prénom et Nom" 
                                    required
                                    disabled={isSaving}
                                    className="flex-1 min-w-0 border-2 border-orange-200 rounded-xl p-3 text-sm outline-none focus:border-orange-500 bg-white disabled:opacity-50 font-bold text-slate-800"
                                />
                                <Button 
                                    type="submit" 
                                    variant={tempFullName.trim() ? "warningSolid" : "secondary"} 
                                    disabled={isSaving || !tempFullName.trim()} 
                                    icon={isSaving ? LoaderIcon : (tempFullName.trim() ? SaveIcon : CheckCircleIcon)} 
                                    className="py-3 px-6 shrink-0 uppercase tracking-widest text-xs shadow-md justify-center"
                                >
                                    {isSaving ? 'Enregistrement...' : (tempFullName.trim() ? 'Enregistrer' : 'À jour')}
                                </Button>
                            </form>
                        </div>
                    )}

                    {isOwner && hasFullName && (
                        <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm space-y-4 animate-in fade-in min-w-0 w-full">
                            <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2 break-words leading-tight"><PlusIcon size={16}/> Inviter un collaborateur</h4>
                            <form onSubmit={handleInvite} className="space-y-4 min-w-0 w-full">
                                <div className="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4 min-w-0 w-full">
                                    <div className="space-y-1 min-w-0 w-full">
                                        <label className="text-xs font-bold text-slate-500 uppercase block break-words leading-tight">Carnet d'adresses</label>
                                        <select value={selectedTeamMember} onChange={e => { setSelectedTeamMember(e.target.value); setInviteEmail(''); }} className="w-full border-2 border-slate-200 rounded-xl p-2.5 text-sm outline-none focus:border-blue-500 bg-white font-bold text-slate-700 min-w-0" disabled={isSaving}>
                                            <option value="">-- Sélectionner un contact --</option>
                                            {availableTeamMembers.map(tm => (
                                                <option key={tm.email} value={tm.email}>{tm.company} ({tm.name})</option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="space-y-1 min-w-0 w-full">
                                        <label className="text-xs font-bold text-slate-500 uppercase block break-words leading-tight">Ou adresse e-mail <span className="text-red-500">*</span></label>
                                        <input type="email" disabled={!!selectedTeamMember || isSaving} value={inviteEmail} onChange={e => setInviteEmail(e.target.value)} placeholder="architecte@exemple.com" className="w-full min-w-0 border-2 border-slate-200 rounded-xl p-2.5 text-sm outline-none focus:border-blue-500 disabled:bg-slate-50 font-bold text-slate-800" />
                                    </div>
                                </div>
                                
                                <div className="space-y-3 pt-2 border-t border-slate-100 min-w-0 w-full">
                                    <label className="text-xs font-bold text-slate-500 uppercase block break-words leading-tight">Droits accordés :</label>
                                    <label className="flex items-center gap-2 cursor-pointer select-none min-w-0">
                                        <input type="checkbox" checked={canEdit} disabled={isSaving} onChange={e => setCanEdit(e.target.checked)} className="w-4 h-4 accent-blue-600 shrink-0" />
                                        <span className="text-sm font-medium text-slate-700 break-words leading-tight">Peut modifier les informations du panneau</span>
                                    </label>
                                    
                                    {canEdit && (
                                        <div className="pl-6 space-y-2 animate-in fade-in slide-in-from-top-2 min-w-0 w-full">
                                            <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest break-words leading-tight block">Verrouiller ces champs (Lecture seule) :</span>
                                            <div className="flex flex-wrap gap-2">
                                                {AVAILABLE_FIELDS.map(f => (
                                                    <div 
                                                        role="button" 
                                                        tabIndex={0} 
                                                        key={f.id} 
                                                        onClick={() => !isSaving && setLockedFields(prev => prev.includes(f.id) ? prev.filter(x => x !== f.id) : [...prev, f.id])} 
                                                        className={`px-3 py-1.5 rounded-lg text-xs font-bold transition border ${isSaving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${lockedFields.includes(f.id) ? 'bg-red-50 text-red-600 border-red-200' : 'bg-slate-50 text-slate-500 border-slate-200 hover:bg-slate-100'}`}
                                                    >
                                                        {lockedFields.includes(f.id) && <LockIcon size={12} className="inline mr-1"/>}{f.label}
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    <div className="flex flex-col gap-1 pt-2 min-w-0 w-full">
                                        <span className="text-sm font-medium text-slate-700 break-words leading-tight">Accès aux conversations avec les riverains :</span>
                                        <div className="flex gap-4 sm:ml-6 flex-col sm:flex-row min-w-0">
                                            <label className="flex items-center gap-1 cursor-pointer select-none min-w-0"><input type="radio" name="chatAccess" value="none" checked={chatAccess === 'none'} disabled={isSaving} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600 shrink-0" /> <span className="text-xs font-bold text-slate-600 break-words leading-tight">Aucun</span></label>
                                            <label className="flex items-center gap-1 cursor-pointer select-none min-w-0"><input type="radio" name="chatAccess" value="read" checked={chatAccess === 'read'} disabled={isSaving} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600 shrink-0" /> <span className="text-xs font-bold text-slate-600 break-words leading-tight">Lecture seule</span></label>
                                            <label className="flex items-center gap-1 cursor-pointer select-none min-w-0"><input type="radio" name="chatAccess" value="rw" checked={chatAccess === 'rw'} disabled={isSaving} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600 shrink-0" /> <span className="text-xs font-bold text-slate-600 break-words leading-tight">Lecture et Écriture</span></label>
                                        </div>
                                    </div>
                                </div>
                                <Button type="submit" variant="infoSolid" disabled={isSaving || (!inviteEmail && !selectedTeamMember)} icon={isSaving ? LoaderIcon : MailIcon} className="w-full py-3 uppercase tracking-widest justify-center shadow-md text-xs">
                                    Envoyer l'invitation
                                </Button>
                            </form>
                        </div>
                    )}

                    <div className="space-y-3 min-w-0 w-full">
                        <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2 border-b border-slate-200 pb-2 break-words leading-tight"><UsersIcon size={16}/> Membres du projet</h4>
                        
                        <div className="p-3 border border-emerald-200 rounded-xl bg-emerald-50 flex items-center justify-between min-w-0">
                            <div className="min-w-0 pr-2">
                                <p className="text-sm font-black text-emerald-900 break-words leading-tight">{ownerDisplayName}</p>
                                <p className="text-xs text-emerald-700 font-bold break-words leading-tight mt-0.5">{isOwner ? "Tous les droits" : "Propriétaire"}</p>
                            </div>
                            <ShieldIcon size={18} className="text-emerald-600 shadow-sm shrink-0" />
                        </div>

                        {visibleCollaborators.map(c => {
                            const isPending = c.status === 'pending';
                            const isTemp = c.uid.startsWith('temp_');
                            const currentLocked = c.rights?.locked_fields || [];
                            
                            return (
                                <div key={c.uid} className={`p-4 border rounded-xl flex flex-col gap-3 min-w-0 ${isPending ? 'bg-slate-50 border-slate-200' : 'bg-white border-slate-200 shadow-sm'}`}>
                                    <div className="flex items-start justify-between gap-2 min-w-0">
                                        <div className="min-w-0 flex-1 pr-2">
                                            <p className="text-sm font-bold text-slate-800 break-words leading-tight">{c.company} <span className="font-normal text-slate-500">({c.name})</span></p>
                                        </div>
                                        {isPending ? (
                                            <div className="flex flex-col items-end gap-1.5 shrink-0">
                                                <span className="px-2 py-0.5 rounded bg-amber-100 text-amber-700 text-[10px] font-black uppercase shadow-sm">
                                                    {isTemp ? <LoaderIcon size={10} className="animate-spin inline mr-1"/> : null} En attente
                                                </span>
                                                {!isTemp && (
                                                    <Button 
                                                        variant="secondary" 
                                                        icon={RefreshCwIcon} 
                                                        onClick={() => handleResendInvite(c)} 
                                                        disabled={isSaving} 
                                                        className="py-1 px-2 text-[9px] uppercase tracking-wider bg-white shadow-sm"
                                                        title="Renvoyer l'e-mail d'invitation"
                                                    >
                                                        Renvoyer
                                                    </Button>
                                                )}
                                            </div>
                                        ) : (
                                            <span className="px-2 py-0.5 rounded bg-emerald-100 text-emerald-700 text-[10px] font-black uppercase shrink-0 shadow-sm">Actif</span>
                                        )}
                                    </div>
                                    {isOwner && (
                                        <div className="flex flex-col gap-3 pt-3 border-t border-slate-100 min-w-0">
                                            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 min-w-0">
                                                <div className="flex flex-col gap-2 min-w-0 flex-1">
                                                    <label className="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer font-bold select-none min-w-0">
                                                        <input 
                                                            type="checkbox" 
                                                            checked={!!c.rights?.can_edit} 
                                                            onChange={e => handleUpdateRights(c.uid, e.target.checked, c.rights?.chat_access || 'none', currentLocked)} 
                                                            disabled={isTemp || isSaving} 
                                                            className="accent-blue-600 w-3 h-3 disabled:opacity-50 shrink-0"
                                                        /> 
                                                        <span className="break-words leading-tight">Édition du panneau</span>
                                                    </label>
                                                    <div className="flex items-center gap-2 min-w-0">
                                                        <span className="text-xs font-bold text-slate-600 shrink-0">Riverains:</span>
                                                        <select 
                                                            value={c.rights?.chat_access || 'none'} 
                                                            onChange={e => handleUpdateRights(c.uid, c.rights?.can_edit || false, e.target.value, currentLocked)} 
                                                            disabled={isTemp || isSaving} 
                                                            className="text-xs min-w-0 border border-slate-200 rounded-xl p-1 outline-none bg-slate-50 disabled:opacity-50 font-bold text-slate-700 flex-1"
                                                        >
                                                            <option value="none">Aucun accès</option>
                                                            <option value="read">Lecture seule</option>
                                                            <option value="rw">Lecture et Écriture</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <Button variant="danger" shape="round" icon={Trash2Icon} onClick={() => handleRemove(c.uid)} disabled={isSaving || isTemp} title="Retirer l'accès" className="shadow-none self-end sm:self-auto shrink-0" />
                                            </div>

                                            {!!c.rights?.can_edit && (
                                                <div className="pl-5 pt-2 border-l-2 border-slate-100 min-w-0">
                                                    <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest block mb-2 break-words leading-tight">Champs verrouillés (Lecture seule) :</span>
                                                    <div className="flex flex-wrap gap-2">
                                                        {AVAILABLE_FIELDS.map(f => {
                                                            const isLocked = currentLocked.includes(f.id);
                                                            return (
                                                                <div 
                                                                    role="button" 
                                                                    tabIndex={0} 
                                                                    key={f.id} 
                                                                    onClick={() => {
                                                                        if (isTemp || isSaving) return;
                                                                        const newLocked = isLocked ? currentLocked.filter(x => x !== f.id) : [...currentLocked, f.id];
                                                                        handleUpdateRights(c.uid, c.rights?.can_edit, c.rights?.chat_access, newLocked);
                                                                    }} 
                                                                    className={`px-2 py-1 rounded text-[10px] font-bold transition border ${isTemp || isSaving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${isLocked ? 'bg-red-50 text-red-600 border-red-200' : 'bg-white text-slate-500 border-slate-200 hover:bg-slate-50'}`}
                                                                >
                                                                    {isLocked && <LockIcon size={10} className="inline mr-1 shrink-0"/>}{f.label}
                                                                </div>
                                                            );
                                                        })}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>
                            );
                        })}

                        {visibleCollaborators.length === 0 && (
                            <p className="text-sm text-slate-500 text-center italic py-4 break-words">Aucun collaborateur invité sur ce projet.</p>
                        )}

                        {!isOwner && (
                            <div className="pt-4 border-t border-slate-100 mt-4 min-w-0">
                                <Button variant="dangerSolid" icon={LogOutIcon} onClick={handleLeave} disabled={isSaving} className="w-full py-3 justify-center uppercase font-bold text-xs tracking-wider shadow-md">
                                    Quitter ce projet
                                </Button>
                            </div>
                        )}
                    </div>
                </div>
            </Modal>

            {confirmDialog && ConfirmModal && (
                <ConfirmModal 
                    {...confirmDialog} 
                    onCancel={() => setConfirmDialog(null)} 
                />
            )}
        </>
    );
};

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