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

window.pano_ClientSettingsProfile = ({ myClientData, data, showToast, refreshData, openLocalDialog, closeCurrentLayer, activeDialog, setHasUnsavedChanges }) => {
    const { useState, useEffect } = React;

    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    const [isSaving, setIsSaving] = useState(false);
    const [userHasEdited, setUserHasEdited] = useState(false);
    const [emailChangeConfig, setEmailChangeConfig] = useState(null);
    const [tempFullName, setTempFullName] = useState('');

    const adminSettings = data.settings || {};
    const optCollab = adminSettings.opt_collab || 'active';
    const optMessaging = adminSettings.opt_messaging || 'active';
    const optNewsletter = adminSettings.opt_newsletter || 'active';

    const getInitialOption = (adminOpt, savedVal) => {
        if (savedVal !== undefined) return savedVal;
        if (adminOpt === 'optional_on') return true; 
        return false; 
    };

    // 1. - Initialisation des données (Mémorisées pour comparaison fluide)
    const initialProfileData = React.useMemo(() => ({
        name: myClientData.name || '',
        full_name: myClientData.full_name || '',
        email: myClientData.email || '',
        phone: myClientData.phone || '',
        address: myClientData.address || '',
        siret: myClientData.siret || '',
        tva: myClientData.tva || ''
    }), [myClientData.name, myClientData.full_name, myClientData.email, myClientData.phone, myClientData.address, myClientData.siret, myClientData.tva]);

    const initialClientOptions = React.useMemo(() => {
        let parsedOpts = {};
        try {
            if (myClientData.uiMode && myClientData.uiMode.startsWith('{')) {
                parsedOpts = JSON.parse(myClientData.uiMode);
            }
        } catch(e) {}

        return {
            collab: getInitialOption(optCollab, parsedOpts.collab),
            messaging: getInitialOption(optMessaging, parsedOpts.messaging),
            newsletter: getInitialOption(optNewsletter, parsedOpts.newsletter),
            has_tva: parsedOpts.has_tva !== false, // Vrai par défaut
            
            simp_opt_description: getInitialOption(adminSettings.simp_opt_description || 'active', parsedOpts.simp_opt_description),
            simp_opt_image: getInitialOption(adminSettings.simp_opt_image || 'active', parsedOpts.simp_opt_image),
            simp_opt_theme: getInitialOption(adminSettings.simp_opt_theme || 'active', parsedOpts.simp_opt_theme),
            simp_opt_link: getInitialOption(adminSettings.simp_opt_link || 'active', parsedOpts.simp_opt_link),
            simp_opt_emergency: getInitialOption(adminSettings.simp_opt_emergency || 'active', parsedOpts.simp_opt_emergency),
            simp_opt_schedule: getInitialOption(adminSettings.simp_opt_schedule || 'active', parsedOpts.simp_opt_schedule),
            simp_opt_hide_intervenants: getInitialOption(adminSettings.simp_opt_hide_intervenants || 'disabled', parsedOpts.simp_opt_hide_intervenants),
            simp_opt_hide_lots: getInitialOption(adminSettings.simp_opt_hide_lots || 'disabled', parsedOpts.simp_opt_hide_lots),
            simp_opt_hide_legal: getInitialOption(adminSettings.simp_opt_hide_legal || 'disabled', parsedOpts.simp_opt_hide_legal)
        };
    }, [myClientData.uiMode, optCollab, optMessaging, optNewsletter, adminSettings]);

    const [profileData, setProfileData] = useState(initialProfileData);
    const [clientOptions, setClientOptions] = useState(initialClientOptions);

    // États de sécurité (Ex-onglet Sécurité)
    const [passwordData, setPasswordData] = useState({ current: '', new: '', confirm: '' });
    
    const [twoFactorSetup, setTwoFactorSetup] = useState(null); 
    const [twoFactorCode, setTwoFactorCode] = useState('');
    const [twoFactorSecret, setTwoFactorSecret] = useState('');
    const [twoFactorQr, setTwoFactorQr] = useState('');

    const updateProfile = (key, val) => {
        setProfileData(prev => ({...prev, [key]: val}));
        setUserHasEdited(true);
    };

    const updateOption = (key, val) => {
        setClientOptions(prev => ({...prev, [key]: val}));
        setUserHasEdited(true);
    };

    const isFormModified = JSON.stringify(profileData) !== JSON.stringify(initialProfileData) || JSON.stringify(clientOptions) !== JSON.stringify(initialClientOptions);

    // 1.1 - Détection des modifications pour l'avertissement de sauvegarde
    useEffect(() => {
        if (setHasUnsavedChanges) {
            setHasUnsavedChanges(isFormModified);
        }
    }, [isFormModified, setHasUnsavedChanges]);

    // 1.2 - Synchronisation douce Zéro-Effacement
    useEffect(() => {
        if (!userHasEdited) {
            setProfileData(initialProfileData);
            setClientOptions(initialClientOptions);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [initialProfileData, initialClientOptions]); 

    // 2. - Import des dépendances UI
    const {
        FileTextIcon, SaveIcon, LoaderIcon, SearchIcon, SettingsIcon, RefreshCwIcon, EditIcon, UserIcon, PhoneIcon,
        LockIcon, ShieldCheckIcon, ShieldAlertIcon, QrCodeIcon, MailIcon, CopyIcon, EyeIcon, HardDriveIcon, FolderIcon, CreditCardIcon
    } = window.pano_getIcons();

    const {
        FormInput, FormTextarea, Modal, Button, Toggle, TextLogo, CardGrid,
        NativeQRCode, PasswordPromptModal
    } = window.pano_getComponents();

    const hasCollaborations = (data.panneaux || []).some(p => 
        (p.client_uid === myClientData.id && p.collaborators && p.collaborators.length > 0) || 
        (p.client_uid !== myClientData.id)
    );

    const hasOptionalFeatures = [optCollab, optMessaging, optNewsletter].some(opt => opt === 'optional_on' || opt === 'optional_off');
    
    const simpKeys = ['simp_opt_description', 'simp_opt_image', 'simp_opt_theme', 'simp_opt_link', 'simp_opt_emergency', 'simp_opt_schedule', 'simp_opt_hide_intervenants', 'simp_opt_hide_lots', 'simp_opt_hide_legal'];
    const hasOptionalSimp = simpKeys.some(k => adminSettings[k] === 'optional_on' || adminSettings[k] === 'optional_off');

    // 3. - Logique métier
    const handleProfileSave = async (e) => {
        e.preventDefault();
        
        if (!profileData.name.trim()) {
            showToast("Le nom de la société est obligatoire.", "error");
            return;
        }

        if (hasCollaborations && !profileData.full_name.trim()) {
            showToast("Vous ne pouvez pas effacer votre nom complet car vous participez à des projets collaboratifs.", "error");
            return;
        }

        if (clientOptions.has_tva !== false && (!profileData.tva || !profileData.tva.trim())) {
            showToast("Le numéro de TVA intracommunautaire est obligatoire si vous y êtes assujetti.", "error");
            return;
        }
        
        const payload = {
            ...profileData,
            uiMode: JSON.stringify(clientOptions)
        };

        const d = await safeFetch('clients/profile/update', { 
            body: payload, 
            setLoading: setIsSaving, 
            successMessage: "Profil et options mis à jour avec succès." 
        });
        
        if (!isMounted.current) return; 

        if (d) {
            setUserHasEdited(false);
            if (setHasUnsavedChanges) setHasUnsavedChanges(false);
            refreshData();
        }
    };

    const handleTvaToggle = (checked) => {
        updateOption('has_tva', checked);
        if (checked && profileData.siret && profileData.siret.length >= 9 && !profileData.tva) {
            const siren = profileData.siret.substring(0, 9);
            const tvaKey = (12 + 3 * (parseInt(siren, 10) % 97)) % 97;
            updateProfile('tva', `FR${tvaKey.toString().padStart(2, '0')}${siren}`);
        } else if (!checked) {
            updateProfile('tva', '');
        }
    };

    const handleSiretLookup = async () => {
        if (!profileData.siret || profileData.siret.length < 9) {
            showToast("Veuillez saisir un SIREN (9 chiffres) ou SIRET (14 chiffres) valide.", "error");
            return;
        }

        const d = await safeFetch('systeme/siret_lookup', { 
            body: { siret: profileData.siret }, 
            setLoading: setIsSaving,
            successMessage: "Informations récupérées avec succès !"
        });

        if (!isMounted.current) return; 

        if (d && d.data) {
            const fetchedAddress = d.data.address || d.data.adresse || d.data.geo_adresse || '';
            const newProfile = {
                ...profileData,
                name: d.data.name || profileData.name,
                address: fetchedAddress || profileData.address,
                siret: d.data.siret || profileData.siret
            };
            if (clientOptions.has_tva !== false && d.data.tva) {
                newProfile.tva = d.data.tva;
            }
            setProfileData(newProfile);
            setUserHasEdited(true);
        }
    };

    const handleEmailChangeRequest = async (e) => {
        e.preventDefault();
        if (!emailChangeConfig.newEmail.trim() || !emailChangeConfig.newEmail.includes('@')) {
            showToast("Veuillez saisir un e-mail valide.", "error");
            return;
        }
        const d = await safeFetch('clients/profile/request_email', {
            body: { email: emailChangeConfig.newEmail },
            setLoading: setIsSaving,
            successMessage: "Un code de vérification a été envoyé à cette nouvelle adresse."
        });

        if (!isMounted.current) return; 

        if (d) {
            setEmailChangeConfig({ ...emailChangeConfig, step: 'verify' });
        }
    };

    const handleEmailChangeVerify = async (e) => {
        e.preventDefault();
        if (emailChangeConfig.code.length !== 6) return;
        const d = await safeFetch('clients/profile/update_email', {
            body: { code: emailChangeConfig.code },
            setLoading: setIsSaving,
            successMessage: "Votre adresse e-mail a été mise à jour avec succès. Veuillez vous reconnecter."
        });

        if (!isMounted.current) return; 

        if (d) {
            setEmailChangeConfig(null);
            setTimeout(() => window.location.href = '?', 1500);
        }
    };

    const handlePasswordChange = async (e) => {
        e.preventDefault();
        if (passwordData.new !== passwordData.confirm) {
            showToast("Les nouveaux mots de passe ne correspondent pas.", "error");
            return;
        }
        if (passwordData.new.length < 8) {
            showToast("Le mot de passe doit contenir au moins 8 caractères.", "error");
            return;
        }

        const d = await safeFetch('clients/password/update', {
            body: { oldPassword: passwordData.current, password: passwordData.new },
            setLoading: setIsSaving,
            successMessage: "Mot de passe mis à jour avec succès."
        });

        if (!isMounted.current) return; 

        if (d) setPasswordData({ current: '', new: '', confirm: '' });
    };

    const start2FASetup = async (type) => {
        if (type === 'email') {
            setTwoFactorSetup('email');
            return;
        }
        
        const d = await safeFetch('clients/profile/setup_totp', { 
            setLoading: setIsSaving 
        });
        
        if (!isMounted.current) return; 

        if (d) {
            setTwoFactorSecret(d.data.secret);
            setTwoFactorQr(d.data.otpauth);
            setTwoFactorSetup('authenticator');
        }
    };

    const confirm2FASetup = async (e) => {
        e.preventDefault();
        if (twoFactorSetup === 'authenticator' && twoFactorCode.length !== 6) return;
        
        const method = twoFactorSetup === 'authenticator' ? 'totp' : 'email';
        
        const d = await safeFetch('clients/profile/update_2fa', {
            body: { method: method },
            setLoading: setIsSaving,
            successMessage: "Authentification à double facteur activée !"
        });

        if (!isMounted.current) return; 

        if (d) {
            setTwoFactorSetup(null);
            setTwoFactorCode('');
            refreshData();
        }
    };

    const disable2FA = () => openLocalDialog('disable_2fa_pwd');
    const handleCancel2FA = () => { setTwoFactorSetup(null); setTwoFactorCode(''); setTwoFactorSecret(''); setTwoFactorQr(''); };

    const renderOption = (id, label, desc, adminStatus, clientValue, toggleKey) => {
        if (adminStatus === 'active' || adminStatus === 'disabled') return null;
        
        return (
            <div className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-slate-50 border border-slate-200 rounded-xl shadow-sm animate-in fade-in gap-3 min-w-0">
                <div className="min-w-0 flex-1">
                    <span className="font-bold text-slate-700 text-sm block break-words leading-tight mb-1">{label}</span>
                    <span className="text-xs text-slate-500 break-words leading-relaxed">{desc}</span>
                </div>
                <div className="shrink-0 self-end sm:self-auto">
                    <Toggle checked={clientValue} onChange={v => updateOption(toggleKey, v)} />
                </div>
            </div>
        );
    };

    // --- CALCUL DU STOCKAGE ---
    const baseQuotaMb = parseInt(adminSettings.quota_global_mb || 5000, 10);
    const extraQuotaGb = parseInt(myClientData.storage_extra_gb || 0, 10);
    const extraPriceMo = parseFloat(myClientData.storage_price_mo || 0);
    const totalQuotaMb = baseQuotaMb + (extraQuotaGb * 1024);
    const usedStorageMb = parseFloat(myClientData.storage_used_mb || 0);
    
    let storagePercent = 0;
    if (totalQuotaMb > 0) {
        storagePercent = Math.min(100, Math.max(0, (usedStorageMb / totalQuotaMb) * 100));
    }

    let progressColorClass = 'bg-emerald-500';
    if (storagePercent > 90) {
        progressColorClass = 'bg-red-600';
    } else if (storagePercent > 80) {
        progressColorClass = 'bg-orange-500';
    }

    return (
        <div className="space-y-8 max-w-4xl animate-in fade-in pb-24 relative min-w-0 w-full">
            <form onSubmit={handleProfileSave} className="space-y-8 min-w-0 w-full">
                
                {/* BLOC 1 : IDENTITÉ ET CONTACT */}
                <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-6 min-w-0 w-full">
                    <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                        <UserIcon size={20} className="text-emerald-600 shrink-0"/> Identité et contact
                    </h3>
                    
                    <div className="bg-blue-50 border border-blue-200 p-4 rounded-xl text-blue-800 text-sm break-words leading-relaxed">
                        Le nom de la société est obligatoire. Cette information sera utilisée pour la facturation et apparaîtra lors de vos invitations collaboratives sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition ml-1 whitespace-nowrap"><TextLogo className="text-sm" /></a>.
                    </div>

                    <CardGrid minWidth="200px" className="gap-6 min-w-0 w-full">
                        <FormInput label="Société" value={profileData.name} onChange={e => updateProfile('name', e.target.value)} required disabled={isSaving} className="min-w-0 w-full" />
                        
                        <div className="relative min-w-0 w-full">
                            <FormInput 
                                label="Nom complet (Prénom NOM)" 
                                value={profileData.full_name} 
                                onChange={e => updateProfile('full_name', e.target.value)} 
                                required={hasCollaborations}
                                disabled={isSaving || hasCollaborations}
                                className="min-w-0 w-full"
                                hint={!hasCollaborations ? "Obligatoire uniquement pour inviter ou rejoindre des collaborateurs." : "Cliquez pour modifier."} 
                            />
                            {hasCollaborations && !isSaving && (
                                <div
                                    className="absolute inset-0 z-10 cursor-pointer"
                                    onClick={(e) => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        setTempFullName(profileData.full_name);
                                        openLocalDialog('locked_fullname_info');
                                    }}
                                    title="Modifier le nom"
                                />
                            )}
                        </div>
                    </CardGrid>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 min-w-0 w-full items-start">
                        <div className="space-y-2 min-w-0 w-full">
                            <label className="text-xs font-bold text-slate-500 uppercase block break-words">Adresse e-mail de connexion</label>
                            <div className="flex flex-col sm:flex-row gap-3 min-w-0 w-full">
                                <input 
                                    type="email" 
                                    value={profileData.email} 
                                    disabled 
                                    className="w-full border-2 border-slate-200 bg-slate-50 text-slate-500 rounded-xl p-3 text-sm outline-none font-bold cursor-not-allowed min-w-0" 
                                />
                                <Button 
                                    variant="secondary" 
                                    type="button" 
                                    icon={EditIcon}
                                    onClick={() => setEmailChangeConfig({ step: 'request', newEmail: '', code: '' })} 
                                    disabled={isSaving} 
                                    className="w-full sm:w-auto py-3 px-6 shrink-0 justify-center border-none shadow-sm hover:bg-slate-200"
                                >
                                    Modifier l'e-mail
                                </Button>
                            </div>
                            <p className="text-xs text-slate-400 mt-1 break-words">Une vérification de sécurité sera exigée pour valider votre nouvelle adresse e-mail.</p>
                        </div>

                        <FormInput label="Téléphone" type="tel" value={profileData.phone} onChange={e => updateProfile('phone', e.target.value)} disabled={isSaving} className="min-w-0 w-full" icon={<PhoneIcon size={14}/>} />
                    </div>
                </div>

                {/* BLOC 2 : INFORMATIONS DE FACTURATION */}
                <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-6 min-w-0 w-full">
                    <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                        <FileTextIcon size={20} className="text-blue-600 shrink-0"/> Informations de facturation
                    </h3>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 items-start min-w-0 w-full">
                        <div className="space-y-1 w-full min-w-0">
                            <label className="text-xs font-bold text-slate-500 uppercase block break-words">N° SIRET</label>
                            <div className="flex flex-col sm:flex-row gap-2 min-w-0 w-full">
                                <input 
                                    type="text" 
                                    value={profileData.siret} 
                                    onChange={e => {
                                        const cleanSiret = e.target.value.replace(/\D/g, '').substring(0, 14);
                                        updateProfile('siret', cleanSiret);
                                    }} 
                                    placeholder="14 chiffres" 
                                    className="flex-1 min-w-0 border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold disabled:bg-slate-50 disabled:opacity-50" 
                                    maxLength={128} 
                                    disabled={isSaving}
                                />
                                <Button variant="info" icon={SearchIcon} type="button" onClick={handleSiretLookup} disabled={isSaving || profileData.siret.length < 9} className="w-full sm:w-auto px-4 py-3 shrink-0 justify-center">
                                    Rechercher
                                </Button>
                            </div>
                        </div>

                        <div className="space-y-4 w-full min-w-0">
                            <div onClick={() => !isSaving && handleTvaToggle(clientOptions.has_tva !== false ? false : true)} className={`flex items-center justify-between gap-3 bg-slate-50 border border-slate-100 p-4 rounded-xl shadow-sm min-w-0 ${isSaving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:border-emerald-300 transition'}`}>
                                <span className="text-sm font-bold text-slate-700 min-w-0 break-words leading-tight">Soumis à la TVA</span>
                                {Toggle && <div className="shrink-0"><Toggle checked={clientOptions.has_tva !== false} onChange={handleTvaToggle} variant="success" disabled={isSaving} /></div>}
                            </div>
                            {clientOptions.has_tva !== false && FormInput && (
                                <FormInput label="TVA intracommunautaire" required disabled={isSaving} value={profileData.tva} onChange={e => updateProfile('tva', e.target.value)} className="uppercase font-bold min-w-0 w-full" />
                            )}
                        </div>
                    </div>
                    
                    <FormTextarea label="Adresse de facturation / siège social" value={profileData.address} disabled={isSaving} onChange={e => updateProfile('address', e.target.value)} rows={3} className="min-w-0 w-full" />
                </div>

                {/* BLOC : ESPACE DE STOCKAGE (NOUVEAU) */}
                <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-6 min-w-0 w-full">
                    <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                        <HardDriveIcon size={20} className="text-indigo-600 shrink-0"/> Espace de stockage global
                    </h3>
                    
                    <div className="space-y-4 min-w-0 w-full">
                        <div className="flex justify-between items-end mb-1 min-w-0">
                            <span className="text-sm font-bold text-slate-700 break-words">Consommation</span>
                            <span className="text-xs font-bold text-slate-500 shrink-0">{usedStorageMb.toFixed(2)} Mo / {totalQuotaMb} Mo</span>
                        </div>
                        
                        <div className="w-full bg-slate-100 h-4 rounded-full overflow-hidden shadow-inner border border-slate-200">
                            <div 
                                className={`h-full transition-all duration-500 ${progressColorClass}`} 
                                style={{ width: `${storagePercent}%` }}
                            ></div>
                        </div>

                        {storagePercent > 90 ? (
                            <p className="text-xs text-red-600 font-medium leading-relaxed break-words">
                                Vous êtes presque à court d'espace ! Supprimez des fichiers ou modifiez votre forfait pour éviter le blocage de vos téléchargements.
                            </p>
                        ) : storagePercent > 80 ? (
                            <p className="text-xs text-orange-600 font-medium leading-relaxed break-words">
                                Votre espace de stockage se remplit. Pensez à faire du tri.
                            </p>
                        ) : null}

                        {extraQuotaGb > 0 && (
                            <div className="bg-slate-50 border border-slate-200 p-3 rounded-lg flex items-center gap-2 mt-2">
                                <CreditCardIcon size={16} className="text-slate-500 shrink-0" />
                                <span className="text-xs font-medium text-slate-700 break-words">
                                    Forfait additionnel actif : <strong className="text-slate-900">+{extraQuotaGb} Go</strong> pour <strong className="text-slate-900">{extraPriceMo} € HT / mois</strong>.
                                </span>
                            </div>
                        )}

                        <div className="flex flex-col sm:flex-row gap-3 pt-2">
                            <Button variant="secondary" icon={FolderIcon} type="button" onClick={() => openLocalDialog('file_manager')} className="flex-1 justify-center py-3 text-sm">
                                Gérer mes fichiers
                            </Button>
                            <Button variant="primary" icon={HardDriveIcon} type="button" onClick={() => openLocalDialog('storage_plan')} className="flex-1 justify-center py-3 text-sm uppercase tracking-widest">
                                Modifier mon forfait
                            </Button>
                        </div>
                    </div>
                </div>

                {/* BLOC 3 : FONCTIONNALITÉS DU COMPTE */}
                {hasOptionalFeatures && (
                    <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4 min-w-0 w-full">
                        <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                            <SettingsIcon size={20} className="text-indigo-600 shrink-0"/> Fonctionnalités du compte
                        </h3>
                        <p className="text-sm text-slate-500 break-words leading-relaxed">Gérez les options additionnelles de votre espace et de vos panneaux.</p>
                        <div className="grid grid-cols-1 gap-4 min-w-0 w-full">
                            {renderOption('opt_collab', 'Travail en collaboration', 'Inviter des membres sur vos panneaux.', optCollab, clientOptions.collab, 'collab')}
                            {renderOption('opt_messaging', 'Messagerie des riverains', 'Recevoir et répondre aux messages du voisinage.', optMessaging, clientOptions.messaging, 'messaging')}
                            {renderOption('opt_newsletter', 'Info riverains', 'Informer les riverains abonnés des événements.', optNewsletter, clientOptions.newsletter, 'newsletter')}
                        </div>
                    </div>
                )}

                {/* BLOC 4 : SIMPLIFICATION DE L'ÉDITEUR */}
                {hasOptionalSimp && (
                    <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4 min-w-0 w-full">
                        <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                            <EditIcon size={20} className="text-emerald-600 shrink-0"/> Simplification de l'éditeur
                        </h3>
                        <p className="text-sm text-slate-500 break-words leading-relaxed">Personnalisez les champs et onglets affichés lors de la création ou de la modification de vos panneaux.</p>
                        
                        <div className="space-y-4 min-w-0 w-full">
                            {['simp_opt_description', 'simp_opt_image', 'simp_opt_theme', 'simp_opt_link', 'simp_opt_emergency', 'simp_opt_schedule'].some(k => adminSettings[k] === 'optional_on' || adminSettings[k] === 'optional_off') && (
                                <div className="space-y-3">
                                    <h4 className="font-bold text-slate-700 text-xs uppercase tracking-widest mt-2 mb-2">Champs de l'éditeur</h4>
                                    {renderOption('simp_opt_description', 'Description des travaux', 'Afficher le champ de description détaillée.', adminSettings.simp_opt_description || 'active', clientOptions.simp_opt_description, 'simp_opt_description')}
                                    {renderOption('simp_opt_image', 'Vue du projet (Image)', 'Permettre l\'upload d\'une image d\'aperçu.', adminSettings.simp_opt_image || 'active', clientOptions.simp_opt_image, 'simp_opt_image')}
                                    {renderOption('simp_opt_theme', 'Couleur du thème', 'Permettre la personnalisation des couleurs.', adminSettings.simp_opt_theme || 'active', clientOptions.simp_opt_theme, 'simp_opt_theme')}
                                    {renderOption('simp_opt_link', 'Lien vers le promoteur', 'Afficher le champ de lien web additionnel.', adminSettings.simp_opt_link || 'active', clientOptions.simp_opt_link, 'simp_opt_link')}
                                    {renderOption('simp_opt_emergency', 'Téléphone d\'urgence', 'Afficher le champ de contact d\'urgence.', adminSettings.simp_opt_emergency || 'active', clientOptions.simp_opt_emergency, 'simp_opt_emergency')}
                                    {renderOption('simp_opt_schedule', 'Horaires de nuisances', 'Afficher les horaires de travaux bruyants.', adminSettings.simp_opt_schedule || 'active', clientOptions.simp_opt_schedule, 'simp_opt_schedule')}
                                </div>
                            )}

                            {['simp_opt_hide_intervenants', 'simp_opt_hide_lots', 'simp_opt_hide_legal'].some(k => adminSettings[k] === 'optional_on' || adminSettings[k] === 'optional_off') && (
                                <div className="space-y-3 pt-2">
                                    <h4 className="font-bold text-slate-700 text-xs uppercase tracking-widest mt-2 mb-2 flex items-center gap-2"><EyeIcon size={14}/> Masquage d'onglets</h4>
                                    {renderOption('simp_opt_hide_intervenants', 'Masquer l\'onglet Intervenants', 'Désactiver la gestion des intervenants.', adminSettings.simp_opt_hide_intervenants || 'disabled', clientOptions.simp_opt_hide_intervenants, 'simp_opt_hide_intervenants')}
                                    {renderOption('simp_opt_hide_lots', 'Masquer l\'onglet Lots de travaux', 'Désactiver la gestion des lots.', adminSettings.simp_opt_hide_lots || 'disabled', clientOptions.simp_opt_hide_lots, 'simp_opt_hide_lots')}
                                    {renderOption('simp_opt_hide_legal', 'Masquer l\'affichage de l\'Arrêté (Public)', 'Cacher le document légal au public.', adminSettings.simp_opt_hide_legal || 'disabled', clientOptions.simp_opt_hide_legal, 'simp_opt_hide_legal')}
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* BOUTON DE SAUVEGARDE PROFIL */}
                <div className="fixed bottom-0 left-0 lg:left-[var(--sidebar-width)] right-0 bg-white/90 backdrop-blur-md border-t border-slate-200 p-4 sm:p-6 z-[100] shadow-[0_-10px_20px_rgba(0,0,0,0.05)] flex justify-center">
                    <Button type="submit" variant="dark" disabled={isSaving || !isFormModified} icon={isSaving ? LoaderIcon : SaveIcon} className="w-full sm:w-auto px-8 py-3.5 uppercase tracking-widest justify-center text-sm">
                        {isSaving ? 'Enregistrement...' : 'Enregistrer les modifications'}
                    </Button>
                </div>
            </form>

            {/* BLOC 5 : MODIFIER LE MOT DE PASSE */}
            <form onSubmit={handlePasswordChange} className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4 min-w-0 w-full">
                <h3 className="font-black text-slate-800 text-lg flex flex-wrap items-center gap-2 border-b border-slate-100 pb-3 break-words">
                    <LockIcon size={20} className="text-orange-600 shrink-0"/> Modifier le mot de passe
                </h3>
                
                <FormInput label="Mot de passe actuel" type="password" disabled={isSaving} value={passwordData.current} onChange={e => setPasswordData({...passwordData, current: e.target.value})} required className="min-w-0 w-full" />
                <CardGrid minWidth="200px" className="gap-4 min-w-0 w-full">
                    <FormInput label="Nouveau mot de passe" type="password" disabled={isSaving} value={passwordData.new} onChange={e => setPasswordData({...passwordData, new: e.target.value})} required className="min-w-0 w-full" />
                    <FormInput label="Confirmer le nouveau" type="password" disabled={isSaving} value={passwordData.confirm} onChange={e => setPasswordData({...passwordData, confirm: e.target.value})} required className="min-w-0 w-full" />
                </CardGrid>
                
                <div className="pt-2">
                    <Button type="submit" variant="dark" disabled={isSaving || !passwordData.current || !passwordData.new} className="w-full sm:w-auto py-3 px-8 uppercase tracking-widest text-sm justify-center">
                        {isSaving ? 'Mise à jour...' : 'Mettre à jour le mot de passe'}
                    </Button>
                </div>
            </form>

            {/* BLOC 6 : AUTHENTIFICATION À DOUBLE FACTEUR */}
            <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm space-y-4 min-w-0 w-full">
                <div className="flex flex-col sm:flex-row justify-between items-start gap-3 border-b border-slate-100 pb-3 min-w-0">
                    <div className="min-w-0 flex-1">
                        <h3 className="font-black text-slate-800 text-lg flex items-center gap-2 break-words">
                            <ShieldCheckIcon size={20} className={`shrink-0 ${myClientData.twoFactorEnabled ? "text-emerald-600" : "text-slate-400"}`}/> 
                            Authentification à double facteur
                        </h3>
                        <p className="text-sm text-slate-500 mt-1 break-words leading-relaxed">Sécurisez l'accès à vos panneaux et à votre coffre-fort légal sur <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition whitespace-nowrap"><TextLogo className="text-sm" /></a>.</p>
                    </div>
                    {myClientData.twoFactorEnabled && (
                        <span className="bg-emerald-100 text-emerald-800 text-xs font-black uppercase px-3 py-1 rounded-lg shrink-0">Activé</span>
                    )}
                </div>

                {myClientData.twoFactorEnabled ? (
                    <div className="space-y-4 animate-in fade-in min-w-0 w-full">
                        <div className="bg-emerald-50 border border-emerald-200 p-4 rounded-xl flex items-start gap-3 min-w-0">
                            <ShieldCheckIcon size={24} className="text-emerald-600 shrink-0"/>
                            <p className="text-sm text-emerald-800 font-medium min-w-0 leading-relaxed break-words">Votre compte est protégé par la double authentification. Vous devez saisir un code unique à chaque connexion depuis un nouvel appareil.</p>
                        </div>
                        <Button variant="danger" icon={ShieldAlertIcon} onClick={disable2FA} disabled={isSaving} className="w-full sm:w-auto py-3 px-6 justify-center">
                            Désactiver la 2FA
                        </Button>
                    </div>
                ) : (
                    <div className="animate-in fade-in min-w-0 w-full">
                        {!twoFactorSetup ? (
                            <CardGrid minWidth="200px" className="pt-2 min-w-0 w-full">
                                <div role="button" tabIndex={0} className={`border border-slate-200 p-4 rounded-xl transition min-w-0 ${isSaving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:border-blue-400 hover:bg-blue-50'}`} onClick={() => !isSaving && start2FASetup('authenticator')}>
                                    <QrCodeIcon size={24} className="text-blue-600 mb-2"/>
                                    <h4 className="font-bold text-slate-800 break-words leading-tight">Application (recommandé)</h4>
                                    <p className="text-xs text-slate-500 mt-1 break-words leading-relaxed">Utilisez Google Authenticator ou Authy pour générer des codes hors-ligne.</p>
                                </div>
                                <div role="button" tabIndex={0} className={`border border-slate-200 p-4 rounded-xl transition min-w-0 ${isSaving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:border-blue-400 hover:bg-blue-50'}`} onClick={() => !isSaving && start2FASetup('email')}>
                                    <MailIcon size={24} className="text-blue-600 mb-2"/>
                                    <h4 className="font-bold text-slate-800 break-words leading-tight">Par e-mail</h4>
                                    <p className="text-xs text-slate-500 mt-1 break-words leading-relaxed">Recevez un code de sécurité par e-mail à chaque connexion.</p>
                                </div>
                            </CardGrid>
                        ) : (
                            <form onSubmit={confirm2FASetup} className="space-y-4 bg-slate-50 p-4 rounded-xl border border-slate-200 animate-in slide-in-from-top-4 min-w-0 w-full">
                                <h4 className="font-black text-slate-800 break-words leading-tight">Configuration {twoFactorSetup === 'email' ? 'par e-mail' : 'via application'}</h4>
                                
                                {twoFactorSetup === 'authenticator' && (
                                    <div className="flex flex-col items-center p-4 bg-white rounded-xl border border-slate-200 space-y-4 min-w-0 w-full">
                                        <p className="text-sm text-center text-slate-600 font-medium break-words leading-relaxed">Scannez ce QR Code avec votre application d'authentification :</p>
                                        <div className="w-48 h-48 border border-slate-100 rounded-lg shadow-sm flex items-center justify-center p-2 bg-white shrink-0">
                                            {NativeQRCode ? <NativeQRCode value={twoFactorQr} size={176} /> : <QrCodeIcon size={48} className="text-slate-300"/>}
                                        </div>
                                        <div className="w-full min-w-0">
                                            <p className="text-xs text-slate-500 font-bold uppercase text-center mb-1 break-words">Ou saisissez la clé manuellement :</p>
                                            <div className="flex gap-2 w-full min-w-0">
                                                <input type="text" value={twoFactorSecret} readOnly className="flex-1 min-w-0 border border-slate-200 rounded-xl p-2 text-xs sm:text-sm text-center font-mono bg-slate-50 outline-none" />
                                                <Button variant="secondary" shape="square" type="button" onClick={() => { navigator.clipboard.writeText(twoFactorSecret); showToast("Clé copiée", "success"); }} className="shadow-none border-transparent hover:bg-slate-200 shrink-0" icon={CopyIcon} title="Copier la clé" />
                                            </div>
                                        </div>
                                    </div>
                                )}
                                
                                {twoFactorSetup === 'email' && (
                                    <p className="text-sm text-slate-600 bg-white p-3 rounded-lg border border-slate-200 font-medium break-words leading-relaxed">
                                        Vous allez recevoir un code de vérification à l'adresse e-mail de votre compte pour chaque connexion.
                                    </p>
                                )}

                                {twoFactorSetup === 'authenticator' && (
                                    <div className="space-y-2 min-w-0 w-full">
                                        <label className="text-xs font-bold text-slate-500 uppercase block break-words leading-relaxed">Saisissez le code à 6 chiffres (Optionnel mais recommandé pour vérifier la configuration)</label>
                                        <input type="text" value={twoFactorCode} disabled={isSaving} onChange={e => setTwoFactorCode(e.target.value.replace(/[^0-9]/g, '').slice(0,6))} placeholder="000000" className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-blue-500 outline-none transition font-black text-center text-xl sm:text-2xl tracking-[0.2em] sm:tracking-widest disabled:opacity-50 min-w-0" />
                                    </div>
                                )}
                                
                                <div className="flex gap-3 min-w-0 w-full">
                                    <Button variant="secondary" type="button" onClick={handleCancel2FA} disabled={isSaving} className="flex-1 py-3 text-sm justify-center">Annuler</Button>
                                    <Button variant="primary" type="submit" disabled={isSaving || (twoFactorSetup === 'authenticator' && twoFactorCode.length > 0 && twoFactorCode.length !== 6)} className="flex-1 py-3 text-sm justify-center uppercase tracking-widest text-center">Activer</Button>
                                </div>
                            </form>
                        )}
                    </div>
                )}
            </div>

            {/* MODALES EXTERNES */}
            {emailChangeConfig && Modal && (
                <Modal 
                    title="Modifier l'adresse e-mail" 
                    onClose={() => setEmailChangeConfig(null)} 
                    preventClose={isSaving} 
                    actions={(close) => 
                        emailChangeConfig.step === 'request' ? (
                            <>
                                <Button variant="secondary" type="button" onClick={close} disabled={isSaving} className="flex-1 py-3 justify-center">Annuler</Button>
                                <Button type="submit" form="email-request-form" variant="primary" disabled={isSaving || !emailChangeConfig.newEmail} icon={isSaving ? LoaderIcon : null} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">Envoyer le code</Button>
                            </>
                        ) : (
                            <Button type="submit" form="email-verify-form" variant="primary" disabled={isSaving || emailChangeConfig.code.length !== 6} icon={isSaving ? LoaderIcon : null} className="w-full py-4 uppercase tracking-widest justify-center shadow-md text-xs">Valider l'e-mail</Button>
                        )
                    }
                >
                    {emailChangeConfig.step === 'request' ? (
                        <form id="email-request-form" onSubmit={handleEmailChangeRequest} className="space-y-4">
                            <p className="text-sm text-slate-600 break-words leading-relaxed">Saisissez votre nouvelle adresse e-mail. Un code de vérification y sera envoyé pour confirmer qu'elle vous appartient bien.</p>
                            <input 
                                type="email" 
                                value={emailChangeConfig.newEmail} 
                                onChange={e => setEmailChangeConfig({...emailChangeConfig, newEmail: e.target.value})} 
                                placeholder="Nouvelle adresse e-mail" 
                                required 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition font-bold min-w-0" 
                                autoFocus 
                            />
                        </form>
                    ) : (
                        <form id="email-verify-form" onSubmit={handleEmailChangeVerify} className="space-y-4">
                            <p className="text-sm text-slate-600 break-words leading-relaxed">Saisissez le code à 6 chiffres envoyé à <strong className="break-all">{emailChangeConfig.newEmail}</strong>.</p>
                            <input 
                                type="text" 
                                value={emailChangeConfig.code} 
                                onChange={e => setEmailChangeConfig({...emailChangeConfig, code: e.target.value.replace(/\D/g, '').slice(0, 6)})} 
                                placeholder="000000" 
                                required 
                                className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-emerald-500 outline-none transition text-center text-2xl tracking-[0.2em] font-black min-w-0" 
                                autoFocus 
                            />
                            <div className="flex justify-between items-center mt-3 pt-3 border-t border-slate-100 min-w-0">
                                <div role="button" tabIndex={0} onClick={handleEmailChangeRequest} className={`text-xs font-bold text-emerald-600 hover:text-emerald-700 transition flex items-center gap-1 cursor-pointer shrink-0 ${isSaving ? 'opacity-50 pointer-events-none' : ''}`}>
                                    {RefreshCwIcon && <RefreshCwIcon size={12}/>} Renvoyer
                                </div>
                                <div role="button" tabIndex={0} onClick={() => setEmailChangeConfig(null)} className={`text-xs font-bold text-slate-500 hover:text-slate-800 transition cursor-pointer shrink-0 ${isSaving ? 'opacity-50 pointer-events-none' : ''}`}>
                                    Annuler
                                </div>
                            </div>
                        </form>
                    )}
                </Modal>
            )}

            {activeDialog === 'disable_2fa_pwd' && PasswordPromptModal && (
                <PasswordPromptModal
                    title="Désactiver la 2FA"
                    desc="Pour confirmer la désactivation de l'authentification à double facteur et prouver votre identité, veuillez saisir votre mot de passe :"
                    onConfirm={async (password) => {
                        const d = await safeFetch('clients/profile/update_2fa', {
                            body: { method: 'none', password: password },
                            setLoading: setIsSaving,
                            successMessage: "Authentification à double facteur désactivée."
                        });
                        if (!isMounted.current) return; 
                        if (d) {
                            closeCurrentLayer();
                            refreshData();
                        }
                    }}
                    onCancel={closeCurrentLayer}
                    isSaving={isSaving}
                />
            )}

            {activeDialog === 'locked_fullname_info' && Modal && (
                <Modal 
                    title="Modifier votre nom" 
                    type="info" 
                    onClose={closeCurrentLayer} 
                    actions={(close) => (
                        <>
                            <Button variant="secondary" type="button" onClick={close} className="flex-1 py-3 justify-center">Annuler</Button>
                            <Button type="submit" form="name-form" variant="primary" disabled={!tempFullName.trim()} className="flex-[2] py-3 uppercase tracking-widest justify-center shadow-md text-xs">Valider</Button>
                        </>
                    )}
                >
                    <form id="name-form" onSubmit={(e) => {
                        e.preventDefault();
                        if (tempFullName.trim()) {
                            updateProfile('full_name', tempFullName);
                            closeCurrentLayer();
                        }
                    }} className="space-y-4 pb-2">
                        <div className="text-center">
                            <div className="mx-auto w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mb-4 shrink-0">
                                <UserIcon size={32} />
                            </div>
                            <p className="text-slate-600 font-medium leading-relaxed break-words text-sm">
                                Vous pouvez modifier votre nom, mais vous ne pouvez pas l'effacer complètement car vous participez à des projets collaboratifs.
                            </p>
                        </div>
                        
                        <div className="pt-2">
                            <FormInput 
                                label="Nouveau nom complet" 
                                value={tempFullName} 
                                onChange={e => setTempFullName(e.target.value)} 
                                required 
                                autoFocus
                            />
                        </div>
                    </form>
                </Modal>
            )}
        </div>
    );
};

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