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

window.pano_AdminSettingsTab = ({ data, refreshData, openLocalModal, openLocalDialog, closeCurrentLayer, activeModal, activeDialog, targetId }) => {
    const { useState, useEffect } = React;

    // ZÉRO-DETTE : Utilisation de notre Hook abstrait !
    const { isMounted, safeFetch } = window.pano_useSafeFetch();

    // 2. - Routage et modales
    const {
        activeDialog: hookActiveDialog,
        openDialog: hookOpenDialog,
        closeCurrentLayer: hookCloseLayer
    } = window.pano_useUrlModal ? 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 [prices, setPrices] = useState(data.prices || {});
    const [pwdRequestData, setPwdRequestData] = useState(null);
    const [confirmConfig, setConfirmConfig] = useState(null);

    // États des notifications Web Push
    const [pushStatus, setPushStatus] = useState('checking');
    const [pushSubscription, setPushSubscription] = useState(null);

    // 4. - Composants et Icônes
    const {
        CreditCardIcon, FileTextIcon, EyeIcon, ZapIcon,
        SaveIcon, LoaderIcon, SearchIcon, HardDriveIcon,
        RefreshCwIcon, BellIcon, SmartphoneIcon, ShieldAlertIcon
    } = window.pano_getIcons();

    const {
        PriceInput, Modal, Toggle, FormInput, FormTextarea,
        PasswordPromptModal, ConfirmModal, TextLogo, Button, DataCard
    } = window.pano_getComponents();

    // 5. - Initialisation des notifications Push
    useEffect(() => {
        const checkPushStatus = async () => {
            if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
                if (isMounted.current) setPushStatus('unsupported');
                return;
            }
            if (Notification.permission === 'denied') {
                if (isMounted.current) setPushStatus('denied');
                return;
            }
            try {
                const registration = await navigator.serviceWorker.ready;
                if (!isMounted.current) return;

                const sub = await registration.pushManager.getSubscription();
                if (!isMounted.current) return;

                if (sub) {
                    setPushSubscription(sub);
                    setPushStatus('subscribed');
                } else {
                    setPushStatus('unsubscribed');
                }
            } catch (e) {
                if (isMounted.current) setPushStatus('unsupported');
            }
        };
        checkPushStatus();
    }, [isMounted]);

    // 6. - Méthodes métier Push
    const subscribeToPush = async () => {
        setIsSaving(true);
        try {
            const permission = await Notification.requestPermission();
            if (!isMounted.current) return; 

            if (permission !== 'granted') {
                setPushStatus('denied');
                setIsSaving(false);
                return;
            }

            const registration = await navigator.serviceWorker.ready;
            if (!isMounted.current) return; 

            const vapidPublicKey = window.pano_CONFIG?.vapidPublicKey || 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
            
            const urlBase64ToUint8Array = (base64String) => {
                const padding = '='.repeat((4 - base64String.length % 4) % 4);
                const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
                const rawData = window.atob(base64);
                const outputArray = new Uint8Array(rawData.length);
                for (let i = 0; i < rawData.length; ++i) {
                    outputArray[i] = rawData.charCodeAt(i);
                }
                return outputArray;
            };

            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
            });

            if (!isMounted.current) return; 

            if (subscription) {
                const subData = JSON.parse(JSON.stringify(subscription));
                await safeFetch('system/push_subscribe', {
                    body: { endpoint: subData.endpoint, keys: subData.keys },
                    successMessage: "Notifications activées sur ce navigateur."
                });

                if (!isMounted.current) return; 

                setPushSubscription(subscription);
                setPushStatus('subscribed');
            }
        } catch (e) {
            if (!isMounted.current) return; 
            if (window.pano_showToast) window.pano_showToast("Erreur lors de l'activation des notifications.", "error");
        }
        if (isMounted.current) setIsSaving(false);
    };

    const unsubscribeFromPush = async () => {
        setIsSaving(true);
        try {
            if (pushSubscription) {
                const endpoint = pushSubscription.endpoint;
                await pushSubscription.unsubscribe();
                
                if (!isMounted.current) return; 

                setPushSubscription(null);
                setPushStatus('unsubscribed');
                
                await safeFetch('system/push_unsubscribe', {
                    body: { endpoint },
                    successMessage: "Notifications désactivées sur ce navigateur."
                });

                if (!isMounted.current) return; 
            }
        } catch (e) {
            if (!isMounted.current) return; 
            if (window.pano_showToast) window.pano_showToast("Erreur lors de la désactivation.", "error");
        }
        if (isMounted.current) setIsSaving(false);
    };

    const revokeAllPushLinks = (e) => {
        setConfirmConfig({
            title: "Rompre tous les liens de notification",
            message: "Êtes-vous sûr de vouloir révoquer les notifications push sur TOUS vos appareils (téléphones, ordinateurs, tablettes) ? Vous devrez les réactiver manuellement sur chaque appareil souhaité.",
            confirmText: "Oui, tout révoquer",
            isDestructive: true,
            onConfirm: async (evt) => {
                const d = await safeFetch('system/push_revoke_all', {
                    setLoading: setIsSaving,
                    successMessage: "Toutes les connexions de notifications ont été rompues."
                });
                
                if (!isMounted.current) return; 
                
                if (d) {
                    if (pushSubscription) {
                        try { await pushSubscription.unsubscribe(); } catch(err) {}
                        if (isMounted.current) {
                            setPushSubscription(null);
                            setPushStatus('unsubscribed');
                        }
                    }
                }
                routerCloseLayer(evt);
            },
            onCancel: routerCloseLayer
        });
        routerOpenDialog('confirm', null, e);
    };

    // 7. - Méthodes métier Paramètres
    const updateSetting = (key, val) => setSettings({ ...settings, [key]: val });
    const updatePrice = (key, val) => setPrices({ ...prices, [key]: val });

    const handleTvaToggle = (checked) => {
        const hasTva = checked ? '1' : '0';
        const newSettings = { ...settings, billing_has_tva: hasTva };
        
        if (hasTva == 1 && settings.billing_siret && settings.billing_siret.length >= 9 && !settings.billing_tva) {
            const siren = settings.billing_siret.substring(0, 9);
            const tvaKey = (12 + 3 * (parseInt(siren, 10) % 97)) % 97;
            newSettings.billing_tva = `FR${tvaKey.toString().padStart(2, '0')}${siren}`;
        }
        
        setSettings(newSettings);
    };

    const handleSiretLookup = async () => {
        if (!settings.billing_siret || settings.billing_siret.length < 9) {
            if (window.pano_showToast) window.pano_showToast("Veuillez saisir un SIREN (9) ou SIRET (14) valide.", "error");
            return;
        }

        const d = await safeFetch('systeme/siret_lookup', {
            body: { siret: settings.billing_siret },
            setLoading: setIsSaving,
            successMessage: "Informations récupérées avec succès."
        });

        if (!isMounted.current) return; 

        if (d && d.data) {
            const newSettings = {
                ...settings,
                billing_company: d.data.name || settings.billing_company,
                billing_address: d.data.address || settings.billing_address,
                billing_siret: d.data.siret || settings.billing_siret
            };
            if (settings.billing_has_tva != 0 && d.data.tva) {
                newSettings.billing_tva = d.data.tva;
            }
            setSettings(newSettings);
        } else if (d && window.pano_showToast) {
            window.pano_showToast("Entreprise introuvable.", "error");
        }
    };

    const handleSave = async (e, forceDisableOrders = false) => {
        const isBillingComplete = !!(
            settings.billing_company?.trim() && 
            settings.billing_address?.trim() && 
            settings.billing_siret?.trim() &&
            (settings.billing_has_tva == 0 || settings.billing_tva?.trim())
        );

        if (!isBillingComplete && settings.allow_new_purchases != 0 && forceDisableOrders !== true) {
            setConfirmConfig({
                title: "Informations de facturation incomplètes",
                message: "Il manque des informations de facturation obligatoires (Raison sociale, SIRET, Adresse, ou TVA intracommunautaire). Si vous enregistrez maintenant, l'autorisation des commandes sera automatiquement désactivée sur la plateforme. Voulez-vous continuer ?",
                confirmText: "Désactiver les commandes et sauver",
                cancelText: "Annuler pour compléter",
                type: "warning",
                isDestructive: false,
                onConfirm: (evt) => {
                    const newSet = { ...settings, allow_new_purchases: '0' };
                    setSettings(newSet);
                    routerCloseLayer(evt);
                    setTimeout(() => { if (isMounted.current) executePreSave(newSet, evt); }, 100);
                },
                onCancel: routerCloseLayer
            });
            routerOpenDialog('confirm', null, e);
            return;
        }

        await executePreSave(settings, e);
    };

    const executePreSave = async (currentSettings, evt) => {
        const payload = {};
        let isProtectedChanged = 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',
            'notif_delay_standard', 'notif_delay_support', 'cron_mail_limit', 'cron_support_ratio',
            'cron_batch_size', 'quota_step_gb'
        ];

        for (const key in currentSettings) {
            const oldVal = String(data.settings?.[key] ?? '').replace(/\r\n/g, '\n');
            const newVal = String(currentSettings[key] ?? '').replace(/\r\n/g, '\n');

            if (oldVal !== newVal) {
                payload[key] = currentSettings[key];
                if (protectedFields.includes(key)) {
                    isProtectedChanged = true;
                }
            }
        }

        const priceKeys = ['rentalMo', 'purchase', 'hostingYr', 'boardFirst', 'boardAdd', 'noAds', 'storage'];
        priceKeys.forEach(k => {
            const oldPrice = parseFloat(data.prices?.[k]) || 0;
            const newPrice = parseFloat(prices[k]) || 0;

            if (oldPrice !== newPrice) {
                payload['price_' + k] = prices[k];
            }
        });

        if (Object.keys(payload).length === 0) {
            if (window.pano_showToast) window.pano_showToast("Aucune modification à sauvegarder.", "info");
            return;
        }

        if (isProtectedChanged) {
            setPwdRequestData({
                title: "Sécurité Zéro-Trust",
                desc: "Cette modification impacte le cœur du système et nécessite votre clé de sécurité globale (AES_KEY_CONFIRM) :",
                onConfirm: async (pwd, submitEvt) => {
                    const d = await executeSave({ ...payload, pwd });
                    if (!isMounted.current) return; 
                    if (d) {
                        routerCloseLayer(submitEvt);
                    }
                }
            });
            routerOpenDialog('pwd_request', null, evt);
            return;
        }

        await executeSave(payload);
    };

    const executeSave = async (finalPayload) => {
        const d = await safeFetch('settings/update', {
            body: finalPayload,
            setLoading: setIsSaving
        });

        if (!isMounted.current) return; 

        if (d && d.status === 'success') {
            if (refreshData) refreshData();
            
            if (d.data && d.data.forced_downgrade) {
                setConfirmConfig({
                    title: "Sécurité d'exploitation",
                    message: "Vos paramètres ont été enregistrés. Toutefois, votre profil de facturation étant incomplet, le système a automatiquement verrouillé la 'Prise de commandes' pour éviter toute anomalie comptable ou juridique.",
                    confirmText: "J'ai compris",
                    cancelText: "Fermer",
                    type: "warning",
                    isDestructive: false,
                    onConfirm: (evt) => routerCloseLayer(evt),
                    onCancel: routerCloseLayer
                });
                routerOpenDialog('confirm', null);
            } else {
                if (window.pano_showToast) window.pano_showToast("Paramètres sauvegardés avec succès !", "success");
            }
        }
        return d;
    };

    let hasChanges = false;
    for (const key in settings) {
        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;
        }
    }
    if (!hasChanges) {
        const priceKeys = ['rentalMo', 'purchase', 'hostingYr', 'boardFirst', 'boardAdd', 'noAds', 'storage'];
        for (const k of priceKeys) {
            const oldPrice = parseFloat(data.prices?.[k]) || 0;
            const newPrice = parseFloat(prices[k]) || 0;
            if (oldPrice !== newPrice) {
                hasChanges = true;
                break;
            }
        }
    }

    const priceFields = [
        { key: 'rentalMo', label: 'Abonnement mensuel' },
        { key: 'purchase', label: 'Achat unique' },
        { key: 'hostingYr', label: 'Hébergement annuel' },
        { key: 'boardFirst', label: 'Impression A1 (1er)' },
        { key: 'boardAdd', label: 'Impression A1 (suiv.)' },
        { key: 'noAds', label: 'Option sans pub' }
    ];

    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">
                    <div className="min-w-0">
                        <h1 className="text-3xl font-black text-slate-800 break-words">Paramètres système</h1>
                        <p className="text-slate-500 font-medium flex items-center flex-wrap gap-1">Configuration globale de <TextLogo className="text-sm" />.</p>
                    </div>
                </div>

                <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 min-w-0 w-full">
                    {/* Tarification */}
                    <DataCard className="xl:col-span-5 2xl:col-span-4 min-w-0">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words"><CreditCardIcon size={18} className="text-blue-600 shrink-0"/> Tarification (HT)</h3>
                        <div className="grid grid-cols-1 gap-4 min-w-0 w-full">
                            {PriceInput && priceFields.map(field => (
                                <PriceInput key={field.key} label={field.label} value={prices[field.key] || 0} onChange={v => updatePrice(field.key, v)} className="min-w-0 w-full" />
                            ))}
                            
                            <div className="pt-4 mt-2 border-t border-slate-100 space-y-4">
                                <h4 className="font-bold text-slate-700 text-xs flex items-center gap-2 break-words uppercase tracking-widest"><HardDriveIcon size={14} className="shrink-0"/> Quotas et Stockage</h4>
                                {FormInput && <FormInput label="Volume d'un palier (Go)" type="number" min="1" value={settings.quota_step_gb || '10'} onChange={e=>updateSetting('quota_step_gb', e.target.value)} className="min-w-0 w-full" hint="Taille ajoutée lors d'un Upsell" />}
                                {PriceInput && <PriceInput label="Prix du palier (Mensuel)" value={prices['storage'] || 0} onChange={v => updatePrice('storage', v)} className="min-w-0 w-full" />}
                            </div>
                        </div>
                    </DataCard>

                    {/* Facturation */}
                    <DataCard className="xl:col-span-7 2xl:col-span-8 min-w-0">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words"><FileTextIcon size={18} className="text-emerald-600 shrink-0"/> Informations de facturation</h3>
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 min-w-0 w-full">
                            <div className="space-y-4 min-w-0 w-full">
                                <div className="space-y-1 min-w-0 w-full">
                                    <label className="text-xs font-bold text-slate-500 uppercase block break-words">N° SIRET</label>
                                    <div className="flex gap-2 min-w-0 w-full">
                                        <input 
                                            value={settings.billing_siret || ''} 
                                            onChange={e => {
                                                const cleanSiret = e.target.value.replace(/\D/g, '').substring(0, 14);
                                                updateSetting('billing_siret', cleanSiret);
                                            }} 
                                            className="flex-1 min-w-0 border-2 border-slate-200 rounded-xl p-3 text-sm font-bold text-slate-700 focus:border-emerald-500 outline-none transition" 
                                            maxLength={128} 
                                            placeholder="Recherche auto..." 
                                        />
                                        <Button variant="info" icon={SearchIcon} type="button" onClick={handleSiretLookup} disabled={isSaving || (settings.billing_siret || '').length < 9} className="px-4 py-3 shrink-0">
                                            <span className="hidden sm:inline">Rechercher</span>
                                        </Button>
                                    </div>
                                </div>
                                {FormInput && <FormInput label="Raison sociale" value={settings.billing_company || ''} onChange={e=>updateSetting('billing_company', e.target.value)} className="min-w-0 w-full" />}
                            </div>

                            <div className="space-y-4 min-w-0 w-full">
                                <div onClick={() => handleTvaToggle(settings.billing_has_tva != 0 ? false : true)} className="flex items-center justify-between cursor-pointer bg-slate-50 border border-slate-100 p-4 rounded-xl shadow-sm min-w-0">
                                    <span className="text-sm font-bold text-slate-700 break-words leading-tight pr-2">Soumis à la TVA</span>
                                    {Toggle && <div className="shrink-0"><Toggle checked={settings.billing_has_tva != 0} onChange={handleTvaToggle} variant="success" /></div>}
                                </div>
                                {settings.billing_has_tva != 0 && FormInput && <FormInput label="TVA intracommunautaire *" required value={settings.billing_tva || ''} onChange={e=>updateSetting('billing_tva', e.target.value)} className="uppercase font-bold min-w-0 w-full" />}
                            </div>

                            <div className="lg:col-span-2 space-y-4 min-w-0 w-full">
                                {FormTextarea && <FormTextarea label="Adresse complète" value={settings.billing_address || ''} onChange={e=>updateSetting('billing_address', e.target.value)} rows={2} className="min-w-0 w-full" />}
                                {FormTextarea && <FormTextarea label="Mentions légales pied de facture" value={settings.billing_legalText || ''} onChange={e=>updateSetting('billing_legalText', e.target.value)} rows={2} className="min-w-0 w-full" />}
                            </div>
                        </div>
                    </DataCard>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 min-w-0 w-full items-start">
                    {/* Bandeaux */}
                    <DataCard className="min-w-0">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words"><EyeIcon size={18} className="text-blue-600 shrink-0"/> Personnalisation et Bandeaux</h3>
                        <p className="text-sm text-slate-500 leading-relaxed mb-2 break-words">Affichez des messages d'information globaux aux utilisateurs connectés ou aux riverains.</p>

                        <div className="space-y-6 min-w-0 w-full">
                            <div className="space-y-3 bg-blue-50/50 p-4 rounded-xl border border-blue-100 min-w-0">
                                <div className="flex items-center justify-between cursor-pointer min-w-0 gap-2" onClick={() => updateSetting('site_banner_active', settings.site_banner_active == 1 ? '0' : '1')}>
                                    <h4 className="font-bold text-slate-800 text-sm break-words leading-tight flex-1">Bandeau Espace client et Admin</h4>
                                    {Toggle && <div className="shrink-0"><Toggle checked={settings.site_banner_active == 1} onChange={(v) => updateSetting('site_banner_active', v ? '1' : '0')} variant="warning" /></div>}
                                </div>
                                {settings.site_banner_active == 1 && 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 min-w-0 w-full" />}
                            </div>
                            
                            <div className="space-y-3 bg-amber-50/50 p-4 rounded-xl border border-amber-100 min-w-0">
                                <div className="flex items-center justify-between cursor-pointer min-w-0 gap-2" onClick={() => updateSetting('panel_banner_active', settings.panel_banner_active == 1 ? '0' : '1')}>
                                    <h4 className="font-bold text-slate-800 text-sm break-words leading-tight flex-1">Bandeau Panneaux publics</h4>
                                    {Toggle && <div className="shrink-0"><Toggle checked={settings.panel_banner_active == 1} onChange={(v) => updateSetting('panel_banner_active', v ? '1' : '0')} variant="warning" /></div>}
                                </div>
                                {settings.panel_banner_active == 1 && 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 min-w-0 w-full" />}
                            </div>
                        </div>
                    </DataCard>

                    {/* CRON et Notifications */}
                    <DataCard className="min-w-0">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words border-b border-slate-100 pb-3">
                            <RefreshCwIcon size={18} className="text-indigo-600 shrink-0"/> Moteur asynchrone et alertes
                        </h3>
                        
                        <div className="space-y-6">
                            {/* ALERTES SUR APPAREILS (PUSH) RENDU DISCRET */}
                            <div>
                                <h4 className="font-bold text-slate-700 text-sm mb-3">Alertes sur les appareils (Push)</h4>
                                <div className="flex flex-col sm:flex-row gap-4">
                                    <div className="flex-1 bg-slate-50 border border-slate-200 rounded-xl p-3 sm:p-4 flex items-center justify-between min-w-0">
                                        <div className="flex items-center gap-3 min-w-0">
                                            <SmartphoneIcon size={20} className="text-slate-400 shrink-0" />
                                            <div className="min-w-0">
                                                <p className="font-bold text-slate-700 text-xs break-words leading-tight">Navigateur actuel</p>
                                                <p className="text-[10px] text-slate-500 break-words leading-tight mt-0.5">
                                                    {pushStatus === 'checking' && "Vérification..."}
                                                    {pushStatus === 'unsupported' && "Non supporté par ce navigateur"}
                                                    {pushStatus === 'denied' && "Bloqué par le navigateur"}
                                                    {pushStatus === 'unsubscribed' && "Désactivé"}
                                                    {pushStatus === 'subscribed' && <span className="text-emerald-600 font-bold">Actif sur cet appareil</span>}
                                                </p>
                                            </div>
                                        </div>
                                        <div className="shrink-0 ml-2">
                                            {pushStatus === 'subscribed' && <Button variant="secondary" onClick={unsubscribeFromPush} disabled={isSaving} className="text-xs py-1.5 px-3">Désactiver</Button>}
                                            {pushStatus === 'unsubscribed' && <Button variant="successSolid" onClick={subscribeToPush} disabled={isSaving} className="text-xs py-1.5 px-3">Activer</Button>}
                                        </div>
                                    </div>

                                    <div className="flex-1 bg-red-50 border border-red-100 rounded-xl p-3 sm:p-4 flex items-center justify-between min-w-0">
                                        <div className="flex items-center gap-3 min-w-0">
                                            <ShieldAlertIcon size={20} className="text-red-400 shrink-0" />
                                            <div className="min-w-0">
                                                <p className="font-bold text-red-800 text-xs break-words leading-tight">Urgence / Sécurité</p>
                                                <p className="text-[10px] text-red-600 break-words leading-tight mt-0.5">Révoquer tous les appareils liés</p>
                                            </div>
                                        </div>
                                        <Button variant="dangerSolid" onClick={revokeAllPushLinks} disabled={isSaving} className="text-xs py-1.5 px-3 shadow-sm shrink-0 ml-2">Révoquer</Button>
                                    </div>
                                </div>
                            </div>

                            <div className="pt-6 border-t border-slate-100">
                                <h4 className="font-bold text-slate-700 text-sm mb-3">File d'attente globale (E-mails)</h4>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 min-w-0 w-full">
                                    <div className="space-y-4 p-4 bg-slate-50 rounded-xl border border-slate-100 shadow-sm min-w-0">
                                        <h5 className="font-bold text-slate-700 text-xs flex items-center gap-2 break-words"><BellIcon size={14} className="shrink-0"/> Délais de rétention avant envoi</h5>
                                        {FormInput && <FormInput label="Messages Standards (Minutes)" type="number" min="1" max="4320" value={settings.notif_delay_standard || '360'} onChange={e=>updateSetting('notif_delay_standard', e.target.value)} className="min-w-0 w-full" />}
                                        {FormInput && <FormInput label="Messages du Support (Minutes)" type="number" min="1" max="120" value={settings.notif_delay_support || '15'} onChange={e=>updateSetting('notif_delay_support', e.target.value)} className="min-w-0 w-full" />}
                                    </div>
                                    
                                    <div className="space-y-4 p-4 bg-slate-50 rounded-xl border border-slate-100 shadow-sm min-w-0">
                                        <h5 className="font-bold text-slate-700 text-xs flex items-center gap-2 break-words"><ZapIcon size={14} className="shrink-0"/> Quotas par cycle CRON</h5>
                                        {FormInput && <FormInput label="Limite max d'e-mails à traiter" type="number" min="10" max="500" value={settings.cron_mail_limit || '100'} onChange={e=>updateSetting('cron_mail_limit', e.target.value)} className="min-w-0 w-full" />}
                                        {FormInput && <FormInput label="Ratio réservé au Support (%)" type="number" min="0" max="100" value={settings.cron_support_ratio || '25'} onChange={e=>updateSetting('cron_support_ratio', e.target.value)} className="min-w-0 w-full" />}
                                        {FormInput && <FormInput label="Taille de lot (Nettoyage BDD)" type="number" min="10" max="1000" value={settings.cron_batch_size || '100'} onChange={e=>updateSetting('cron_batch_size', e.target.value)} hint="Nombre maximal d'éléments audités par cycle" className="min-w-0 w-full" />}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </DataCard>
                </div>

                {/* CGV / RGPD */}
                <DataCard className="min-w-0">
                    <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words"><ZapIcon size={18} className="text-purple-600 shrink-0"/> Conditions de service (CGV / RGPD)</h3>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 min-w-0 w-full">
                        {FormTextarea && (
                            <>
                                <div className="relative min-w-0">
                                    <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 text-xs shadow-inner min-w-0 w-full" />
                                    <span className="absolute top-0 right-0 text-[9px] font-bold bg-purple-50 text-purple-700 px-2 py-0.5 rounded uppercase tracking-widest pointer-events-none border border-purple-100">Support HTML</span>
                                </div>
                                
                                <div className="relative min-w-0">
                                    <FormTextarea label="Politique de confidentialité (RGPD)" value={settings.rgpd || ''} onChange={e=>updateSetting('rgpd', e.target.value)} rows={15} className="font-mono bg-slate-50 text-xs shadow-inner min-w-0 w-full" />
                                    <span className="absolute top-0 right-0 text-[9px] font-bold bg-purple-50 text-purple-700 px-2 py-0.5 rounded uppercase tracking-widest pointer-events-none border border-purple-100">Support HTML</span>
                                </div>
                            </>
                        )}
                    </div>
                </DataCard>
            </div>

            {/* Barre de sauvegarde */}
            <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 text-sm">
                    {isSaving ? 'Enregistrement...' : 'Sauvegarder les paramètres'}
                </Button>
            </div>

            {/* Modales */}
            {routerActiveDialog === 'confirm' && confirmConfig && ConfirmModal && <ConfirmModal {...confirmConfig} onCancel={routerCloseLayer} />}

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

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