/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglets Dashboard et Système/Paramètres
 * =========================================================================
 */

const { useState, useEffect, useRef } = React;
const { 
    Activity, Users, Building, Eye, MessageSquare, Terminal, Archive, Save, 
    Download, RefreshCw, Trash2, Loader, ShieldAlert, CreditCard, FileText, 
    AlertTriangle, Settings, Zap 
} = window;

const decodeHTML = (html) => {
    const txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
};

// =========================================================================
// 1. ONGLET : TABLEAU DE BORD (SUPERVISION ET DIAGNOSTICS)
// =========================================================================

window.AdminDashboardTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [diagnostics, setDiagnostics] = useState(null);
    const [logs, setLogs] = useState('');
    const [backups, setBackups] = useState([]);
    const [isLoadingBackups, setIsLoadingBackups] = useState(false);
    const [showAllBackups, setShowAllBackups] = useState(false);
    const [sysSummary, setSysSummary] = useState({ 
        loaded: false, diagStatus: 'emerald', backupStatus: 'emerald', logStatus: 'emerald', 
        php: '', ram: '', db: '', disk: '', backupsCount: 0, logDesc: '', backupDesc: '' 
    });
    
    const [modalView, setModalView] = useState(null);
    const [pwdRequest, setPwdRequest] = useState(null); 
    const [promptDialog, setPromptDialog] = useState(null);

    const fetchTelemetry = async (silent = false) => {
        try {
            const cacheBuster = '&_t=' + Date.now();
            const fetchOpts = silent ? { cache: 'no-store', headers: { 'x-silent': '1' } } : { cache: 'no-store' };
            const [diagRes, backRes, logRes] = await Promise.all([
                fetch(window.ECO_CONFIG.apiBaseUrl + 'system/diagnostics' + cacheBuster + (silent ? '&silent=1' : ''), fetchOpts).then(r => r.json()),
                fetch(window.ECO_CONFIG.apiBaseUrl + 'system/backups' + cacheBuster + (silent ? '&silent=1' : ''), fetchOpts).then(r => r.json()),
                fetch(window.ECO_CONFIG.apiBaseUrl + 'system/logs' + cacheBuster + (silent ? '&silent=1' : ''), fetchOpts).then(r => r.json())
            ]);
            
            if (diagRes.status === 'success') {
                const dbDetail = diagRes.data.find(d => d.id === 'db')?.detail || '0 ms';
                const diskDetail = diagRes.data.find(d => d.id === 'disk')?.detail || '0 GB';
                const dbVal = parseFloat(dbDetail);
                const diskVal = parseFloat(diskDetail);
                
                let diagStatus = 'emerald';
                if (dbVal > 500 || diskVal < 1) diagStatus = 'red';
                else if (dbVal > 200 || diskVal < 5) diagStatus = 'amber';
                
                const backupsData = backRes.data || [];
                const backupsCount = backupsData.length;
                let backupStatus = 'emerald';
                let backupDesc = `${backupsCount} archive(s)`;

                if (backupsCount === 0) {
                    backupStatus = 'red';
                    backupDesc = "Alerte : Aucune sauvegarde";
                } else {
                    const latestBackup = backupsData.reduce((max, b) => b.date > max.date ? b : max, backupsData[0]);
                    const hoursSinceLast = (Date.now() - latestBackup.date) / (1000 * 60 * 60);

                    if (hoursSinceLast > 48) { backupStatus = 'red'; backupDesc = `Critique : Retard de ${Math.floor(hoursSinceLast/24)} jours`; } 
                    else if (hoursSinceLast > 24) { backupStatus = 'amber'; backupDesc = `Attention : Retard de ${Math.floor(hoursSinceLast)}h`; } 
                    else { backupStatus = 'emerald'; backupDesc = `À jour (${backupsCount} archives)`; }
                }
                
                const logsContent = logRes.data?.logs || '';
                let logStatus = 'emerald';
                let logDesc = 'Journal vierge (Sain)';
                const lowerLogs = logsContent.toLowerCase();
                
                if (lowerLogs.includes('fatal error') || lowerLogs.includes('exception')) { logStatus = 'red'; logDesc = 'Erreurs critiques détectées !'; } 
                else if (logsContent.length > 5) { logStatus = 'amber'; logDesc = 'Avertissements enregistrés'; }
                
                setSysSummary({
                    loaded: true, diagStatus, backupStatus, logStatus,
                    php: diagRes.data.find(d => d.id === 'php')?.detail || 'OK',
                    ram: diagRes.data.find(d => d.id === 'ram')?.detail || 'OK',
                    db: dbDetail, disk: diskDetail, backupsCount, logDesc, backupDesc
                });
            }
        } catch(e) {}
    };

    useEffect(() => { 
        fetchTelemetry(); 
        let telemetryInterval;
        let currentDelay = 10000; 
        let lastActivityTime = Date.now();
        let isTabVisible = !document.hidden;

        const performTelemetrySync = async () => {
            if (!isTabVisible) return;
            await fetchTelemetry(true); 

            const idleTime = Date.now() - lastActivityTime;
            if (idleTime > 120000) currentDelay = 60000;      
            else if (idleTime > 30000) currentDelay = 30000;  
            else currentDelay = 10000;                        

            scheduleNextPoll(currentDelay);
        };

        const scheduleNextPoll = (delay) => {
            clearTimeout(telemetryInterval);
            if (isTabVisible) telemetryInterval = setTimeout(performTelemetrySync, delay);
        };

        const handleVisibilityChange = () => {
            isTabVisible = !document.hidden;
            if (isTabVisible) {
                lastActivityTime = Date.now();
                currentDelay = 10000;
                performTelemetrySync();
            } else {
                clearTimeout(telemetryInterval);
            }
        };

        const handleUserInteraction = () => {
            if (currentDelay > 10000) {
                lastActivityTime = Date.now();
                currentDelay = 10000;
                scheduleNextPoll(10000);
            } else {
                lastActivityTime = Date.now();
            }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);
        document.addEventListener('click', handleUserInteraction);
        document.addEventListener('keydown', handleUserInteraction);

        scheduleNextPoll(currentDelay);

        return () => {
            clearTimeout(telemetryInterval);
            document.removeEventListener('visibilitychange', handleVisibilityChange);
            document.removeEventListener('click', handleUserInteraction);
            document.removeEventListener('keydown', handleUserInteraction);
        };
    }, []);

    useEffect(() => {
        let interval;
        if (modalView === 'diagnostics') {
            interval = setInterval(() => {
                fetch(window.ECO_CONFIG.apiBaseUrl + 'system/diagnostics&silent=1&_t=' + Date.now(), { cache: 'no-store', headers: { 'x-silent': '1' } })
                .then(r => r.json())
                .then(d => {
                    if (d.status === 'success') setDiagnostics(d.data);
                }).catch(()=>{});
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [modalView]);

    const fetchDiagnostics = async () => { setModalView('diagnostics'); setDiagnostics(null); const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/diagnostics&_t=' + Date.now(), { cache: 'no-store' }); const d = await res.json(); if(d.status === 'success') setDiagnostics(d.data); };
    const fetchLogs = async () => { setModalView('logs'); setLogs('Chargement...'); const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/logs&_t=' + Date.now(), { cache: 'no-store' }); const d = await res.json(); setLogs(d.data?.logs || 'Aucun log trouvé.'); };
    const clearLogs = async () => { await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/logs/clear', { method: 'POST' }); fetchLogs(); fetchTelemetry(); };
    const loadBackups = async () => { setModalView('backups'); setShowAllBackups(false); setIsLoadingBackups(true); try { const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/backups&_t=' + Date.now(), { cache: 'no-store' }); const d = await res.json(); if(d.status === 'success') setBackups(d.data); } catch(e) { showToast("Erreur lors du chargement des sauvegardes", "error"); } finally { setIsLoadingBackups(false); } };
    
    const createBackup = () => {
        setPromptDialog({
            title: "Nouvelle sauvegarde",
            message: "Saisissez un marqueur ou label personnalisé pour identifier cette sauvegarde manuelle :",
            placeholder: "Ex : Avant la mise à jour...",
            confirmText: "Sauvegarder",
            onConfirm: async (label) => {
                setIsSaving(true);
                try {
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/backups/create', { method: 'POST', body: JSON.stringify({ label }) });
                    if ((await res.json()).status === 'success') { showToast("Sauvegarde créée avec succès.", "success"); loadBackups(); fetchTelemetry(); } 
                    else showToast("Erreur de sauvegarde", "error");
                } catch(e) { showToast("Erreur réseau", "error"); } finally { setIsSaving(false); }
            }
        });
    };

    const restoreBackup = (filename) => { setPwdRequest({ title: "Restauration système", desc: "ATTENTION CRITIQUE : La restauration écrasera la base de données actuelle. Saisissez le mot de passe administrateur :", onConfirm: async (pwd) => { setIsSaving(true); try { const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/backups/restore', { method: 'POST', body: JSON.stringify({ filename, pwd }) }); if ((await res.json()).status === 'success') { alert("Restauration réussie. L'application va recharger."); window.location.reload(); } else showToast("Mot de passe incorrect ou erreur.", "error"); } finally { setIsSaving(false); } } }); };
    const deleteBackup = (filename) => { setPwdRequest({ title: "Suppression d'archive", desc: "Saisissez le mot de passe administrateur pour supprimer définitivement cette sauvegarde :", onConfirm: async (pwd) => { const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'system/backups/delete', { method: 'POST', body: JSON.stringify({ filename, pwd }) }); if ((await res.json()).status === 'success') { loadBackups(); fetchTelemetry(); } else { showToast("Mot de passe incorrect", "error"); } } }); };
    
    const getColorClass = (status) => { 
        if (!sysSummary.loaded) return 'text-slate-500 border-slate-200 bg-slate-50'; 
        if (status === 'red') return 'text-red-700 border-red-200 bg-red-50 hover:border-red-400'; 
        if (status === 'amber') return 'text-amber-700 border-amber-200 bg-amber-50 hover:border-amber-400'; 
        return 'text-emerald-700 border-emerald-200 bg-emerald-50 hover:border-emerald-400'; 
    };

    const clients = data.clients || [];
    const panneaux = data.panneaux || [];
    const activePanneaux = panneaux.filter(p => p.status === 'Actif' && p.id !== 'demo-panneau');
    const mrr = activePanneaux.filter(p => p.offerType === 'rental').reduce((sum, p) => sum + (p.currentRate || 0), 0);
    const interactions = data.interactions || [];
    const recentMessages = [...interactions].filter(m => m.target === 'Admin').reverse().slice(0, 5);

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4">
            <div><h1 className="text-3xl font-black text-slate-800">Supervision</h1><p className="text-slate-500 font-medium">Vue d'ensemble de la plateforme SaaS.</p></div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <window.StatCard title="MRR (revenus loc.)" value={`${mrr} €`} icon={<Activity size={24}/>} color="text-emerald-600" bg="bg-emerald-100" />
                <window.StatCard title="Clients inscrits" value={clients.length} icon={<Users size={24}/>} color="text-blue-600" bg="bg-blue-100" onClick={() => setActiveTab('clients')} />
                <window.StatCard title="Panneaux actifs" value={activePanneaux.length} icon={<Building size={24}/>} color="text-indigo-600" bg="bg-indigo-100" onClick={() => setActiveTab('panneaux')} />
                <window.StatCard title="Total scans QR" value={data.stats?.totalViews || 0} icon={<Eye size={24}/>} color="text-amber-600" bg="bg-amber-100" />
            </div>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100">
                    <div className="flex justify-between items-center mb-6"><h3 className="font-black text-slate-800 flex items-center gap-2"><MessageSquare size={18} className="text-emerald-600"/> Derniers messages</h3><button onClick={() => setActiveTab('messages')} className="text-xs font-bold text-emerald-600 hover:underline">Voir tout</button></div>
                    <div className="space-y-4">
                        {recentMessages.map((m, i) => {
                            let displayAuthor = m.author;
                            
                            if (m.panneauId === 'CONTACT_PUBLIC') {
                                if (m.author === 'Admin') displayAuthor = 'Service client';
                                else if (m.author === 'Système' || m.author === 'Systeme') displayAuthor = 'Système';
                                else displayAuthor = `Visiteur ${m.author}`;
                            } else {
                                if (m.author === 'Admin') displayAuthor = 'Support';
                                else if (m.author === 'Client') {
                                    if (m.panneauId.startsWith('SUPPORT_')) {
                                        const cUid = m.panneauId.split('_')[1];
                                        const c = clients.find(cl => cl.id === cUid);
                                        if (c && c.name) displayAuthor = c.name;
                                    } else displayAuthor = 'Client';
                                } else if (m.author === 'Système' || m.author === 'Systeme') displayAuthor = 'Système';
                            }

                            return (
                                <div key={i} className="flex flex-col p-4 rounded-xl border border-slate-100 bg-slate-50 cursor-pointer hover:border-emerald-200 transition" onClick={() => {
                                    let tId = m.panneauId;
                                    if (m.panneauId === 'CONTACT_PUBLIC') {
                                         tId = `CONTACT_PUBLIC_${m.author}`;
                                    } else if (m.panneauId.startsWith('SUPPORT_')) {
                                         tId = m.panneauId;
                                    } else if (m.author !== 'Client' && m.author !== 'Admin') {
                                         tId = `${m.panneauId}_${m.author}`;
                                    } else if (m.target !== 'Client' && m.target !== 'Admin' && m.target) {
                                         tId = `${m.panneauId}_${m.target}`;
                                    }
                                    const u = new URL(window.location);
                                    if (tId) u.searchParams.set('chat_id', tId);
                                    window.history.replaceState({}, '', u);
                                    setActiveTab('messages');
                                }}>
                                    <div className="flex justify-between items-start mb-2"><div className="flex items-center gap-2"><span className={`w-2 h-2 rounded-full ${m.isAlert ? 'bg-red-500' : (m.resolved ? 'bg-slate-300' : 'bg-emerald-500')}`}></span><p className="font-bold text-xs text-slate-700">{displayAuthor}</p></div><span className="text-[10px] font-bold text-slate-400">{new Date(String(m.created_at || '').replace(' ', 'T')).toLocaleDateString('fr-FR')}</span></div>
                                    <p className="text-sm text-slate-600 line-clamp-2">{m.detail.replace(/\[ATTACHMENT:[^\]]+\]/g, '[Pièce jointe]').replace(/<[^>]*>?/gm, '')}</p>
                                    <p className="text-[10px] text-slate-400 mt-2 pt-2 border-t border-slate-200 font-bold">{m.panneauId === 'CONTACT_PUBLIC' ? 'ORIGINE : Nous contacter' : 'ORIGINE : Espace client (Support)'}</p>
                                </div>
                            );
                        })}
                        {recentMessages.length === 0 && <p className="text-sm text-slate-400 italic text-center py-4">Aucune interaction récente.</p>}
                    </div>
                </div>
                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 flex flex-col">
                    <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><Terminal size={18} className="text-emerald-600"/> Serveur et maintenance</h3>
                    <div className="space-y-3 flex-1 flex flex-col justify-start">
                        <button onClick={loadBackups} title="Gérer les sauvegardes du site" className={`w-full flex items-center justify-between p-4 rounded-xl border transition group text-left ${getColorClass(sysSummary.backupStatus)}`}>
                            <div className="flex items-center gap-4"><Archive size={24} className="group-hover:scale-110 transition-transform"/><div><p className="font-bold text-sm">Sauvegardes système</p><p className={`text-xs mt-1 ${sysSummary.loaded ? 'opacity-80' : 'opacity-50 animate-pulse'}`}>{sysSummary.loaded ? sysSummary.backupDesc : 'Vérification...'}</p></div></div>
                        </button>
                        <button onClick={fetchDiagnostics} title="Voir l'état des services" className={`w-full flex items-center justify-between p-4 rounded-xl border transition group text-left ${getColorClass(sysSummary.diagStatus)}`}>
                            <div className="flex items-center gap-4"><Activity size={24} className="group-hover:scale-110 transition-transform"/><div><p className="font-bold text-sm">Diagnostics système</p><p className={`text-xs mt-1 ${sysSummary.loaded ? 'opacity-80' : 'opacity-50 animate-pulse'}`}>{sysSummary.loaded ? `RAM: ${sysSummary.ram} • DB: ${sysSummary.db}` : 'Analyse en cours...'}</p></div></div>
                        </button>
                        <button onClick={fetchLogs} title="Consulter les erreurs backend" className={`w-full flex items-center justify-between p-4 rounded-xl border transition group text-left ${getColorClass(sysSummary.logStatus)}`}>
                            <div className="flex items-center gap-4"><Terminal size={24} className="group-hover:scale-110 transition-transform"/><div><p className="font-bold text-sm">Logs d'erreurs (PHP)</p><p className={`text-xs mt-1 ${sysSummary.loaded ? 'opacity-80' : 'opacity-50 animate-pulse'}`}>{sysSummary.loaded ? sysSummary.logDesc : 'Chargement...'}</p></div></div>
                        </button>
                    </div>
                </div>
            </div>

            {/* MODALES SYSTÈME */}
            {modalView === 'diagnostics' && (
                <window.Modal title="Diagnostics système" onClose={() => setModalView(null)}>
                    {!diagnostics ? <div className="p-10 text-center"><Loader className="animate-spin inline-block text-emerald-600 mb-2" size={32}/><p className="text-slate-500 font-bold">Analyse complète en cours...</p></div> : (
                        <div className="space-y-3">
                            {diagnostics.map(d => (
                                <div key={d.id} className="flex justify-between items-center p-4 bg-slate-50 rounded-xl border border-slate-100">
                                    <div><p className="font-bold text-sm text-slate-800">{d.label}</p><p className="text-xs text-slate-500">{d.status}</p></div>
                                    <span className="font-mono text-sm font-black text-slate-700 bg-white px-3 py-1 rounded shadow-sm">{d.detail}</span>
                                </div>
                            ))}
                        </div>
                    )}
                </window.Modal>
            )}

            {modalView === 'logs' && (
                <window.Modal title="Logs d'erreurs (PHP)" onClose={() => setModalView(null)}>
                    <button onClick={clearLogs} className="w-full bg-red-50 text-red-600 py-3 rounded-xl font-bold flex justify-center items-center gap-2 hover:bg-red-100 transition mb-4"><Trash2 size={16}/> Vider les logs</button>
                    <div className="bg-slate-900 rounded-xl p-4 overflow-x-auto max-h-[60vh] custom-scrollbar">
                        <pre className="text-[10px] text-emerald-400 font-mono whitespace-pre-wrap">{logs}</pre>
                    </div>
                </window.Modal>
            )}

            {modalView === 'backups' && (
                <window.Modal title="Gestion des sauvegardes système" onClose={() => setModalView(null)} preventClose={isLoadingBackups}>
                    <div className="space-y-4">
                        {isLoadingBackups ? (
                            <div className="py-12 text-center text-slate-500">
                                <Loader size={32} className="animate-spin inline-block mb-4 text-emerald-600"/>
                                <p className="text-sm font-bold uppercase tracking-widest">Chargement en cours...</p>
                            </div>
                        ) : (
                            <>
                                <button onClick={createBackup} disabled={isSaving} className="w-full bg-slate-900 text-white py-4 rounded-xl font-black uppercase tracking-widest shadow-lg flex items-center justify-center gap-3 hover:bg-slate-800 disabled:opacity-50 transition mb-6">
                                    {(isSaving || isLoadingBackups) ? <Loader size={20} className="animate-spin"/> : <Save size={20} className="text-emerald-400"/>} 
                                    {isSaving ? 'COMPRESSION...' : 'SAUVEGARDER LE SITE'}
                                </button>
                                
                                {backups.slice(0, showAllBackups ? backups.length : 5).map(b => (
                                    <div key={b.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-slate-50 border border-slate-200 rounded-xl gap-4">
                                        <div className="min-w-0">
                                            <div className="flex items-center gap-2 mb-1">
                                                <span className={`px-2 py-0.5 rounded-md text-[10px] font-black uppercase tracking-widest ${b.label === 'Automatique' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}`}>
                                                    {b.label === 'Automatique' ? 'CRON' : 'MANUEL'}
                                                </span>
                                                <p className="font-bold text-sm text-slate-800 truncate" title={decodeHTML(b.label)}>{decodeHTML(b.label)}</p>
                                            </div>
                                            <p className="text-xs text-slate-500">{new Date(b.date).toLocaleString('fr-FR')} • {b.size}</p>
                                        </div>
                                        <div className="flex gap-2 shrink-0">
                                            <a href={`?api=system/backups/download&file=${encodeURIComponent(b.name)}`} title="Télécharger l'archive" className="p-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition"><Download size={16}/></a>
                                            <button onClick={() => restoreBackup(b.name)} disabled={isSaving} title="Restaurer (Écraser la BDD actuelle)" className="p-2 bg-amber-50 text-amber-600 rounded-lg hover:bg-amber-100 transition disabled:opacity-50"><RefreshCw size={16}/></button>
                                            <button onClick={() => deleteBackup(b.name)} title="Supprimer définitivement" className="p-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition"><Trash2 size={16}/></button>
                                        </div>
                                    </div>
                                ))}

                                {backups.length === 0 && <p className="text-center text-sm text-slate-500 py-6 italic">Aucune sauvegarde trouvée.</p>}
                                
                                {!showAllBackups && backups.length > 5 && (
                                    <button onClick={() => setShowAllBackups(true)} className="w-full py-3 bg-slate-100 text-slate-600 font-bold rounded-xl hover:bg-slate-200 transition mt-2 text-sm">
                                        Afficher tout ({backups.length - 5} de plus)
                                    </button>
                                )}
                            </>
                        )}
                    </div>
                </window.Modal>
            )}

            {pwdRequest && (
                <window.Modal title={pwdRequest.title} onClose={() => setPwdRequest(null)} zIndex="z-[250]">
                    <div className="text-sm text-slate-600 mb-6 font-medium leading-relaxed">{pwdRequest.desc}</div>
                    <form onSubmit={(e) => {
                        e.preventDefault();
                        const pwd = e.target.pwd.value;
                        if(pwd) { pwdRequest.onConfirm(pwd); setPwdRequest(null); }
                    }}>
                        <input name="pwd" type="password" autoFocus required placeholder="Mot de passe administrateur..." className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition mb-4" />
                        <button type="submit" className="w-full bg-slate-900 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg">Confirmer l'action</button>
                    </form>
                </window.Modal>
            )}

            {promptDialog && <window.PromptModal {...promptDialog} zIndex="z-[250]" onCancel={() => setPromptDialog(null)} />}
        </div>
    );
};

// =========================================================================
// 2. ONGLET : PARAMÈTRES DU SYSTÈME (TARIFS ET SÉCURITÉ)
// =========================================================================

window.AdminSettingsTab = ({ data, refreshData, showToast, setActiveTab }) => {
    const [isSaving, setIsSaving] = useState(false);
    const [hasTva, setHasTva] = useState(true);
    const [showTvaWarning, setShowTvaWarning] = useState(false);
    const [pwdRequest, setPwdRequest] = useState(null); 
    const [promptDialog, setPromptDialog] = useState(null);
    
    // CORRECTION : Initialisation stricte de toutes les variables pour éviter le Warning React "uncontrolled to controlled"
    const [settingsData, setSettingsData] = useState({ 
        ...data.settings, 
        ...data.prices,
        hostingYr: data.prices?.hostingYr ?? 1,
        billing_legalText: data.settings?.billing_legalText ?? '',
        site_banner_active: data.settings?.site_banner_active ?? '0',
        site_banner_msg: data.settings?.site_banner_msg ?? '',
        panel_banner_active: data.settings?.panel_banner_active ?? '0',
        panel_banner_msg: data.settings?.panel_banner_msg ?? '',
        allow_new_purchases: data.settings?.allow_new_purchases ?? '1',
        simp_opt_description: data.settings?.simp_opt_description ?? '1',
        simp_opt_image: data.settings?.simp_opt_image ?? '1',
        simp_opt_theme: data.settings?.simp_opt_theme ?? '1',
        simp_opt_link: data.settings?.simp_opt_link ?? '1',
        simp_opt_emergency: data.settings?.simp_opt_emergency ?? '1',
        simp_opt_schedule: data.settings?.simp_opt_schedule ?? '1',
        blacklist: data.settings?.blacklist ?? 'putain, connard, salope',
        greylist: data.settings?.greylist ?? 'merde, chier',
        sec_ip_limit: data.settings?.sec_ip_limit ?? 5,
        sec_global_limit: data.settings?.sec_global_limit ?? 1000,
        sec_lock_min: data.settings?.sec_lock_min ?? 10,
        sec_lock_max: data.settings?.sec_lock_max ?? 60,
        maintenance: data.settings?.maintenance ?? '0'
    });

    const settingsLoadedRef = useRef(false);

    useEffect(() => { 
        if (data.settings && !settingsLoadedRef.current) {
            setSettingsData({ 
                ...data.settings, 
                ...data.prices,
                hostingYr: data.prices?.hostingYr ?? 1,
                billing_legalText: data.settings?.billing_legalText ?? '',
                site_banner_active: data.settings?.site_banner_active ?? '0',
                site_banner_msg: data.settings?.site_banner_msg ?? '',
                panel_banner_active: data.settings?.panel_banner_active ?? '0',
                panel_banner_msg: data.settings?.panel_banner_msg ?? '',
                allow_new_purchases: data.settings?.allow_new_purchases ?? '1',
                simp_opt_description: data.settings?.simp_opt_description ?? '1',
                simp_opt_image: data.settings?.simp_opt_image ?? '1',
                simp_opt_theme: data.settings?.simp_opt_theme ?? '1',
                simp_opt_link: data.settings?.simp_opt_link ?? '1',
                simp_opt_emergency: data.settings?.simp_opt_emergency ?? '1',
                simp_opt_schedule: data.settings?.simp_opt_schedule ?? '1',
                blacklist: data.settings?.blacklist ?? 'putain, connard, salope',
                greylist: data.settings?.greylist ?? 'merde, chier',
                sec_ip_limit: data.settings?.sec_ip_limit ?? 5,
                sec_global_limit: data.settings?.sec_global_limit ?? 1000,
                sec_lock_min: data.settings?.sec_lock_min ?? 10,
                sec_lock_max: data.settings?.sec_lock_max ?? 60,
                maintenance: data.settings?.maintenance ?? '0'
            }); 
            setHasTva(data.settings?.billing_has_tva !== '0');
            settingsLoadedRef.current = true;
        }
    }, [data]);

    const handleAutoFill = () => {
        setPromptDialog({
            title: "Saisie automatique",
            message: "Saisissez le SIRET (14 chiffres) ou SIREN (9 chiffres) de l'entreprise qui gère la plateforme (Vous) :",
            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 : Aucune entreprise correspondante.", "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}`;

                        setSettingsData({ ...settingsData, billing_company: company.nom_complet, billing_address: address, billing_siret: foundSiret, billing_tva: calculatedTva });
                        setHasTva(true);
                        showToast("Informations récupérées avec succès !", "success");
                    } else showToast("Aucune entreprise trouvée.", "error");
                } catch (err) { showToast("Le service gouvernemental est momentanément indisponible.", "error"); }
                setIsSaving(false);
            }
        });
    };

    const handleToggleTva = () => {
        if (hasTva) { setShowTvaWarning(true); } else { setHasTva(true); }
    };

    const confirmTvaExemption = () => {
        setHasTva(false);
        setSettingsData({ ...settingsData, billing_tva: '' });
        setShowTvaWarning(false);
    };

    const handleSaveSettings = () => {
        setPwdRequest({
            title: "Modification globale",
            desc: "Saisissez le mot de passe administrateur pour confirmer la modification des paramètres de la plateforme.",
            onConfirm: async (pwd) => {
                setIsSaving(true);
                try {
                    const payload = { 
                        ...settingsData, pwd, 
                        billing_has_tva: hasTva ? '1' : '0', 
                        price_rentalMo: settingsData.rentalMo, price_purchase: settingsData.purchase, 
                        price_boardFirst: settingsData.boardFirst, price_boardAdd: settingsData.boardAdd, 
                        price_noAds: settingsData.noAds,
                        price_hostingYr: settingsData.hostingYr,
                        billing_legalText: settingsData.billing_legalText,
                        sec_ip_limit: settingsData.sec_ip_limit,
                        sec_global_limit: settingsData.sec_global_limit,
                        sec_lock_min: settingsData.sec_lock_min,
                        sec_lock_max: settingsData.sec_lock_max
                    };
                    const res = await fetch(window.ECO_CONFIG.apiBaseUrl + 'settings/update', { method: 'POST', body: JSON.stringify(payload) });
                    if ((await res.json()).status === 'success') { showToast("Paramètres globaux mis à jour."); refreshData(); } 
                    else showToast("Mot de passe invalide", 'error');
                } finally { setIsSaving(false); }
            }
        });
    };

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 max-w-4xl mx-auto">
            <div><h1 className="text-3xl font-black text-slate-800">Paramètres système</h1><p className="text-slate-500 font-medium">Tarification globale et mentions légales.</p></div>

            <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200 mt-6">
                <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><ShieldAlert size={18} className="text-red-600"/> Cyberdéfense et pare-feu (Panic Mode)</h3>
                <p className="text-xs text-slate-500 mb-6">Paramétrez les seuils de déclenchement du confinement automatique en cas d'attaque réseau.</p>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                    <div className="p-4 bg-slate-50 border border-slate-100 rounded-xl">
                        <label className="text-xs font-bold text-slate-700 uppercase block mb-1">Limite d'échecs par IP</label>
                        <p className="text-[10px] text-slate-500 mb-3">Nombre d'erreurs de mot de passe avant bannissement de l'IP (15 min).</p>
                        <input type="number" min="1" max="50" value={settingsData.sec_ip_limit} onChange={e => setSettingsData({...settingsData, sec_ip_limit: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-2 text-sm focus:border-red-500 outline-none transition" />
                    </div>
                    
                    <div className="p-4 bg-slate-50 border border-slate-100 rounded-xl">
                        <label className="text-xs font-bold text-slate-700 uppercase block mb-1">Seuil d'alerte globale (DDoS / Botnet)</label>
                        <p className="text-[10px] text-slate-500 mb-3">Nombre d'IPs malveillantes simultanées avant confinement du site.</p>
                        <input type="number" min="50" max="10000" value={settingsData.sec_global_limit} onChange={e => setSettingsData({...settingsData, sec_global_limit: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-2 text-sm focus:border-red-500 outline-none transition" />
                    </div>
                    
                    <div className="p-4 bg-slate-50 border border-slate-100 rounded-xl">
                        <label className="text-xs font-bold text-slate-700 uppercase block mb-1">Durée minimum du confinement</label>
                        <p className="text-[10px] text-slate-500 mb-3">En minutes (Valeur aléatoire entre le min et le max).</p>
                        <input type="number" min="1" max="120" value={settingsData.sec_lock_min} onChange={e => setSettingsData({...settingsData, sec_lock_min: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-2 text-sm focus:border-red-500 outline-none transition" />
                    </div>

                    <div className="p-4 bg-slate-50 border border-slate-100 rounded-xl">
                        <label className="text-xs font-bold text-slate-700 uppercase block mb-1">Durée maximum du confinement</label>
                        <p className="text-[10px] text-slate-500 mb-3">En minutes.</p>
                        <input type="number" min="2" max="1440" value={settingsData.sec_lock_max} onChange={e => setSettingsData({...settingsData, sec_lock_max: e.target.value})} className="w-full border-2 border-slate-200 rounded-xl p-2 text-sm focus:border-red-500 outline-none transition" />
                    </div>
                </div>
            </div>

            <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200 mt-6">
                <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><CreditCard size={18} className="text-emerald-600"/> Paramètres des ventes</h3>
                
                <div className="p-4 bg-orange-50 border border-orange-200 rounded-xl mb-6">
                    <label className="flex items-center justify-between cursor-pointer">
                        <div>
                            <span className="text-sm font-bold text-orange-900">Autoriser les nouvelles commandes (Ventes)</span>
                            <p className="text-[10px] text-orange-700 mt-1">Désactivez ceci pour empêcher temporairement les clients de payer/créer de nouveaux panneaux.</p>
                        </div>
                        <div className={`w-12 h-6 rounded-full transition-colors relative shrink-0 ml-4 ${settingsData.allow_new_purchases === '1' ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                            <div className={`absolute top-1 bg-white w-4 h-4 rounded-full transition-transform ${settingsData.allow_new_purchases === '1' ? 'translate-x-7' : 'translate-x-1'}`}></div>
                        </div>
                        <input type="checkbox" checked={settingsData.allow_new_purchases === '1'} onChange={e => setSettingsData({...settingsData, allow_new_purchases: e.target.checked ? '1' : '0'})} className="hidden" />
                    </label>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                    <window.PriceInput label="Abonnement mensuel" value={settingsData.rentalMo} onChange={v => setSettingsData({...settingsData, rentalMo: v})} />
                    <window.PriceInput label="Achat définitif" value={settingsData.purchase} onChange={v => setSettingsData({...settingsData, purchase: v})} />
                    <window.PriceInput label="Hébergement annuel" value={settingsData.hostingYr} onChange={v => setSettingsData({...settingsData, hostingYr: v})} />
                    
                    <window.PriceInput label="Panneau physique (1er)" value={settingsData.boardFirst} onChange={v => setSettingsData({...settingsData, boardFirst: v})} />
                    <window.PriceInput label="Panneau physique (suivants)" value={settingsData.boardAdd} onChange={v => setSettingsData({...settingsData, boardAdd: v})} />
                    <window.PriceInput label="Option marque blanche" value={settingsData.noAds} onChange={v => setSettingsData({...settingsData, noAds: v})} />
                </div>
                
                <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2 border-t pt-6"><FileText size={18} className="text-emerald-600"/> Mentions légales (CGV et RGPD)</h3>
                <div className="space-y-4 mb-6">
                    <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Conditions générales de vente</label><textarea value={settingsData.cgv || ''} onChange={e=>setSettingsData({...settingsData, cgv: e.target.value})} rows="4" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition custom-scrollbar"></textarea></div>
                    <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Politique de confidentialité (RGPD)</label><textarea value={settingsData.rgpd || ''} onChange={e=>setSettingsData({...settingsData, rgpd: e.target.value})} rows="4" className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition custom-scrollbar"></textarea></div>
                </div>

                <div className="bg-slate-50 rounded-2xl p-4 sm:p-6 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"/> Émetteur (facturation)</h3>
                        <button onClick={handleAutoFill} className="text-xs font-bold text-blue-700 bg-blue-100 hover:bg-blue-200 px-3 py-1.5 rounded-lg flex items-center gap-1 transition shadow-sm"><Zap size={14}/> Saisie automatique</button>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">Raison sociale</label><input value={settingsData.billing_company || ''} onChange={e=>setSettingsData({...settingsData, billing_company: e.target.value})} className="w-full border border-slate-200 rounded-lg p-2 text-sm outline-none focus:border-slate-400 bg-white" /></div>
                        <div className="space-y-1"><label className="text-xs font-bold text-slate-500 uppercase block">SIRET</label><input value={settingsData.billing_siret || ''} onChange={e=>setSettingsData({...settingsData, billing_siret: e.target.value})} className="w-full border border-slate-200 rounded-lg p-2 text-sm outline-none focus:border-slate-400 bg-white" /></div>
                        <div className="space-y-1 sm:col-span-2"><label className="text-xs font-bold text-slate-500 uppercase block">Adresse</label><input value={settingsData.billing_address || ''} onChange={e=>setSettingsData({...settingsData, billing_address: e.target.value})} className="w-full border border-slate-200 rounded-lg p-2 text-sm outline-none focus:border-slate-400 bg-white" /></div>
                        <div className="space-y-1 sm:col-span-2 mt-2">
                            <label className="text-xs font-bold text-slate-500 uppercase block">Texte légal (bas de facture)</label>
                            <textarea value={settingsData.billing_legalText || ''} onChange={e=>setSettingsData({...settingsData, billing_legalText: e.target.value})} rows="2" className="w-full border border-slate-200 rounded-lg p-2 text-sm outline-none focus:border-slate-400 bg-white custom-scrollbar" placeholder="Ex: SAS au capital de..."></textarea>
                        </div>
                    </div>

                    <div className="pt-4 border-t border-slate-200 mt-2">
                        <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 sur la plateforme.</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-3 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={settingsData.billing_tva || ''} onChange={e=>setSettingsData({...settingsData, billing_tva: e.target.value})} placeholder="FR..." className="w-full border border-slate-200 rounded-lg p-2 text-sm outline-none focus:border-slate-400 uppercase bg-white" />
                            </div>
                        )}
                    </div>
                </div>

                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200 mt-6">
                    <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><AlertTriangle size={18} className="text-emerald-600"/> Bandeaux d'information</h3>
                    <p className="text-xs text-slate-500 mb-4">Affichez des messages importantes aux utilisateurs de la plateforme.</p>
                    <div className="space-y-6">
                        <div className="p-4 bg-orange-50 border border-orange-200 rounded-xl">
                            <label className="flex items-center justify-between cursor-pointer mb-3">
                                <span className="text-sm font-bold text-orange-900">Bandeau global (Orange)</span>
                                <input type="checkbox" checked={settingsData.site_banner_active === '1'} onChange={e => setSettingsData({...settingsData, site_banner_active: e.target.checked ? '1' : '0'})} className="w-5 h-5 accent-orange-600" />
                            </label>
                            <p className="text-[10px] text-orange-700 mb-2">Visible par les clients et visiteurs (sauf espace riverain).</p>
                            <textarea value={settingsData.site_banner_msg || ''} onChange={e=>setSettingsData({...settingsData, site_banner_msg: e.target.value})} rows="2" placeholder="Ex: Maintenance prévue ce soir à 20h..." className="w-full border-2 border-orange-200 rounded-xl p-3 text-sm focus:border-orange-500 outline-none transition custom-scrollbar"></textarea>
                        </div>
                        
                        <div className="p-4 bg-blue-50 border border-blue-200 rounded-xl">
                            <label className="flex items-center justify-between cursor-pointer mb-3">
                                <span className="text-sm font-bold text-blue-900">Bandeau espace riverain (Bleu)</span>
                                <input type="checkbox" checked={settingsData.panel_banner_active === '1'} onChange={e => setSettingsData({...settingsData, panel_banner_active: e.target.checked ? '1' : '0'})} className="w-5 h-5 accent-blue-600" />
                            </label>
                            <p className="text-[10px] text-blue-700 mb-2">Visible uniquement par les riverains qui scannent un panneau.</p>
                            <textarea value={settingsData.panel_banner_msg || ''} onChange={e=>setSettingsData({...settingsData, panel_banner_msg: e.target.value})} rows="2" placeholder="Ex: Bienvenue sur l'espace d'information..." className="w-full border-2 border-blue-200 rounded-xl p-3 text-sm focus:border-blue-500 outline-none transition custom-scrollbar"></textarea>
                        </div>
                    </div>
                </div>

                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200 mt-6">
                    <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2"><ShieldAlert size={18} className="text-red-600"/> Modération et mots-clés</h3>
                    <p className="text-xs text-slate-500 mb-4">Ces listes permettent de détecter les panneaux ou messages ne respectant pas les règles de bienséance. (Mots séparés par des virgules)</p>
                    <div className="space-y-4">
                        <div>
                            <label className="text-xs font-bold text-red-600 uppercase block mb-1">Liste noire (bloquante)</label>
                            <textarea value={settingsData.blacklist || ''} onChange={e=>setSettingsData({...settingsData, blacklist: e.target.value})} rows="3" className="w-full border-2 border-red-200 rounded-xl p-3 text-sm focus:border-red-500 outline-none transition custom-scrollbar"></textarea>
                        </div>
                        <div>
                            <label className="text-xs font-bold text-amber-600 uppercase block mb-1">Liste grise (alerte si {'>'} 2)</label>
                            <textarea value={settingsData.greylist || ''} onChange={e=>setSettingsData({...settingsData, greylist: e.target.value})} rows="3" className="w-full border-2 border-amber-200 rounded-xl p-3 text-sm focus:border-amber-500 outline-none transition custom-scrollbar"></textarea>
                        </div>
                    </div>
                </div>

                <div className="bg-white rounded-3xl mt-6 p-6 shadow-sm border border-slate-200">
                    <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2"><Settings size={18} className="text-emerald-600"/> Options du mode simplifié</h3>
                    <p className="text-xs text-slate-500 mb-6">Sélectionnez les fonctionnalités accessibles aux clients utilisant l'interface "Simplifiée".</p>
                    
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        {[
                            { key: 'simp_opt_description', label: 'Description des travaux' },
                            { key: 'simp_opt_image', label: 'Image du panneau' },
                            { key: 'simp_opt_theme', label: 'Couleur du thème' },
                            { key: 'simp_opt_link', label: 'Lien promoteur' },
                            { key: 'simp_opt_emergency', label: 'N° d\'urgence' },
                            { key: 'simp_opt_schedule', label: 'Horaires des nuisances' }
                        ].map(opt => (
                            <label key={opt.key} className="flex items-center justify-between p-4 border border-slate-200 rounded-xl cursor-pointer hover:bg-slate-50 transition">
                                <span className="text-sm font-bold text-slate-700">{opt.label}</span>
                                <input type="checkbox" checked={settingsData[opt.key] === '1'} onChange={e => setSettingsData({...settingsData, [opt.key]: e.target.checked ? '1' : '0'})} className="w-5 h-5 accent-emerald-600" />
                            </label>
                        ))}
                    </div>
                </div>

                <div className="border-t pt-6 mt-6">
                    <label className="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-xl cursor-pointer">
                        <input type="checkbox" checked={settingsData.maintenance === '1'} onChange={e => setSettingsData({...settingsData, maintenance: e.target.checked ? '1' : '0'})} className="w-5 h-5 accent-red-600" />
                        <div><p className="text-sm font-bold text-red-900">Activer le mode maintenance</p><p className="text-xs text-red-700">Déconnecte tous les clients et bloque l'accès public.</p></div>
                    </label>
                </div>
                
                <button onClick={handleSaveSettings} disabled={isSaving} className="mt-6 w-full bg-slate-900 text-white py-4 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg disabled:opacity-50 flex items-center justify-center gap-2"><Save size={18}/> Sauvegarder la configuration globale</button>
            </div>
            
            {showTvaWarning && (
                <window.Modal title="Avertissement légal (émetteur)" onClose={() => setShowTvaWarning(false)}>
                    <div className="space-y-4">
                        <div className="bg-orange-50 text-orange-800 p-5 rounded-2xl border border-orange-200 text-sm leading-relaxed">
                            <p className="font-black mb-2 flex items-center gap-2"><AlertTriangle size={18}/> Exonération de TVA</p>
                            <p>En désactivant ce champ, vous indiquez que votre propre société (la plateforme eco-panneau) n'est pas assujettie à la TVA (ex : auto-entrepreneur).</p>
                            <p className="mt-2 font-bold">Conséquence immédiate :</p>
                            <ul className="list-disc pl-5 mt-1 space-y-1">
                                <li>Toutes vos futures factures seront émises <strong>sans TVA</strong> (Prix TTC = Prix HT).</li>
                                <li>La mention légale <em>"TVA non applicable, art. 293 B du CGI"</em> figurera sur les factures clients.</li>
                                <li>Les montants envoyés à Stripe ne seront plus majorés de 20%.</li>
                            </ul>
                        </div>
                        <div className="flex gap-3">
                            <button onClick={() => setShowTvaWarning(false)} className="flex-1 bg-slate-100 text-slate-700 py-3 rounded-xl font-bold hover:bg-slate-200 transition">Annuler</button>
                            <button onClick={confirmTvaExemption} className="flex-1 bg-emerald-600 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-emerald-700 transition shadow-lg">J'ai compris, désactiver la TVA</button>
                        </div>
                    </div>
                </window.Modal>
            )}

            {pwdRequest && (
                <window.Modal title={pwdRequest.title} onClose={() => setPwdRequest(null)} zIndex="z-[250]">
                    <div className="text-sm text-slate-600 mb-6 font-medium leading-relaxed">{pwdRequest.desc}</div>
                    <form onSubmit={(e) => {
                        e.preventDefault();
                        const pwd = e.target.pwd.value;
                        if(pwd) { pwdRequest.onConfirm(pwd); setPwdRequest(null); }
                    }}>
                        <input name="pwd" type="password" autoFocus required placeholder="Mot de passe administrateur..." className="w-full border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition mb-4" />
                        <button type="submit" className="w-full bg-slate-900 text-white py-3 rounded-xl font-black uppercase tracking-widest hover:bg-slate-800 transition shadow-lg">Confirmer l'action</button>
                    </form>
                </window.Modal>
            )}

            {promptDialog && <window.PromptModal {...promptDialog} zIndex="z-[250]" onCancel={() => setPromptDialog(null)} />}
        </div>
    );
};

/*
		EOF	========== [_www/_react/_admin_systeme.jsx]
*/