/**
 * =========================================================================
 * PLATEFORME ECO-PANNEAU.FR - VERSION 1.0.0
 * Interface Administrateur - Onglet Paramètres Système et Sécurité
 * =========================================================================
 */

// Helpers pour l'interface "Geek" (Configuration de bas niveau)
const GeekInput = ({ label, value, onChange, type = 'number', hint }) => (
    <div className="space-y-1 mb-4">
        <label className="text-[10px] font-bold text-slate-400 font-mono uppercase block">{label}</label>
        <input 
            type={type} 
            value={value} 
            onChange={onChange} 
            className="w-full bg-slate-950 border border-slate-700 rounded-lg p-2 text-sm text-emerald-400 font-mono focus:border-emerald-500 outline-none transition shadow-inner" 
        />
        {hint && <p className="text-[9px] text-slate-500 font-mono mt-1 leading-tight">{hint}</p>}
    </div>
);

const GeekTextarea = ({ label, value, onChange, hint }) => (
    <div className="space-y-1 mb-4">
        <label className="text-[10px] font-bold text-slate-400 font-mono uppercase block">{label}</label>
        <textarea 
            value={value} 
            onChange={onChange} 
            rows={3}
            className="w-full bg-slate-950 border border-slate-700 rounded-lg p-2.5 text-sm text-emerald-400 font-mono focus:border-emerald-500 outline-none transition shadow-inner resize-none custom-scrollbar" 
        />
        {hint && <p className="text-[9px] text-slate-500 font-mono mt-1 leading-tight">{hint}</p>}
    </div>
);

