// ECO-PANNEAU.FR - _react/admin/_admin_cyberdefense.jsx

window.pano_AdminCyberdefenseTab = ({ data, refreshData, openLocalDialog, closeCurrentLayer, activeDialog }) => {
    const { useState, useEffect } = React;
    
    // 1. - SÉCURITÉ ANTI-FUITE DE MÉMOIRE (Zéro-Dette)
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // 2. - Routage et modales
    const { activeDialog: hookActiveDialog, openDialog: hookOpenDialog, closeCurrentLayer: hookCloseLayer } = window.pano_useUrlModal();
    const routerActiveDialog = activeDialog || hookActiveDialog;
    const routerCloseLayer = closeCurrentLayer || hookCloseLayer;
    const routerOpenDialog = openLocalDialog || hookOpenDialog;

    // 3. - États
    const [isSaving, setIsSaving] = useState(false);
    const [settings, setSettings] = useState(data.settings || {});
    const [pwdRequestData, setPwdRequestData] = useState(null); 
    const [generatedKey, setGeneratedKey] = useState('');
    
    // États pour le statut de la Cyberdéfense (Blocages actifs)
    const [cyberStatus, setCyberStatus] = useState({ current_ip: '', blocked_list: [] });
    const [isLoadingStatus, setIsLoadingStatus] = useState(true);

    // 4. - Composants et Icônes
    const {
        ShieldAlertIcon, ShieldCheckIcon, SaveIcon, LoaderIcon, ActivityIcon, LockIcon, CopyIcon, RefreshCwIcon, Trash2Icon
    } = window.pano_getIcons();

    const {
        FormInput, FormTextarea, Toggle, Button, PasswordPromptModal, CardGrid, DataCard, IconBadge
    } = window.pano_getComponents();

    // 5. - Méthodes métier
    
    // 5.1 - Fetch du statut des blocages
    const fetchCyberStatus = async () => {
        setIsLoadingStatus(true);
        const d = await safeFetch('system/cyberdefense/status', { method: 'GET', silent: true });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d && d.status === 'success') {
            setCyberStatus(d.data);
        }
        setIsLoadingStatus(false);
    };

    useEffect(() => {
        fetchCyberStatus();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 5.2 - Action : Débloquer une IP
    const handleUnblock = async (hash) => {
        const d = await safeFetch('system/cyberdefense/unblock', {
            body: { hash },
            setLoading: setIsSaving,
            successMessage: 'Accès débloqué avec succès.'
        });
        
        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
        
        if (d) fetchCyberStatus();
    };

    const updateSetting = (key, val) => setSettings({ ...settings, [key]: val });

    const handleSave = async () => {
        const payload = {};
        let localHasChanges = false;

        const protectedFields = [
            'maintenance', 'allow_new_purchases', 'blacklist', 'greylist', 
            'sec_ip_limit', 'mail_limit_count', 'mail_limit_window', 
            'sec_global_limit', 'sec_lock_min', 'sec_lock_max',
            'honeypot_min_seconds' // AJOUT DU HONEYPOT
        ];

        for (const key of protectedFields) {
            const oldVal = String(data.settings?.[key] ?? '').replace(/\r\n/g, '\n');
            const newVal = String(settings[key] ?? '').replace(/\r\n/g, '\n');
            
            if (oldVal !== newVal) {
                payload[key] = settings[key];
                localHasChanges = true;
            }
        }

        if (!localHasChanges) {
            if (window.pano_showToast) window.pano_showToast("Aucune modification à sauvegarder.", "info");
            return;
        }

        setPwdRequestData({
            title: "Sécurité Zéro-Trust",
            desc: "La modification des paramètres de cyberdéfense nécessite votre clé de sécurité globale (AES_KEY_CONFIRM) :",
            onConfirm: async (pwd) => {
                const d = await executeSave({ ...payload, pwd });
                if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit
                if (d) {
                    routerCloseLayer();
                }
            }
        });
        routerOpenDialog('pwd_request');
    };

    const executeSave = async (finalPayload) => {
        const d = await safeFetch('settings/update', {
            body: finalPayload,
            setLoading: setIsSaving,
            successMessage: "Règles de cyberdéfense mises à jour !"
        });

        if (!isMounted.current) return; // SÉCURITÉ : Coupe-circuit

        if (d) {
            refreshData();
        }
        return d;
    };

    const generateNewKey = () => {
        const array = new Uint8Array(32);
        crypto.getRandomValues(array);
        const hex = Array.from(array).map(b => b.toString(16).padStart(2, '0')).join('');
        setGeneratedKey(hex);
    };

    // 5.3 - Vérification de conformité comptable
    const isBillingComplete = !!(
        data.settings?.billing_company?.trim() && 
        data.settings?.billing_address?.trim() && 
        data.settings?.billing_siret?.trim() &&
        (data.settings?.billing_has_tva === '0' || data.settings?.billing_tva?.trim())
    );

    // 5.4 - Calcul de "hasChanges" pour afficher/griser le bouton "Sauvegarder"
    let hasChanges = false;
    const cyberFields = [
        'maintenance', 'allow_new_purchases', 'blacklist', 'greylist', 
        'sec_ip_limit', 'mail_limit_count', 'mail_limit_window', 
        'sec_global_limit', 'sec_lock_min', 'sec_lock_max',
        'honeypot_min_seconds' // AJOUT DU HONEYPOT
    ];

    for (const key of cyberFields) {
        const oldVal = String(data.settings?.[key] ?? '').replace(/\r\n/g, '\n');
        const newVal = String(settings[key] ?? '').replace(/\r\n/g, '\n');
        if (oldVal !== newVal) {
            hasChanges = true;
            break;
        }
    }

    // 6. - Rendu UI
    return (
        <>
            <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 relative pb-24 min-w-0 w-full overflow-x-hidden">
                <div className="flex justify-between items-center mb-2 min-w-0 w-full">
                    <div className="min-w-0">
                        <h1 className="text-3xl font-black text-slate-800 break-words">Cyberdéfense</h1>
                        <p className="text-slate-500 font-medium break-words leading-relaxed">Contrôle des boucliers réseau, filtres sémantiques et accès globaux.</p>
                    </div>
                </div>

                <CardGrid minWidth="350px">
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words">
                            <LockIcon size={18} className="text-slate-600 shrink-0"/> Contrôle d'accès global
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            <div onClick={() => updateSetting('maintenance', settings.maintenance === '1' ? '0' : '1')} className="flex items-center justify-between p-4 bg-slate-50 border border-slate-100 rounded-xl cursor-pointer hover:bg-slate-100 transition shadow-sm min-w-0">
                                <div className="min-w-0 flex-1 pr-4">
                                    <p className="font-bold text-slate-800 text-sm break-words leading-tight">Mode maintenance</p>
                                    <p className="text-xs text-slate-500 mt-1 break-words leading-relaxed">Verrouille l'accès public et client au portail.</p>
                                </div>
                                {Toggle && <div className="shrink-0"><Toggle checked={settings.maintenance === '1'} onChange={(v) => updateSetting('maintenance', v ? '1' : '0')} variant="danger" /></div>}
                            </div>
                            
                            <div 
                                onClick={() => { 
                                    if(isBillingComplete) updateSetting('allow_new_purchases', settings.allow_new_purchases !== '0' ? '0' : '1'); 
                                }} 
                                className={`flex items-center justify-between p-4 bg-slate-50 border border-slate-100 rounded-xl transition shadow-sm min-w-0 ${!isBillingComplete ? 'opacity-70 cursor-not-allowed' : 'cursor-pointer hover:bg-slate-100'}`}
                            >
                                <div className="min-w-0 flex-1 pr-4">
                                    <p className="font-bold text-slate-800 text-sm break-words leading-tight">Autoriser les commandes</p>
                                    <p className="text-xs text-slate-500 mt-1 break-words leading-relaxed">Autoriser la validation et le paiement de nouveaux panneaux.</p>
                                    {!isBillingComplete && (
                                        <p className="text-[10px] text-red-500 font-bold mt-1 leading-tight break-words">
                                            Requiert la configuration complète des informations de facturation dans l'onglet Paramètres système (raison sociale, adresse, SIRET, TVA).
                                        </p>
                                    )}
                                </div>
                                {Toggle && <div className="shrink-0"><Toggle disabled={!isBillingComplete} checked={isBillingComplete && settings.allow_new_purchases !== '0'} onChange={(v) => { if(isBillingComplete) updateSetting('allow_new_purchases', v ? '1' : '0'); }} variant="success" /></div>}
                            </div>
                        </div>
                    </DataCard>

                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words">
                            <ShieldCheckIcon size={18} className="text-indigo-600 shrink-0"/> Moteur sémantique
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {FormTextarea && (
                                <>
                                    <FormTextarea 
                                        label="Mots interdits (Liste noire)" 
                                        value={settings.blacklist || ''} 
                                        onChange={e=>updateSetting('blacklist', e.target.value)}
                                        hint="Mots séparés par des virgules. Rejet silencieux immédiat."
                                        rows={3}
                                        className="min-w-0 w-full"
                                    />
                                    <FormTextarea 
                                        label="Mots sensibles (Liste grise)" 
                                        value={settings.greylist || ''} 
                                        onChange={e=>updateSetting('greylist', e.target.value)}
                                        hint="Tolérance maximale : 2 occurrences. Au-delà, validation requise."
                                        rows={3}
                                        className="min-w-0 w-full"
                                    />
                                </>
                            )}
                        </div>
                    </DataCard>
                </CardGrid>

                <CardGrid minWidth="350px">
                    {/* BLOC : ÉTAT DES BLOCAGES ACTIFS */}
                    <DataCard className="min-w-0 w-full lg:col-span-full">
                        <div className="flex justify-between items-center mb-4 border-b border-slate-100 pb-3 min-w-0">
                            <h3 className="font-black text-slate-800 flex items-center gap-2 break-words">
                                <ShieldAlertIcon size={18} className="text-red-600 shrink-0"/> Blocages actifs
                            </h3>
                            <Button variant="ghost" shape="square" icon={RefreshCwIcon} onClick={fetchCyberStatus} disabled={isLoadingStatus} className="text-slate-400 hover:text-slate-600 hover:bg-slate-100 p-2 shadow-none border-none" title="Actualiser" />
                        </div>
                        
                        <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 mb-4 flex flex-col sm:flex-row justify-between sm:items-center gap-4 min-w-0">
                            <div className="min-w-0">
                                <p className="text-xs font-bold text-slate-500 uppercase tracking-widest break-words leading-tight mb-1">Votre IP actuelle</p>
                                <p className="text-lg font-black text-slate-800 break-words leading-tight">{cyberStatus.current_ip || 'Chargement...'}</p>
                                <p className="text-[10px] text-slate-500 mt-1 leading-relaxed break-words">Pour vous prémunir des blocages de sécurité lors de vos tests, vous pouvez inscrire cette IP dans le fichier <strong className="font-mono bg-white px-1 py-0.5 rounded border border-slate-200">_whiteListe-[*****].txt</strong> situé à la racine de votre hébergement.</p>
                            </div>
                            <div className="shrink-0 self-end sm:self-auto">
                                <IconBadge icon={ActivityIcon} variant="success" />
                            </div>
                        </div>

                        {isLoadingStatus ? (
                            <div className="p-4 text-center text-slate-500 flex items-center justify-center gap-2"><LoaderIcon className="animate-spin shrink-0"/> Chargement des statuts...</div>
                        ) : cyberStatus.blocked_list.length === 0 ? (
                            <div className="p-6 text-center text-slate-500 border border-slate-200 border-dashed rounded-xl bg-slate-50 min-w-0">
                                <ShieldCheckIcon size={32} className="mx-auto mb-2 opacity-50 shrink-0"/>
                                <p className="font-medium break-words">Aucune adresse IP n'est actuellement bloquée.</p>
                            </div>
                        ) : (
                            <div className="space-y-3 min-w-0">
                                {cyberStatus.blocked_list.map((b, i) => (
                                    <div key={i} className="flex flex-col sm:flex-row justify-between items-start sm:items-center p-3 sm:p-4 bg-red-50 border border-red-100 rounded-xl gap-3 min-w-0">
                                        <div className="min-w-0 flex-1">
                                            <p className="font-mono text-xs font-bold text-red-800 break-all leading-tight" title={b.ip}>{b.ip}</p>
                                            <p className="text-[10px] text-red-600 mt-1 uppercase tracking-widest font-bold break-words leading-tight">
                                                Bloqué jusqu'au : {new Date(b.locked_until.replace(' ', 'T')).toLocaleString('fr-FR')} • {b.attempts} tentatives
                                            </p>
                                        </div>
                                        <Button variant="dangerSolid" icon={RefreshCwIcon} onClick={() => handleUnblock(b.ip)} disabled={isSaving} className="text-xs py-2 px-4 shrink-0 shadow-md">
                                            Débloquer
                                        </Button>
                                    </div>
                                ))}
                            </div>
                        )}
                    </DataCard>

                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words">
                            <ActivityIcon size={18} className="text-orange-600 shrink-0"/> Filtres IP et anti-spam (L4)
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 min-w-0 w-full">
                            {FormInput && (
                                <>
                                    <FormInput 
                                        type="number" 
                                        label="Échecs de connexion" 
                                        value={settings.sec_ip_limit ?? 5} 
                                        onChange={e=>updateSetting('sec_ip_limit', e.target.value)} 
                                        hint="Nb. max d'échecs (15 min)"
                                        className="min-w-0 w-full"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Honeypot Anti-Bot" 
                                        value={settings.honeypot_min_seconds ?? 3} 
                                        onChange={e=>updateSetting('honeypot_min_seconds', e.target.value)} 
                                        hint="Délai min. saisie (sec)"
                                        className="min-w-0 w-full"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Quota e-mails" 
                                        value={settings.mail_limit_count ?? 10} 
                                        onChange={e=>updateSetting('mail_limit_count', e.target.value)} 
                                        hint="Messages max / IP"
                                        className="min-w-0 w-full"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Fenêtre d'analyse" 
                                        value={settings.mail_limit_window ?? 15} 
                                        onChange={e=>updateSetting('mail_limit_window', e.target.value)} 
                                        hint="Durée en minutes"
                                        className="min-w-0 w-full"
                                    />
                                </>
                            )}
                        </div>
                    </DataCard>

                    <DataCard variant="danger" className="min-w-0 w-full">
                        <h3 className="font-black text-red-700 mb-2 flex items-center gap-2 break-words">
                            <ShieldAlertIcon size={18} className="text-red-600 shrink-0"/> Bouclier anti-DDoS (L7)
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 min-w-0 w-full">
                            {FormInput && (
                                <>
                                    <FormInput 
                                        type="number" 
                                        label="Seuil critique global" 
                                        value={settings.sec_global_limit ?? 1000} 
                                        onChange={e=>updateSetting('sec_global_limit', e.target.value)} 
                                        hint="IPs distinctes / 60s"
                                        className="col-span-full min-w-0 w-full"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Verrouillage min." 
                                        value={settings.sec_lock_min ?? 10} 
                                        onChange={e=>updateSetting('sec_lock_min', e.target.value)} 
                                        hint="Durée minimale (min)"
                                        className="min-w-0 w-full"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Verrouillage max." 
                                        value={settings.sec_lock_max ?? 60} 
                                        onChange={e=>updateSetting('sec_lock_max', e.target.value)} 
                                        hint="Durée maximale (min)"
                                        className="min-w-0 w-full"
                                    />
                                </>
                            )}
                        </div>
                    </DataCard>
                </CardGrid>

                <div className="w-full min-w-0">
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words">
                            <LockIcon size={18} className="text-slate-600 shrink-0"/> Générateur de clés de sécurité
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            <p className="text-sm text-slate-500 break-words leading-relaxed">Générez une clé SHA-256 (64 caractères hexadécimaux) cryptographiquement sécurisée pour configurer les variables d'environnement de votre installation. L'opération est effectuée localement sur votre navigateur.</p>
                            <div className="flex gap-2 min-w-0 w-full">
                                <input 
                                    type="text" 
                                    readOnly 
                                    value={generatedKey} 
                                    placeholder="Cliquez sur générer pour obtenir une clé..."
                                    className="flex-1 border border-slate-200 rounded-xl p-3 text-sm font-mono outline-none bg-slate-50 text-slate-600 min-w-0"
                                />
                                <Button variant="secondary" shape="square" icon={RefreshCwIcon} onClick={generateNewKey} title="Générer une nouvelle clé" className="p-3 bg-white border border-slate-200 shrink-0" />
                                <Button variant="primary" shape="square" icon={CopyIcon} disabled={!generatedKey} onClick={() => { navigator.clipboard.writeText(generatedKey); if(window.pano_showToast) window.pano_showToast("Clé copiée avec succès", "success"); }} title="Copier la clé" className="p-3 shrink-0" />
                            </div>
                        </div>
                    </DataCard>
                </div>
            </div>

            <div className="fixed bottom-0 left-0 lg:left-[var(--sidebar-width)] right-0 bg-white/90 backdrop-blur-md border-t border-slate-200 p-4 sm:p-6 z-[100] shadow-[0_-10px_20px_rgba(0,0,0,0.05)] flex justify-center">
                <Button variant="dark" onClick={handleSave} disabled={isSaving || !hasChanges} icon={isSaving ? LoaderIcon : SaveIcon} className="w-full sm:w-auto px-8 py-3.5 uppercase tracking-widest justify-center">
                    {isSaving ? 'Enregistrement...' : 'Sauvegarder les règles'}
                </Button>
            </div>

            {routerActiveDialog === 'pwd_request' && pwdRequestData && PasswordPromptModal && (
                <PasswordPromptModal
                    title={pwdRequestData.title}
                    desc={pwdRequestData.desc}
                    onConfirm={pwdRequestData.onConfirm}
                    onCancel={routerCloseLayer}
                    isSaving={isSaving}
                />
            )}
        </>
    );
};

/* EOF ========== [_react/admin/_admin_cyberdefense.jsx] */