/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Modale de gestion d'équipe par panneau
 * =========================================================================
 */

const { useState, useEffect } = React;

window.ClientPanelTeamModal = ({ panneau, myClientData, teamMembers, onClose, refreshData, showToast }) => {
    const [inviteEmail, setInviteEmail] = useState('');
    const [selectedTeamMember, setSelectedTeamMember] = useState('');
    const [canEdit, setCanEdit] = useState(false);
    const [chatAccess, setChatAccess] = useState('none'); 
    const [isSaving, setIsSaving] = useState(false);
    const [confirmDialog, setConfirmDialog] = useState(null);
    
    // État pour la saisie rapide du nom complet si manquant
    const [tempFullName, setTempFullName] = useState('');

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

    // COMPOSANTS GLOBAUX NETTOYÉS
    const AlertBox = window.AlertBox;
    const ConfirmModal = window.ConfirmModal;
    const Button = window.Button;
    
    const UsersIcon = window.UsersIcon || (() => null);
    const MailIcon = window.MailIcon || (() => null);
    const PlusIcon = window.PlusIcon || (() => null);
    const Trash2Icon = window.Trash2Icon || (() => null);
    const LoaderIcon = window.LoaderIcon || (() => null);
    const ShieldIcon = window.ShieldIcon || (() => null);
    const LogOutIcon = window.LogOutIcon || (() => null);
    const AlertTriangleIcon = window.AlertTriangleIcon || (() => null);
    const SaveIcon = window.SaveIcon || (() => null);

    // BINDING
    const isOwner = panneau.client_uid === myClientData.id;
    const collaborators = panneau.collaborators || [];
    
    // CORRECTION UX : Vérification de la présence du nom complet pour autoriser la collaboration
    const hasFullName = !!(myClientData.full_name && myClientData.full_name.trim());

    // Saisie rapide du nom complet directement depuis la modale
    const handleSaveFullName = async (e) => {
        e.preventDefault();
        if (!tempFullName.trim()) return;

        const payload = {
            ...myClientData,
            full_name: tempFullName
        };
        
        const d = await window.apiFetch('clients/profile/update', {
            body: payload,
            setLoading: setIsSaving,
            successMessage: "Identité enregistrée avec succès."
        });
        
        if (d) {
            if (refreshData) refreshData();
        }
    };

    const handleInvite = async (e) => {
        e.preventDefault();
        const targetEmail = selectedTeamMember || inviteEmail;
        if (!targetEmail) return;
        
        const d = await window.apiFetch('panneaux/collaborators/invite', {
            body: { panneau_id: panneau.id, email: targetEmail, can_edit: canEdit, chat_access: chatAccess },
            setLoading: setIsSaving,
            successMessage: "Invitation envoyée avec succès."
        });
        
        if (d) {
            setInviteEmail('');
            setSelectedTeamMember('');
            setCanEdit(false);
            setChatAccess('none');
            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);
                const d = await window.apiFetch('panneaux/collaborators/remove', {
                    body: { panneau_id: panneau.id, target_uid: uid },
                    setLoading: setIsSaving,
                    successMessage: "Collaborateur retiré du panneau."
                });
                if (d) refreshData();
            }
        });
    };

    const handleUpdateRights = async (uid, can_edit, chat_access) => {
        const d = await window.apiFetch('panneaux/collaborators/update', {
            body: { panneau_id: panneau.id, target_uid: uid, rights: { can_edit, chat_access } },
            setLoading: setIsSaving,
            successMessage: "Droits mis à jour avec succès."
        });
        if (d) 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 window.apiFetch('panneaux/collaborators/leave', {
                    body: { panneau_id: panneau.id },
                    setLoading: setIsSaving,
                    successMessage: "Vous avez quitté le projet."
                });
                if (d) {
                    onClose();
                    refreshData();
                }
            }
        });
    };

    return (
        <window.Modal title={`Équipe du panneau : ${panneau.name}`} type="info" onClose={onClose} preventClose={isSaving} requireConfirm={isDirty} zIndex="z-[300]">
            <div className="space-y-6">
                
                <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">
                        <div className="flex items-start gap-3">
                            <AlertTriangleIcon size={24} className="text-orange-600 shrink-0" />
                            <div>
                                <h4 className="font-black text-orange-900">Identité requise</h4>
                                <p className="text-sm text-orange-800 mt-1">
                                    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">
                            <input 
                                type="text" 
                                value={tempFullName} 
                                onChange={e => setTempFullName(e.target.value)} 
                                placeholder="Prénom et Nom" 
                                required
                                disabled={isSaving}
                                className="flex-1 border-2 border-orange-200 rounded-xl p-3 text-sm outline-none focus:border-orange-500 bg-white disabled:opacity-50"
                            />
                            <Button type="submit" variant="warningSolid" disabled={isSaving || !tempFullName.trim()} icon={isSaving ? LoaderIcon : SaveIcon} className="py-3 px-6">
                                Enregistrer
                            </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">
                        <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2"><PlusIcon size={16}/> Inviter un collaborateur</h4>
                        <form onSubmit={handleInvite} className="space-y-4">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-slate-500 uppercase block">Carnet d'adresses</label>
                                    <select value={selectedTeamMember} onChange={e => { setSelectedTeamMember(e.target.value); setInviteEmail(''); }} className="w-full border-2 border-slate-200 rounded-lg p-2.5 text-sm outline-none focus:border-blue-500 bg-white">
                                        <option value="">-- Sélectionner un contact --</option>
                                        {(teamMembers || []).map(tm => (
                                            <option key={tm.email} value={tm.email}>{tm.company} ({tm.name})</option>
                                        ))}
                                    </select>
                                </div>
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-slate-500 uppercase block">Ou adresse e-mail <span className="text-red-500">*</span></label>
                                    <input type="email" disabled={!!selectedTeamMember} value={inviteEmail} onChange={e => setInviteEmail(e.target.value)} placeholder="architecte@exemple.com" className="w-full border-2 border-slate-200 rounded-lg p-2.5 text-sm outline-none focus:border-blue-500 disabled:bg-slate-50" />
                                </div>
                            </div>
                            
                            <div className="space-y-2 pt-2 border-t border-slate-100">
                                <label className="text-xs font-bold text-slate-500 uppercase block">Droits accordés :</label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input type="checkbox" checked={canEdit} onChange={e => setCanEdit(e.target.checked)} className="w-4 h-4 accent-blue-600" />
                                    <span className="text-sm font-medium text-slate-700">Peut modifier les informations du panneau</span>
                                </label>
                                <div className="flex flex-col gap-1 pt-2">
                                    <span className="text-sm font-medium text-slate-700">Accès aux conversations avec les riverains :</span>
                                    <div className="flex gap-4 ml-6 flex-wrap">
                                        <label className="flex items-center gap-1 cursor-pointer"><input type="radio" name="chatAccess" value="none" checked={chatAccess === 'none'} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600" /> <span className="text-xs">Aucun</span></label>
                                        <label className="flex items-center gap-1 cursor-pointer"><input type="radio" name="chatAccess" value="read" checked={chatAccess === 'read'} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600" /> <span className="text-xs">Lecture seule</span></label>
                                        <label className="flex items-center gap-1 cursor-pointer"><input type="radio" name="chatAccess" value="rw" checked={chatAccess === 'rw'} onChange={e => setChatAccess(e.target.value)} className="accent-blue-600" /> <span className="text-xs">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">
                                Envoyer l'invitation
                            </Button>
                        </form>
                    </div>
                )}

                <div className="space-y-3">
                    <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2 border-b border-slate-200 pb-2"><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">
                        <div>
                            <p className="text-sm font-black text-emerald-900">{isOwner ? "Vous (Propriétaire)" : `${panneau.owner_company || 'Propriétaire'} (${panneau.owner_name || ''})`}</p>
                            <p className="text-xs text-emerald-700">{isOwner ? "Tous les droits" : "Propriétaire"}</p>
                        </div>
                        <ShieldIcon size={18} className="text-emerald-600" />
                    </div>

                    {collaborators.map(c => (
                        <div key={c.uid} className={`p-4 border rounded-xl flex flex-col gap-3 ${c.status === 'pending' ? 'bg-slate-50 border-slate-200' : 'bg-white border-slate-200 shadow-sm'}`}>
                            <div className="flex items-start justify-between">
                                <div className="min-w-0 pr-2">
                                    <p className="text-sm font-bold text-slate-800 truncate">{c.company} <span className="font-normal text-slate-500">({c.name})</span></p>
                                    <p className="text-xs text-slate-500 truncate">{c.email}</p>
                                </div>
                                {c.status === 'pending' ? (
                                    <span className="px-2 py-0.5 rounded bg-amber-100 text-amber-700 text-[10px] font-black uppercase shrink-0 shadow-sm">En attente</span>
                                ) : (
                                    <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 sm:flex-row items-start sm:items-center justify-between gap-3 pt-2 border-t border-slate-100">
                                    <div className="flex flex-col gap-2">
                                        <label className="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer font-bold">
                                            <input type="checkbox" checked={c.rights?.can_edit} onChange={e => handleUpdateRights(c.uid, e.target.checked, c.rights?.chat_access || 'none')} className="accent-blue-600 w-3 h-3"/> Édition du panneau
                                        </label>
                                        <div className="flex items-center gap-2">
                                            <span className="text-xs font-bold text-slate-600">Riverains:</span>
                                            <select value={c.rights?.chat_access || 'none'} onChange={e => handleUpdateRights(c.uid, c.rights?.can_edit || false, e.target.value)} className="text-xs border border-slate-200 rounded p-1 outline-none bg-slate-50">
                                                <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" icon={Trash2Icon} onClick={() => handleRemove(c.uid)} disabled={isSaving} title="Retirer l'accès" className="p-2 self-end sm:self-auto" />
                                </div>
                            )}
                        </div>
                    ))}

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

                    {!isOwner && (
                        <div className="pt-4 border-t border-slate-100 mt-4">
                            <Button variant="dangerSolid" icon={LogOutIcon} onClick={handleLeave} disabled={isSaving} className="w-full py-3 justify-center">
                                Quitter ce projet
                            </Button>
                        </div>
                    )}
                </div>
            </div>
            
            {confirmDialog && ConfirmModal && (
                <ConfirmModal 
                    {...confirmDialog} 
                    onCancel={() => setConfirmDialog(null)} 
                    zIndex="z-[350]" 
                />
            )}
        </window.Modal>
    );
};

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