window.AdminSettingsTab = ({ data, refreshData, openLocalModal, openLocalDialog, closeCurrentLayer, activeModal, activeDialog, targetId }) => {
    const { useState, useEffect } = React;
    
    // Moteur de routage local (Fallback)
    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 [forceRender, setForceRender] = useState(0);
    useEffect(() => {
        if (!activeDialog) {
            const onPop = () => setForceRender(prev => prev + 1);
            window.addEventListener('popstate', onPop);
            return () => window.removeEventListener('popstate', onPop);
        }
    }, [activeDialog]);

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

    // RÉCUPÉRATION SÉCURISÉE DES COMPOSANTS (Suffixe "Icon")
    const ShieldAlertIcon = window.ShieldAlertIcon || (() => null);
    const CreditCardIcon = window.CreditCardIcon || (() => null);
    const FileTextIcon = window.FileTextIcon || (() => null);
    const SettingsIcon = window.SettingsIcon || (() => null);
    const EyeIcon = window.EyeIcon || (() => null);
    const ZapIcon = window.ZapIcon || (() => null);
    const SaveIcon = window.SaveIcon || (() => null);
    const LoaderIcon = window.LoaderIcon || (() => null);
    const SearchIcon = window.SearchIcon || (() => null);

    const PriceInput = window.PriceInput || (() => null);
    const Modal = window.Modal || (() => null);
    const Toggle = window.Toggle || (() => null);
    const FormInput = window.FormInput || (() => null);
    const FormTextarea = window.FormTextarea || (() => null);
    const PasswordPromptModal = window.PasswordPromptModal || (() => null);
    
    const Button = window.Button;

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

    const handleSiretLookup = async () => {
        if (!settings.billing_siret || settings.billing_siret.length < 9) {
            window.showToast("Veuillez saisir un SIREN (9) ou SIRET (14) valide.", "error");
            return;
        }
        
        const d = await window.apiFetch('system/sirene', {
            body: { q: settings.billing_siret },
            setLoading: setIsSaving,
            successMessage: "Informations récupérées avec succès."
        });

        if (d && d.data?.results?.[0]) {
            const ent = d.data.results[0];
            setSettings({
                ...settings,
                billing_company: ent.nom_complet || settings.billing_company,
                billing_address: ent.siege?.geo_adresse || settings.billing_address
            });
        } else if (d) {
            window.showToast("Entreprise introuvable.", "error");
        }
    };

    const handleSave = async () => {
        const isMaintenanceChanged = settings.maintenance !== data.settings?.maintenance;
        const isPurchasesChanged = settings.allow_new_purchases !== data.settings?.allow_new_purchases;
        
        if (isMaintenanceChanged || isPurchasesChanged) {
            setPwdRequestData({
                title: "Confirmation de sécurité",
                desc: "La modification des paramètres d'accès (Maintenance ou Achats) nécessite le mot de passe admin :",
                onConfirm: async (pwd) => {
                    await executeSave(pwd);
                }
            });
            routerOpenDialog('pwd_request');
            return;
        }
        await executeSave();
    };

    const executeSave = async (pwd = null) => {
        const payload = { 
            ...settings,
            price_rentalMo: prices.rentalMo, price_purchase: prices.purchase, price_hostingYr: prices.hostingYr, 
            price_boardFirst: prices.boardFirst, price_boardAdd: prices.boardAdd, price_noAds: prices.noAds
        };
        if (pwd) payload.pwd = pwd;

        const d = await window.apiFetch('settings/update', {
            body: payload,
            setLoading: setIsSaving,
            successMessage: "Paramètres sauvegardés avec succès !"
        });

        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">Paramètres système</h1>
                        <p className="text-slate-500 font-medium">Configuration globale de <a href="https://eco-panneau.fr" target="_blank" rel="noopener noreferrer" className="text-emerald-600 hover:underline font-bold">eco-panneau.fr</a>.</p>
                    </div>
                </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-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">{CreditCardIcon && <CreditCardIcon size={18} className="text-blue-600"/>} Tarification (HT)</h3>
                        <div className="grid grid-cols-2 gap-4">
                            {PriceInput && <PriceInput label="Abonnement mensuel" value={prices.rentalMo || 0} onChange={v => updatePrice('rentalMo', v)} />}
                            {PriceInput && <PriceInput label="Achat unique" value={prices.purchase || 0} onChange={v => updatePrice('purchase', v)} />}
                            {PriceInput && <PriceInput label="Hébergement annuel" value={prices.hostingYr || 0} onChange={v => updatePrice('hostingYr', v)} />}
                            {PriceInput && <PriceInput label="Impression A1 (1er)" value={prices.boardFirst || 0} onChange={v => updatePrice('boardFirst', v)} />}
                            {PriceInput && <PriceInput label="Impression A1 (suiv.)" value={prices.boardAdd || 0} onChange={v => updatePrice('boardAdd', v)} />}
                            {PriceInput && <PriceInput label="Option sans pub" value={prices.noAds || 0} onChange={v => updatePrice('noAds', v)} />}
                        </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">{FileTextIcon && <FileTextIcon size={18} className="text-emerald-600"/>} Informations de facturation</h3>
                        <div className="space-y-4">
                            {FormInput && <FormInput label="Raison sociale" value={settings.billing_company || ''} onChange={e=>updateSetting('billing_company', e.target.value)} />}
                            
                            <div className="space-y-1">
                                <label className="text-xs font-bold text-slate-500 uppercase block">N° SIRET</label>
                                <div className="flex gap-2">
                                    <input value={settings.billing_siret || ''} onChange={e=>updateSetting('billing_siret', e.target.value.replace(/\s/g, ''))} className="flex-1 border-2 border-slate-200 rounded-xl p-3 text-sm focus:border-emerald-500 outline-none transition" maxLength={14} />
                                    <Button variant="info" icon={SearchIcon} type="button" onClick={handleSiretLookup} disabled={isSaving || (settings.billing_siret || '').length < 9} className="px-4 py-3">
                                        <span className="hidden sm:inline">Rechercher</span>
                                    </Button>
                                </div>
                            </div>
                            
                            {FormTextarea && <FormTextarea label="Adresse complète" value={settings.billing_address || ''} onChange={e=>updateSetting('billing_address', e.target.value)} rows={2} />}
                            
                            <div onClick={() => updateSetting('billing_has_tva', settings.billing_has_tva !== '0' ? '0' : '1')} className="pt-2 border-t border-slate-100 flex items-center justify-between cursor-pointer">
                                <span className="text-sm font-bold text-slate-700">Soumis à la TVA</span>
                                {Toggle && <Toggle checked={settings.billing_has_tva !== '0'} onChange={(v) => updateSetting('billing_has_tva', v ? '1' : '0')} variant="success" />}
                            </div>
                            
                            {settings.billing_has_tva !== '0' && FormInput && (
                                <FormInput label="TVA intracommunautaire" value={settings.billing_tva || ''} onChange={e=>updateSetting('billing_tva', e.target.value)} className="uppercase" />
                            )}
                            
                            {FormTextarea && <FormTextarea label="Mentions légales pied de facture" value={settings.billing_legalText || ''} onChange={e=>updateSetting('billing_legalText', e.target.value)} rows={3} />}
                        </div>
                    </div>
                </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-200">
                        <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2">{SettingsIcon && <SettingsIcon size={18} className="text-slate-600"/>} Options de l'Éditeur simplifié (clients)</h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {[
                                { id: 'simp_opt_description', label: 'Description du projet' },
                                { id: 'simp_opt_image', label: 'Photo d\'illustration' },
                                { id: 'simp_opt_theme', label: 'Couleur du thème public' },
                                { id: 'simp_opt_link', label: 'Lien site web promoteur' },
                                { id: 'simp_opt_emergency', label: 'Téléphone d\'urgence 24/7' },
                                { id: 'simp_opt_schedule', label: 'Horaires travaux bruyants' },
                                { id: 'simp_opt_hide_intervenants', label: 'Option : Masquer l\'équipe' },
                                { id: 'simp_opt_hide_lots', label: 'Option : Masquer les lots' },
                                { id: 'simp_opt_hide_legal', label: 'Option : Masquer l\'arrêté' }
                            ].map(opt => (
                                <div key={opt.id} onClick={() => updateSetting(opt.id, settings[opt.id] === '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">
                                    <span className="font-bold text-slate-700 text-sm">{opt.label}</span>
                                    {Toggle && <Toggle checked={settings[opt.id] === '1'} onChange={(v) => updateSetting(opt.id, 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">{EyeIcon && <EyeIcon size={18} className="text-blue-600"/>} Bandeaux d'information (bannières)</h3>
                        <div className="grid grid-cols-1 gap-6">
                            <div className="space-y-4">
                                <div className="flex items-center justify-between pb-2 border-b border-slate-100 cursor-pointer" onClick={() => updateSetting('site_banner_active', settings.site_banner_active === '1' ? '0' : '1')}>
                                    <h4 className="font-bold text-slate-800">Espace client / admin</h4>
                                    {Toggle && <Toggle checked={settings.site_banner_active === '1'} onChange={(v) => updateSetting('site_banner_active', v ? '1' : '0')} variant="warning" />}
                                </div>
                                {FormInput && <FormInput label="Message du bandeau (HTML autorisé)" value={settings.site_banner_msg || ''} onChange={e=>updateSetting('site_banner_msg', e.target.value)} className="font-mono text-xs" />}
                            </div>
                            
                            <div className="space-y-4 pt-4 border-t border-slate-100">
                                <div className="flex items-center justify-between pb-2 border-b border-slate-100 cursor-pointer" onClick={() => updateSetting('panel_banner_active', settings.panel_banner_active === '1' ? '0' : '1')}>
                                    <h4 className="font-bold text-slate-800">Panneaux publics (riverains)</h4>
                                    {Toggle && <Toggle checked={settings.panel_banner_active === '1'} onChange={(v) => updateSetting('panel_banner_active', v ? '1' : '0')} variant="warning" />}
                                </div>
                                {FormInput && <FormInput label="Message du bandeau (HTML autorisé)" value={settings.panel_banner_msg || ''} onChange={e=>updateSetting('panel_banner_msg', e.target.value)} className="font-mono text-xs" />}
                            </div>
                        </div>
                    </div>
                </div>

                <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-200">
                    <div className="flex justify-between items-center mb-6">
                        <h3 className="font-black text-slate-800 flex items-center gap-2">{ZapIcon && <ZapIcon size={18} className="text-purple-600"/>} Conditions de service (CGV / RGPD)</h3>
                        <span className="text-[10px] font-bold bg-purple-50 text-purple-700 px-3 py-1 rounded-lg uppercase tracking-widest">Support HTML</span>
                    </div>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {FormTextarea && (
                            <>
                                <FormTextarea label="Conditions générales de vente (CGV)" value={settings.cgv || ''} onChange={e=>updateSetting('cgv', e.target.value)} rows={15} className="font-mono bg-slate-50" />
                                <FormTextarea label="Politique de confidentialité (RGPD)" value={settings.rgpd || ''} onChange={e=>updateSetting('rgpd', e.target.value)} rows={15} className="font-mono bg-slate-50" />
                            </>
                        )}
                    </div>
                </div>

                {/* CENTRE DE CYBERDÉFENSE */}
                <div className="bg-slate-900 rounded-3xl p-6 sm:p-8 shadow-2xl border border-slate-800 relative overflow-hidden group">
                    <div className="absolute top-0 right-0 p-8 opacity-5 pointer-events-none group-hover:scale-110 transition-transform">
                        {ShieldAlertIcon && <ShieldAlertIcon size={150} />}
                    </div>
                    
                    <h3 className="font-black text-emerald-400 mb-2 flex items-center gap-2 text-xl tracking-tight relative z-10">
                        {ShieldAlertIcon && <ShieldAlertIcon size={24}/>} CYBERDÉFENSE ET MODÉRATION (AVANCÉ)
                    </h3>
                    <p className="text-slate-400 font-mono text-xs mb-8 relative z-10">Interface de contrôle de bas niveau des boucliers L4/L7 et des filtres sémantiques.</p>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8 relative z-10">
                        <div onClick={() => updateSetting('maintenance', settings.maintenance === '1' ? '0' : '1')} className="flex items-center justify-between p-4 bg-slate-800 border border-slate-700 rounded-xl cursor-pointer hover:bg-slate-700 transition shadow-sm">
                            <div><p className="font-bold text-slate-200 text-sm font-mono">SYS_MAINTENANCE_MODE</p><p className="text-xs text-slate-400 mt-1 font-mono">Verrouille l'accès public 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-800 border border-slate-700 rounded-xl cursor-pointer hover:bg-slate-700 transition shadow-sm">
                            <div><p className="font-bold text-slate-200 text-sm font-mono">ALLOW_NEW_PURCHASES</p><p className="text-xs text-slate-400 mt-1 font-mono">Accepter les nouvelles commandes</p></div>
                            {Toggle && <Toggle checked={settings.allow_new_purchases !== '0'} onChange={(v) => updateSetting('allow_new_purchases', v ? '1' : '0')} variant="success" />}
                        </div>
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 relative z-10">
                        <div className="bg-slate-800/50 p-5 rounded-2xl border border-slate-700/50">
                            <h4 className="text-sm font-bold text-indigo-400 uppercase tracking-widest mb-4 flex items-center gap-2 border-b border-slate-700 pb-2">
                                Moteur Sémantique
                            </h4>
                            <GeekTextarea 
                                label="BLACKLIST_WORDS (Rejet direct)" 
                                value={settings.blacklist || ''} 
                                onChange={e=>updateSetting('blacklist', e.target.value)}
                                hint="Séparés par des virgules. Bloque silencieusement le message."
                            />
                            <GeekTextarea 
                                label="GREYLIST_WORDS (Quarantaine)" 
                                value={settings.greylist || ''} 
                                onChange={e=>updateSetting('greylist', e.target.value)}
                                hint="Tolérance max : 2 mots. Au-delà = validation Admin requise."
                            />
                        </div>

                        <div className="bg-slate-800/50 p-5 rounded-2xl border border-slate-700/50">
                            <h4 className="text-sm font-bold text-orange-400 uppercase tracking-widest mb-4 flex items-center gap-2 border-b border-slate-700 pb-2">
                                Filtres par IP (L4)
                            </h4>
                            <GeekInput 
                                label="MAX_AUTH_FAILS (Anti-Bruteforce)" 
                                value={settings.sec_ip_limit ?? 5} 
                                onChange={e=>updateSetting('sec_ip_limit', e.target.value)} 
                                hint="Échecs de login avant blocage IP (15 min)."
                            />
                            <GeekInput 
                                label="MAX_EMAILS_PER_IP (Anti-Spam)" 
                                value={settings.mail_limit_count ?? 10} 
                                onChange={e=>updateSetting('mail_limit_count', e.target.value)} 
                                hint="Nb. max d'e-mails envoyés par une même IP."
                            />
                            <GeekInput 
                                label="EMAIL_WINDOW_MINUTES (Fenêtre)" 
                                value={settings.mail_limit_window ?? 15} 
                                onChange={e=>updateSetting('mail_limit_window', e.target.value)} 
                                hint="Durée d'analyse du quota e-mail (en minutes)."
                            />
                        </div>

                        <div className="bg-slate-800/50 p-5 rounded-2xl border border-red-900/30">
                            <h4 className="text-sm font-bold text-red-400 uppercase tracking-widest mb-4 flex items-center gap-2 border-b border-red-900/50 pb-2">
                                Bouclier Anti-DDoS (L7)
                            </h4>
                            <GeekInput 
                                label="GLOBAL_ACTIVE_IPS_THRESHOLD" 
                                value={settings.sec_global_limit ?? 1000} 
                                onChange={e=>updateSetting('sec_global_limit', e.target.value)} 
                                hint="IPs distinctes en 60s déclenchant le PANIC MODE."
                            />
                            <GeekInput 
                                label="PANIC_LOCK_MIN_DURATION" 
                                value={settings.sec_lock_min ?? 10} 
                                onChange={e=>updateSetting('sec_lock_min', e.target.value)} 
                                hint="Durée aléatoire minimale du verrouillage (min)."
                            />
                            <GeekInput 
                                label="PANIC_LOCK_MAX_DURATION" 
                                value={settings.sec_lock_max ?? 60} 
                                onChange={e=>updateSetting('sec_lock_max', e.target.value)} 
                                hint="Durée aléatoire maximale du verrouillage (min)."
                            />
                        </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 paramètres'}
                </Button>
            </div>

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

/* EOF ========== [_react/_admin_settings.jsx] */