/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Composant : Paramètres du compte client (Onglet "Mon compte")
 * =========================================================================
 */

const { useState, useEffect, useRef } = React;

window.ClientAccountTab = ({ 
    myClientData, 
    data, 
    isCollaborator, 
    uiMode, 
    showToast, 
    refreshData, 
    setArchiveConfig,
    openTeamManage 
}) => {
    const { 
        Building, Lock, ShieldCheck, Mail, Users, Bell, Power, 
        AlertTriangle, Download, Trash2, CheckCircle, Loader, Zap, X, FileText, RefreshCw 
    } = window;

    const [isSaving, setIsSaving] = useState(false);
    
    // États locaux des formulaires
    const [profileData, setProfileData] = useState({ type_client: 'entreprise', employees_gt_5: false, name: '', address: '', siret: '', tva: '', monthlyReport: 0, two_factor_method: 'none' });
    const [hasTva, setHasTva] = useState(true);
    const [passwordData, setPasswordData] = useState({ oldPassword: '', newPassword: '' });
    const [emailChangeData, setEmailChangeData] = useState({ step: 'input', email: '', code: '' });
    const [totpSetupData, setTotpSetupData] = useState(null);
    const [pushEnabled, setPushEnabled] = useState(localStorage.getItem('eco_push_enabled') === 'true' && window.Notification?.permission === 'granted');
    
    // États des modales locales
    const [showPushTutorial, setShowPushTutorial] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [promptDialog, setPromptDialog] = useState(null);
    const [legalModal, setLegalModal] = useState(null);

    const profileLoadedRef = useRef(false);

    useEffect(() => {
        if (myClientData.id && !profileLoadedRef.current) {
            const isTvaExempt = myClientData.tva === 'NON_ASSUJETTI';
            setHasTva(!isTvaExempt);
            
            setProfileData({
                type_client: myClientData.type_client || 'entreprise',
                employees_gt_5: myClientData.employees_gt_5 == 1 || myClientData.employees_gt_5 === true,
                name: myClientData.name || '', address: myClientData.address || '',
                siret: myClientData.siret || '', tva: isTvaExempt ? '' : (myClientData.tva || ''),
                monthlyReport: myClientData.monthlyReport || 0,
                two_factor_method: myClientData.two_factor_method || 'none'
            });
            profileLoadedRef.current = true;
        }
    }, [myClientData]);

    const allSimpOptionsActive = data.settings?.simp_opt_description === '1' && data.settings?.simp_opt_image === '1' && data.settings?.simp_opt_theme === '1' && data.settings?.simp_opt_link === '1' && data.settings?.simp_opt_emergency === '1' && data.settings?.simp_opt_schedule === '1';
    const isAdvancedMode = uiMode === 'professionnel' || allSimpOptionsActive;

    // --- LOGIQUE MÉTIER ---

    const handleAutoFill = () => {
        setPromptDialog({
            title: "Saisie automatique", message: "Saisissez votre numéro SIRET (14 chiffres) ou SIREN (9 chiffres) :", placeholder: "N° SIREN ou SIRET", confirmText: "Rechercher",
            onConfirm: async (num) => {
                const cleanNum = num.replace(/\D/g, '');
                if (cleanNum.length !== 9 && cleanNum.length !== 14) return showToast("Le numéro doit contenir exactement 9 ou 14 chiffres.", "error");
                setIsSaving(true);
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/sirene', { method: 'POST', body: JSON.stringify({ q: cleanNum }) });
                    const responseData = await res.json();
                    if (responseData.status !== 'success') throw new Error(responseData.message);

                    const apiData = responseData.data;
                    if (apiData.results && apiData.results.length > 0) {
                        const company = apiData.results[0];
                        const expectedSiren = cleanNum.substring(0, 9);
                        if (company.siren !== expectedSiren) { setIsSaving(false); return showToast("Numéro invalide.", "error"); }
                        const siege = company.siege || {};
                        let foundSiret = siege.siret || company.siren + "00010";
                        if (cleanNum.length === 14) { if (siege.siret === cleanNum) foundSiret = cleanNum; else if (company.matching_etablissements) { const exactEtab = company.matching_etablissements.find(e => e.siret === cleanNum); if (exactEtab) foundSiret = cleanNum; } }
                        const addressParts = [siege.numero_voie, siege.indice_repetition, siege.type_voie, siege.libelle_voie, siege.code_postal, siege.libelle_commune];
                        const address = addressParts.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim() || "Adresse non renseignée";
                        const tvaKey = (12 + 3 * (parseInt(company.siren, 10) % 97)) % 97;
                        const calculatedTva = `FR${tvaKey.toString().padStart(2, '0')}${company.siren}`;

                        setProfileData({ ...profileData, type_client: 'entreprise', name: company.nom_complet, address: address, siret: foundSiret, tva: calculatedTva });
                        setHasTva(true); showToast("Informations récupérées !", "success");
                    } else showToast("Aucune entreprise trouvée.", "error");
                } catch (err) { showToast("Le service est indisponible.", "error"); }
                setIsSaving(false);
            }
        });
    };

    const handleToggleTva = () => {
        if (isCollaborator) return;
        setHasTva(!hasTva); 
    };

    const handleSaveProfile = async () => {
        if(!profileData.name.trim() || !profileData.address.trim()) return showToast("Veuillez remplir le nom et l'adresse.", "error");
        if (profileData.type_client === 'entreprise' && !profileData.siret.trim()) return showToast("Veuillez remplir le SIRET.", "error");

        let cleanTva = 'NON_ASSUJETTI';
        if (profileData.type_client === 'entreprise' && hasTva) {
            if (!profileData.tva || profileData.tva.trim() === '') return showToast("Veuillez renseigner votre numéro de TVA.", "error");
            cleanTva = profileData.tva.replace(/\s+/g, '').toUpperCase();
            if (!/^[A-Z]{2}[A-Z0-9]{2,12}$/.test(cleanTva)) return showToast("Format de TVA invalide.", "error");
        }

        setIsSaving(true);
        try {
            const payload = { ...profileData, tva: cleanTva, uiMode: uiMode };
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update', { method: 'POST', body: JSON.stringify(payload) });
            if((await res.json()).status === 'success') { 
                setProfileData({ ...profileData, tva: profileData.type_client === 'entreprise' && hasTva ? cleanTva : '' });
                showToast("Profil mis à jour !"); 
                refreshData(); 
            }
        } finally { setIsSaving(false); }
    };

    const handleRequestEmailChange = async (e) => {
        if (e) e.preventDefault();
        const newEmail = emailChangeData.email.trim();
        if (!newEmail || !newEmail.includes('@')) return showToast("E-mail invalide.", "error");
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/request_email', { method: 'POST', body: JSON.stringify({ email: newEmail }) });
            const d = await res.json();
            if (d.status === 'success') {
                showToast("Un code de vérification a été envoyé à cette nouvelle adresse.", "info");
                setEmailChangeData(prev => ({ ...prev, step: 'verify' }));
            } else { showToast(d.message, 'error'); }
        } catch(err) { showToast("Erreur réseau.", "error"); }
        setIsSaving(false);
    };

    const handleConfirmEmailChange = async (e) => {
        e.preventDefault();
        const code = emailChangeData.code.trim();
        if (!code) return showToast("Code manquant.", "error");
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update_email', { method: 'POST', body: JSON.stringify({ code }) });
            const d = await res.json();
            if (d.status === 'success') {
                showToast("E-mail mis à jour avec succès !", "success");
                setEmailChangeData({ step: 'input', email: '', code: '' });
                refreshData();
            } else { showToast(d.message, 'error'); }
        } catch(err) { showToast("Erreur réseau.", "error"); }
        setIsSaving(false);
    };

    const handleSavePassword = async () => {
        if(!passwordData.oldPassword || !passwordData.newPassword) return showToast("Champs manquants", "error");
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/password/update', { method: 'POST', body: JSON.stringify({ oldPassword: passwordData.oldPassword, password: passwordData.newPassword }) });
            const d = await res.json();
            if(d.status === 'success') { showToast("Mot de passe mis à jour"); setPasswordData({oldPassword:'', newPassword:''}); }
            else showToast(d.message, 'error');
        } finally { setIsSaving(false); }
    };

    const requestAccountDeletion = async (e) => {
        e.preventDefault();
        const pwd = e.target.password.value;
        if (!pwd) return;
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/request_delete', { method: 'POST', body: JSON.stringify({ password: pwd }) });
            const d = await res.json();
            if (d.status === 'success') {
                showToast("E-mail de confirmation envoyé.", "info");
                setShowDeleteModal(false);
            } else {
                showToast(d.message, 'error');
            }
        } catch(e) { showToast("Erreur", "error"); }
        setIsSaving(false);
    };

    const togglePush = () => {
        if (pushEnabled) { localStorage.setItem('eco_push_enabled', 'false'); setPushEnabled(false); showToast("Notifications web désactivées.", "info"); } 
        else {
            if (!window.Notification) return showToast("Votre navigateur ne supporte pas les notifications.", "error");
            Notification.requestPermission().then(perm => {
                if (perm === 'granted') { localStorage.setItem('eco_push_enabled', 'true'); setPushEnabled(true); showToast("Notifications activées !", "success"); } 
                else if (perm === 'denied') { setShowPushTutorial(true); }
            });
        }
    };

    const enableTotp = async () => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/setup_totp', { method: 'POST' });
            const d = await res.json();
            if (d.status === 'success') { setTotpSetupData(d.data); } 
            else { showToast(d.message, 'error'); }
        } catch(e) { showToast("Erreur réseau", "error"); }
        setIsSaving(false);
    };

    const confirmTotp = async () => {
        setIsSaving(true);
        try {
            const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update_2fa', { method: 'POST', body: JSON.stringify({ method: 'totp' }) });
            if ((await res.json()).status === 'success') {
                setProfileData({...profileData, two_factor_method: 'totp'});
                setTotpSetupData(null);
                showToast("2FA par application activée avec succès !", "success");
            }
        } catch(e) {}
        setIsSaving(false);
    };

    // --- RENDU JSX ---

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4">
            <div><h1 className="text-3xl font-black text-slate-800">Mon compte</h1><p className="text-slate-500 font-medium">Paramètres de profil et sécurité.</p></div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                
                {/* 1. PROFIL DE LA SOCIÉTÉ */}
                <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                    <div className="flex justify-between items-center mb-6">
                        <h3 className="font-black text-slate-800 flex items-center gap-2"><Building size={18} className="text-emerald-600"/> Profil de la société</h3>
                        {!isCollaborator && (
                            <button onClick={handleAutoFill} className="text-xs font-bold text-blue-700 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-lg flex items-center gap-1 transition border border-blue-200 shadow-sm">
                                <Zap size={14}/> Saisie automatique
                            </button>
                        )}
                    </div>
                    <div className="space-y-4">
                        {!isCollaborator && (
                            <div className="flex items-center gap-4 mb-4 pb-4 border-b border-slate-100">
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="type_client" value="particulier" checked={profileData.type_client === 'particulier'} onChange={(e) => setProfileData({...profileData, type_client: e.target.value})} className="w-4 h-4 accent-emerald-600" />
                                    <span className="text-sm font-bold text-slate-700">Particulier</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="type_client" value="entreprise" checked={profileData.type_client === 'entreprise'} onChange={(e) => setProfileData({...profileData, type_client: e.target.value})} className="w-4 h-4 accent-emerald-600" />
                                    <span className="text-sm font-bold text-slate-700">Entreprise</span>
                                </label>
                            </div>
                        )}

                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">{profileData.type_client === 'entreprise' ? 'Nom / raison sociale *' : 'Nom complet *'}</label><input value={profileData.name} onChange={e=>setProfileData({...profileData, name: e.target.value})} disabled={isCollaborator} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition disabled:bg-slate-50" /></div>
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Adresse complète *</label><textarea value={profileData.address} onChange={e=>setProfileData({...profileData, address: e.target.value})} disabled={isCollaborator} rows="2" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition resize-none disabled:bg-slate-50"></textarea></div>
                        
                        {profileData.type_client === 'entreprise' && (
                            <>
                                <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">SIRET *</label><input value={profileData.siret} onChange={e=>setProfileData({...profileData, siret: e.target.value})} disabled={isCollaborator} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition disabled:bg-slate-50" /></div>
                                
                                {!isCollaborator && (
                                    <label className="flex items-center gap-3 p-3 bg-slate-50 border border-slate-200 rounded-xl cursor-pointer hover:bg-slate-100 transition mt-2">
                                        <input type="checkbox" checked={profileData.employees_gt_5} onChange={(e) => setProfileData({...profileData, employees_gt_5: e.target.checked})} className="w-5 h-5 accent-emerald-600" />
                                        <div><p className="text-sm font-bold text-slate-800">L'entreprise compte plus de 5 employés</p></div>
                                    </label>
                                )}

                                {!isCollaborator && (
                                    <div className="pt-2 border-t border-slate-100 mt-4">
                                        <label className="flex items-center justify-between cursor-pointer group py-2">
                                            <div>
                                                <p className="text-sm font-bold text-slate-800">Assujetti à la TVA</p>
                                                <p className="text-[10px] font-medium text-slate-500">Mon entreprise facture la TVA.</p>
                                            </div>
                                            <div className={`w-12 h-6 rounded-full transition-colors relative shrink-0 ${hasTva ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                                                <div className={`absolute top-1 bg-white w-4 h-4 rounded-full transition-transform ${hasTva ? 'left-7' : 'left-1'}`}></div>
                                            </div>
                                            <input type="checkbox" className="hidden" checked={hasTva} onChange={handleToggleTva} />
                                        </label>

                                        {hasTva && (
                                            <div className="space-y-1 mt-2 animate-in fade-in slide-in-from-top-2">
                                                <label className="text-xs font-bold text-slate-500 uppercase block">TVA intracommunautaire *</label>
                                                <input value={profileData.tva} onChange={e=>setProfileData({...profileData, tva: e.target.value})} placeholder="FR..." className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition uppercase" />
                                            </div>
                                        )}
                                    </div>
                                )}
                            </>
                        )}

                        {!isCollaborator && (
                            <label className="flex items-center gap-3 p-4 border border-slate-200 rounded-xl cursor-pointer hover:bg-slate-50 transition mt-4">
                                <input type="checkbox" checked={profileData.monthlyReport === 1} onChange={(e) => setProfileData({...profileData, monthlyReport: e.target.checked ? 1 : 0})} className="w-5 h-5 accent-emerald-600" />
                                <div><p className="text-sm font-bold text-slate-800">Rapports d'activité</p><p className="text-xs text-slate-500">Recevoir un e-mail mensuel sur l'usage des panneaux.</p></div>
                            </label>
                        )}
                        {!isCollaborator && <button onClick={handleSaveProfile} disabled={isSaving} className="w-full bg-slate-900 text-white py-3 rounded-xl font-bold shadow-md hover:bg-slate-800 transition disabled:opacity-50">Enregistrer les modifications</button>}
                    </div>
                </div>

                <div className="space-y-6">

                    {/* 2. EMAIL DE CONNEXION */}
                    <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><Mail size={18} className="text-emerald-600"/> Adresse e-mail de connexion</h3>
                        <div className="space-y-4">
                            <div className="space-y-1">
                                <label className="text-xs font-bold text-slate-500 uppercase block">E-mail actuel</label>
                                <input disabled value={myClientData.email || ''} className="w-full border border-slate-200 rounded-xl p-3 text-sm outline-none bg-slate-50 text-slate-500" />
                            </div>
                            
                            {emailChangeData.step === 'input' ? (
                                <form onSubmit={handleRequestEmailChange} className="space-y-3 pt-2 border-t border-slate-100">
                                    <div className="space-y-1">
                                        <label className="text-xs font-bold text-slate-500 uppercase block">Nouvel e-mail souhaité</label>
                                        <input type="email" required value={emailChangeData.email} onChange={e=>setEmailChangeData({...emailChangeData, email: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" />
                                    </div>
                                    <button type="submit" disabled={isSaving} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition disabled:opacity-50">Demander le changement</button>
                                </form>
                            ) : (
                                <form onSubmit={handleConfirmEmailChange} className="space-y-3 pt-2 border-t border-slate-100 animate-in fade-in slide-in-from-top-2">
                                    <p className="text-xs text-emerald-600 font-bold mb-2">Un code a été envoyé à {emailChangeData.email}</p>
                                    <div className="space-y-1">
                                        <label className="text-xs font-bold text-slate-500 uppercase block">Code de vérification (6 chiffres)</label>
                                        <input type="text" required value={emailChangeData.code} onChange={e=>setEmailChangeData({...emailChangeData, code: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition text-center tracking-[0.5em] font-black" placeholder="------" />
                                    </div>
                                    <div className="flex gap-2">
                                        <button type="button" onClick={() => setEmailChangeData({ step: 'input', email: '', code: '' })} className="px-4 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition">Annuler</button>
                                        <button type="submit" disabled={isSaving} className="flex-1 bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg disabled:opacity-50">Valider</button>
                                    </div>
                                    <div className="text-center mt-2">
                                        <button type="button" onClick={handleRequestEmailChange} disabled={isSaving} className="text-xs font-bold text-emerald-600 hover:text-emerald-700 disabled:opacity-50 transition flex items-center justify-center gap-1 w-full py-2">
                                            <RefreshCw size={12}/> Renvoyer le code
                                        </button>
                                    </div>
                                </form>
                            )}
                        </div>
                    </div>

                    {/* 3. MOT DE PASSE */}
                    <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><Lock size={18} className="text-emerald-600"/> Mot de passe</h3>
                        <div className="space-y-4">
                            <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Ancien mot de passe</label><input type="password" value={passwordData.oldPassword} onChange={e=>setPasswordData({...passwordData, oldPassword: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" /></div>
                            <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Nouveau mot de passe</label><input type="password" value={passwordData.newPassword} onChange={e=>setPasswordData({...passwordData, newPassword: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" placeholder="Min 8 car., Maj, Min, Chiffre" /></div>
                            <button onClick={handleSavePassword} disabled={isSaving} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition disabled:opacity-50">Modifier le mot de passe</button>
                        </div>
                    </div>

                    {/* 4. SECURITE 2FA */}
                    <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200 mt-6">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><ShieldCheck size={18} className="text-emerald-600"/> Authentification à double facteur (2FA)</h3>
                        <p className="text-xs text-slate-500 mb-4">Protégez votre compte avec une étape de sécurité supplémentaire lors de la connexion.</p>
                        
                        <div className="space-y-3">
                            <label className={`flex items-center gap-3 p-4 border rounded-xl cursor-pointer transition shadow-sm ${profileData.two_factor_method === 'none' ? 'border-emerald-500 bg-emerald-50' : 'border-slate-200 hover:bg-slate-50'}`}>
                                <input type="radio" name="2fa_method" checked={profileData.two_factor_method === 'none'} onChange={async () => {
                                    setIsSaving(true);
                                    await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update_2fa', { method: 'POST', body: JSON.stringify({ method: 'none' }) });
                                    setProfileData({...profileData, two_factor_method: 'none'});
                                    setTotpSetupData(null);
                                    showToast("2FA désactivée.");
                                    setIsSaving(false);
                                }} className="w-5 h-5 accent-emerald-600 shrink-0" />
                                <div className="flex-1"><span className="text-sm font-bold text-slate-800">Désactivée</span></div>
                            </label>

                            <label className={`flex items-center gap-3 p-4 border rounded-xl cursor-pointer transition shadow-sm ${profileData.two_factor_method === 'email' ? 'border-emerald-500 bg-emerald-50' : 'border-slate-200 hover:bg-slate-50'}`}>
                                <input type="radio" name="2fa_method" checked={profileData.two_factor_method === 'email'} onChange={async () => {
                                    setIsSaving(true);
                                    await fetch(window.ECO_CONFIG.apiBaseUrl + 'clients/profile/update_2fa', { method: 'POST', body: JSON.stringify({ method: 'email' }) });
                                    setProfileData({...profileData, two_factor_method: 'email'});
                                    setTotpSetupData(null);
                                    showToast("2FA par e-mail activée.");
                                    setIsSaving(false);
                                }} className="w-5 h-5 accent-emerald-600 shrink-0" />
                                <div className="flex-1 flex justify-between items-center w-full">
                                    <div>
                                        <span className="text-sm font-bold text-slate-800 block">Par e-mail</span>
                                        <span className="text-[10px] text-slate-500 leading-tight">Un code à 6 chiffres vous sera envoyé à chaque connexion.</span>
                                    </div>
                                    {profileData.two_factor_method === 'email' && <span className="text-[10px] font-black uppercase text-emerald-600 bg-emerald-100 px-2 py-0.5 rounded ml-2">Activée</span>}
                                </div>
                            </label>

                            <label className={`flex items-center gap-3 p-4 border rounded-xl cursor-pointer transition shadow-sm ${profileData.two_factor_method === 'totp' ? 'border-emerald-500 bg-emerald-50' : 'border-slate-200 hover:bg-slate-50'}`}>
                                <input type="radio" name="2fa_method" checked={profileData.two_factor_method === 'totp'} onChange={() => {
                                    if (profileData.two_factor_method !== 'totp') enableTotp();
                                }} className="w-5 h-5 accent-emerald-600 shrink-0" />
                                <div className="flex-1 flex justify-between items-center w-full">
                                    <div>
                                        <span className="text-sm font-bold text-slate-800 block">Application (Google Auth, Authy...)</span>
                                        <span className="text-[10px] text-slate-500 leading-tight">Générez des codes hors-ligne directement sur smartphone.</span>
                                    </div>
                                    {profileData.two_factor_method === 'totp' && <span className="text-[10px] font-black uppercase text-emerald-600 bg-emerald-100 px-2 py-0.5 rounded ml-2">Activée</span>}
                                </div>
                            </label>
                        </div>
                    </div>

                    {/* 5. ÉQUIPE DE COLLABORATEURS */}
                    {!isCollaborator && isAdvancedMode && (
                        <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-slate-200">
                            <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2"><Users size={18} className="text-emerald-600"/> Équipe de collaborateurs</h3>
                            <p className="text-xs text-slate-500 mb-4">Gérez les accès de votre équipe à vos panneaux.</p>
                            <button onClick={openTeamManage} className="w-full bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition flex justify-center items-center gap-2 shadow-sm"><Users size={16}/> Gérer l'équipe ({data.team?.length || 0})</button>
                        </div>
                    )}

                    {/* 6. DOCUMENTS LÉGAUX */}
                    <div className="bg-white p-6 rounded-3xl border border-slate-200 shadow-sm mt-6">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2"><FileText size={18} className="text-slate-600"/> Documents légaux</h3>
                        <p className="text-xs text-slate-500 mb-4 leading-relaxed font-medium">Consultez nos conditions d'utilisation et notre politique de confidentialité.</p>
                        <div className="flex flex-col sm:flex-row gap-3">
                            <button onClick={() => setLegalModal('cgv')} className="flex-1 bg-slate-50 border border-slate-200 text-slate-700 px-4 py-3 rounded-xl font-bold text-sm shadow-sm hover:bg-slate-100 transition flex items-center justify-center gap-2">
                                Conditions générales de vente
                            </button>
                            <button onClick={() => setLegalModal('rgpd')} className="flex-1 bg-slate-50 border border-slate-200 text-slate-700 px-4 py-3 rounded-xl font-bold text-sm shadow-sm hover:bg-slate-100 transition flex items-center justify-center gap-2">
                                Politique de confidentialité
                            </button>
                        </div>
                    </div>

                    {/* 7. ALERTES NAVIGATEUR */}
                    <div className="bg-indigo-50 p-6 rounded-2xl border border-indigo-100 shadow-sm mt-6">
                        <h3 className="font-black text-indigo-900 mb-2 flex items-center gap-2"><Bell size={18}/> Alertes navigateur</h3>
                        <p className="text-xs text-indigo-700/80 mb-4 leading-relaxed font-medium">Recevez une alerte visuelle et sonore sur votre PC/Mobile dès qu'un riverain poste un message.</p>
                        <button onClick={togglePush} className={`w-full px-4 py-3 rounded-xl font-bold text-sm transition shadow-sm ${pushEnabled ? 'bg-indigo-200 text-indigo-800 hover:bg-indigo-300' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
                            {pushEnabled ? 'Désactiver les alertes' : 'Activer les alertes (Opt-in)'}
                        </button>
                    </div>

                    {/* 8. SUPPRESSION DE COMPTE */}
                    {!isCollaborator && (
                        <div className="bg-red-50 p-6 rounded-2xl border border-red-100 shadow-sm">
                            <h3 className="font-black text-red-900 mb-2 flex items-center gap-2"><Power size={18}/> Supprimer votre compte</h3>
                            <p className="text-xs text-red-700/80 mb-4 leading-relaxed font-medium">La suppression de votre compte effacera définitivement tous vos panneaux, factures et fichiers (D.O.E inclus).</p>
                            
                            {myClientData.wallet_balance < 0 ? (
                                <div className="bg-red-100 text-red-800 p-3 rounded-xl text-sm font-bold border border-red-200 text-center">
                                    <AlertTriangle className="inline mr-2" size={16} />
                                    Votre solde est débiteur ({myClientData.wallet_balance.toFixed(2)}€). Vous devez régulariser vos factures avant de pouvoir fermer votre compte.
                                </div>
                            ) : (
                                <button onClick={() => setShowDeleteModal(true)} className="w-full bg-red-600 text-white px-4 py-3 rounded-xl font-bold text-sm shadow-md hover:bg-red-700 transition">Supprimer mon compte définitivement</button>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* MODALES LOCALES DES PARAMÈTRES */}
            {promptDialog && <window.PromptModal {...promptDialog} zIndex="z-[250]" onCancel={() => setPromptDialog(null)} />}
            
            {legalModal && (
                <window.Modal title={legalModal === 'cgv' ? 'Conditions générales de vente' : 'Politique de confidentialité'} onClose={() => setLegalModal(null)} zIndex="z-[250]">
                    <div 
                        dangerouslySetInnerHTML={{ 
                            __html: window.DOMPurify 
                                ? window.DOMPurify.sanitize(
                                    legalModal === 'cgv' ? (data?.settings?.cgv || "Aucune CGV définie.") : (data?.settings?.rgpd || "Aucune mention légale définie.")
                                )
                                : (legalModal === 'cgv' ? (data?.settings?.cgv || "Aucune CGV.") : (data?.settings?.rgpd || "Aucune mention.")).toString().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
                        }} 
                        className="text-sm text-slate-600 leading-relaxed font-medium admin-html" 
                    />
                </window.Modal>
            )}

            {totpSetupData && (
                <window.Modal title="Configuration 2FA" onClose={() => { setTotpSetupData(null); setProfileData({...profileData, two_factor_method: 'none'}); }} zIndex="z-[250]">
                    <div className="flex flex-col items-center text-center space-y-4">
                        <p className="text-sm text-slate-600 font-medium">Scannez ce QR Code avec votre application d'authentification (Google Authenticator, Authy, etc.) :</p>
                        <div className="bg-white p-2 rounded-xl shadow-sm border border-slate-100">
                            <window.NativeQRCode value={totpSetupData.otpauth} size={150} />
                        </div>
                        <p className="text-xs text-slate-500">Ou saisissez cette clé manuellement :</p>
                        <code className="bg-slate-100 px-3 py-2 rounded text-slate-700 font-black tracking-widest select-all">{totpSetupData.secret}</code>
                        <div className="w-full pt-4 border-t border-slate-100 mt-2">
                            <button onClick={confirmTotp} disabled={isSaving} className="w-full bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg">
                                J'ai scanné le code, activer
                            </button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {showPushTutorial && (
                <window.Modal title="Notifications bloquées" onClose={() => setShowPushTutorial(false)} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-orange-50 text-orange-800 p-4 rounded-xl text-sm leading-relaxed border border-orange-100">
                            <AlertTriangle className="inline mr-2 mb-1 text-orange-600" size={16}/>
                            Vous avez refusé les notifications pour ce site dans votre navigateur ou sur votre appareil. Voici comment les réactiver manuellement :
                        </div>
                        <div className="space-y-3 pt-2 text-sm text-slate-700">
                            <details className="bg-white border border-slate-200 rounded-xl p-3 cursor-pointer group">
                                <summary className="font-bold outline-none">Sur ordinateur (Chrome / Edge / Firefox)</summary>
                                <p className="mt-2 text-xs text-slate-500 pl-4 border-l-2 border-slate-200">Cliquez sur l'icône de cadenas à gauche de la barre d'adresse URL, puis cherchez la ligne "Notifications" et passez-la sur "Autoriser". Rechargez ensuite la page.</p>
                            </details>
                            <details className="bg-white border border-slate-200 rounded-xl p-3 cursor-pointer group">
                                <summary className="font-bold outline-none">Sur Mac (Safari)</summary>
                                <p className="mt-2 text-xs text-slate-500 pl-4 border-l-2 border-slate-200">Allez dans le menu Safari &gt; Réglages &gt; Sites web &gt; Notifications. Cherchez "eco-panneau.fr" dans la liste et sélectionnez "Autoriser".</p>
                            </details>
                            <details className="bg-white border border-slate-200 rounded-xl p-3 cursor-pointer group">
                                <summary className="font-bold outline-none">Sur Android (Chrome)</summary>
                                <p className="mt-2 text-xs text-slate-500 pl-4 border-l-2 border-slate-200">Appuyez sur l'icône cadenas ou menu dans la barre d'adresse &gt; Paramètres du site &gt; Notifications &gt; Autoriser.</p>
                            </details>
                            <details className="bg-white border border-slate-200 rounded-xl p-3 cursor-pointer group">
                                <summary className="font-bold outline-none">Sur iPhone / iPad (iOS)</summary>
                                <p className="mt-2 text-xs text-slate-500 pl-4 border-l-2 border-slate-200">Les notifications sur iOS nécessitent que vous "Ajoutiez le site sur l'écran d'accueil" (bouton Partager &gt; Sur l'écran d'accueil). Lancez ensuite l'application depuis votre écran d'accueil pour réactiver l'alerte.</p>
                            </details>
                        </div>
                        <button onClick={() => setShowPushTutorial(false)} className="w-full bg-slate-100 text-slate-700 py-3 mt-4 rounded-xl font-bold hover:bg-slate-200 transition">J'ai compris</button>
                    </div>
                </window.Modal>
            )}

            {showDeleteModal && (
                <window.Modal title="Supprimer votre compte" onClose={() => setShowDeleteModal(false)} preventClose={isSaving} zIndex="z-[250]">
                    <div className="space-y-4">
                        <div className="bg-red-50 text-red-800 p-4 rounded-xl text-sm leading-relaxed border border-red-100">
                            <AlertTriangle className="inline mr-2 mb-1" size={16}/>
                            La suppression est immédiate et irréversible. Vos panneaux, fichiers (D.O.E) et factures seront supprimés de nos serveurs.
                        </div>
                        
                        {myClientData.wallet_balance > 0 && (
                            <div className="bg-orange-50 text-orange-800 p-4 rounded-xl text-sm leading-relaxed border border-orange-200 font-bold text-center">
                                Attention : la suppression entraînera la perte définitive de votre solde positif ({myClientData.wallet_balance.toFixed(2)} €).
                            </div>
                        )}

                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 flex flex-col items-center justify-center text-center gap-2">
                            <p className="text-xs text-slate-500 font-bold uppercase">Avant de partir</p>
                            <button onClick={() => { setShowDeleteModal(false); setArchiveConfig({ type: 'rgpd' }); }} className="text-sm font-bold text-blue-600 hover:text-blue-800 flex items-center gap-2 transition hover:bg-blue-50 px-4 py-2 rounded-lg">
                                <Download size={16}/> Télécharger vos données personnelles (Export RGPD)
                            </button>
                        </div>

                        <form onSubmit={requestAccountDeletion} className="pt-2">
                            <label className="text-xs font-bold text-slate-500 uppercase block mb-1">Pour confirmer, saisissez votre mot de passe</label>
                            <input name="password" type="password" required className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-red-500 outline-none transition mb-4" />
                            <div className="flex gap-2">
                                <button type="button" onClick={() => setShowDeleteModal(false)} className="px-4 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition">Annuler</button>
                                <button type="submit" disabled={isSaving} className="flex-1 bg-red-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-red-700 transition shadow-lg flex items-center justify-center gap-2 disabled:opacity-50">
                                    {isSaving ? <Loader className="animate-spin w-4 h-4"/> : <Trash2 size={16}/>}
                                    CONFIRMER LA SUPPRESSION
                                </button>
                            </div>
                        </form>
                    </div>
                </window.Modal>
            )}
        </div>
    );
};

/* EOF ===== [_clients_settings.jsx] =============== */