/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglet Cyberdéfense et Modération
 * =========================================================================
 */

window.pano_AdminCyberdefenseTab = ({ data, refreshData, openLocalDialog, closeCurrentLayer, activeDialog }) => {
    const { useState, useEffect } = React;
    
    const routerActiveDialog = activeDialog || new URLSearchParams(window.location.search).get('dialog');
    const routerCloseLayer = closeCurrentLayer || (() => window.history.back());
    const routerOpenDialog = openLocalDialog || ((type) => {
        const u = new URL(window.location);
        u.searchParams.set('dialog', type);
        window.history.pushState({ dialog: type }, '', u);
        window.dispatchEvent(new Event('popstate'));
    });

    const [isSaving, setIsSaving] = useState(false);
    const [settings, setSettings] = useState(data.settings || {});
    const [pwdRequestData, setPwdRequestData] = useState(null); 

    const {
        ShieldAlertIcon, ShieldCheckIcon, SaveIcon, LoaderIcon, ActivityIcon, MailIcon, LockIcon
    } = window.pano_getIcons();

    const FormInput = window.pano_FormInput || (() => null);
    const FormTextarea = window.pano_FormTextarea || (() => null);
    const Toggle = window.pano_Toggle || (() => null);
    const Button = window.pano_Button || (() => null);
    const PasswordPromptModal = window.pano_PasswordPromptModal || (() => null);

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

    const handleSave = async () => {
        const payload = {};
        let hasChanges = 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'
        ];

        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];
                hasChanges = true;
            }
        }

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

        setPwdRequestData({
            title: "Confirmation de sécurité",
            desc: "La modification des paramètres de sécurité ou d'accès nécessite le mot de passe administrateur :",
            onConfirm: async (pwd) => {
                await executeSave({ ...payload, pwd });
            }
        });
        routerOpenDialog('pwd_request');
    };

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

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

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

                <div className="grid grid-cols-[repeat(auto-fit,minmax(350px,1fr))] gap-6">
                    <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">
                            <LockIcon size={18} className="text-slate-600"/> Contrôle d'accès global
                        </h3>
                        <div className="space-y-4">
                            <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">
                                <div>
                                    <p className="font-bold text-slate-800 text-sm">Mode Maintenance</p>
                                    <p className="text-xs text-slate-500 mt-1">Verrouille l'accès public et client au portail.</p>
                                </div>
                                {Toggle && <Toggle checked={settings.maintenance === '1'} onChange={(v) => updateSetting('maintenance', v ? '1' : '0')} variant="danger" />}
                            </div>
                            
                            <div onClick={() => 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 cursor-pointer hover:bg-slate-100 transition shadow-sm">
                                <div>
                                    <p className="font-bold text-slate-800 text-sm">Nouvelles commandes</p>
                                    <p className="text-xs text-slate-500 mt-1">Autoriser la validation et le paiement de nouveaux panneaux.</p>
                                </div>
                                {Toggle && <Toggle checked={settings.allow_new_purchases !== '0'} onChange={(v) => updateSetting('allow_new_purchases', v ? '1' : '0')} variant="success" />}
                            </div>
                        </div>
                    </div>

                    <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">
                            <ShieldCheckIcon size={18} className="text-indigo-600"/> Moteur Sémantique
                        </h3>
                        <div className="space-y-4">
                            {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}
                                    />
                                    <FormTextarea 
                                        label="Mots sensibles (Liste grise)" 
                                        value={settings.greylist || ''} 
                                        onChange={e=>updateSetting('greylist', e.target.value)}
                                        hint="Tolérance max : 2 occurrences. Au-delà, validation requise."
                                        rows={3}
                                    />
                                </>
                            )}
                        </div>
                    </div>
                </div>

                <div className="grid grid-cols-[repeat(auto-fit,minmax(350px,1fr))] gap-6">
                    <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">
                            <ActivityIcon size={18} className="text-orange-600"/> Filtres IP & Anti-Spam (L4)
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {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="col-span-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"
                                    />
                                    <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"
                                    />
                                </>
                            )}
                        </div>
                    </div>

                    <div className="bg-white rounded-3xl p-6 shadow-sm border border-red-200 shadow-red-100/50">
                        <h3 className="font-black text-red-700 mb-6 flex items-center gap-2">
                            <ShieldAlertIcon size={18} className="text-red-600"/> Bouclier Anti-DDoS (L7)
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {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"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Verrouillage Min." 
                                        value={settings.sec_lock_min ?? 10} 
                                        onChange={e=>updateSetting('sec_lock_min', e.target.value)} 
                                        hint="Durée min. (minutes)"
                                    />
                                    <FormInput 
                                        type="number" 
                                        label="Verrouillage Max." 
                                        value={settings.sec_lock_max ?? 60} 
                                        onChange={e=>updateSetting('sec_lock_max', e.target.value)} 
                                        hint="Durée max. (minutes)"
                                    />
                                </>
                            )}
                        </div>
                    </div>
                </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-end">
                <Button variant="dark" onClick={handleSave} disabled={isSaving} 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_cyberdefense.jsx] */