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

window.pano_AdminReglesTab = ({ data, refreshData, openLocalDialog, closeCurrentLayer, activeDialog }) => {
    const { useState } = React;

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

    // 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;

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

    // Composants et Icônes
    const {
        SettingsIcon, EyeIcon, SaveIcon, LoaderIcon, DatabaseIcon, ServerIcon,
        ClockIcon, HardDriveIcon, UploadCloudIcon, Trash2Icon, KeyRoundIcon,
        RefreshCwIcon, ZapIcon, EditIcon, MessageSquareIcon, ShieldAlertIcon
    } = window.pano_getIcons();

    const { FormInput, PasswordPromptModal, TextLogo, Button, DataCard } = window.pano_getComponents();

    const DBIconToUse = DatabaseIcon || ServerIcon || SettingsIcon;
    const ClockIconToUse = ClockIcon || RefreshCwIcon || ZapIcon;
    const HardDriveIconToUse = HardDriveIcon || SaveIcon || UploadCloudIcon;
    const MessageIconToUse = MessageSquareIcon || EditIcon;

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

    const handleSave = async (e) => {
        e.preventDefault();
        const payload = {};
        let isProtectedChanged = false;

        const protectedFields = [
            'limit_rgpd_delete', 'limit_draft_delete', 'limit_keepalive_delete',
            'limit_shipping_force', 'limit_history_max', 'quota_vault_mb',
            'quota_upload_private_mb', 'quota_upload_public_mb', 'limit_pdf_pages',
            'purge_zip_transit_hours', 'purge_zip_doe_hours', 'token_register_hours',
            'token_reset_hours', 'token_invite_days', 'token_support_days', 'support_access_hours',
            'cron_batch_size', 'editor_lock_timeout',
            'limit_strikes_suspend', 'magic_link_expire_days', 'token_recovery_hours',
            'timeline_max_chars', 'timeline_anti_spam_sec', 'timeline_auto_close_days',
            // NOUVEAUX CHAMPS (Spam intelligent et Quota global)
            'timeline_spam_max_msg', 'timeline_spam_window_sec', 'quota_global_mb'
        ];

        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) {
                payload[key] = settings[key];
                if (protectedFields.includes(key)) {
                    isProtectedChanged = true;
                }
            }
        }

        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: "La modification des règles et seuils du système 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, e);
            return;
        }

        await executeSave(payload);
    };

    const executeSave = async (finalPayload) => {
        const d = await safeFetch('settings/update', {
            body: finalPayload,
            setLoading: setIsSaving,
            successMessage: "Règles et options sauvegardées avec succès !"
        });

        if (!isMounted.current) return;

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

    const renderSelectRow = (key, label) => {
        const val = settings[key] || 'active'; 
        return (
            <div key={key} className="flex flex-col p-4 bg-slate-50 border border-slate-100 rounded-xl shadow-sm gap-2 min-w-0 transition hover:border-emerald-300">
                <span className="font-bold text-slate-700 text-sm break-words leading-tight block">{label}</span>
                <select 
                    value={val} 
                    onChange={(e) => updateSetting(key, e.target.value)}
                    className="text-xs font-bold border border-slate-200 rounded-lg p-2.5 outline-none focus:border-emerald-500 bg-white cursor-pointer text-slate-700 min-w-0 w-full shadow-sm"
                >
                    <option value="active">Activée</option>
                    <option value="optional_on">En option (activée par défaut)</option>
                    <option value="optional_off">En option (désactivée par défaut)</option>
                    <option value="disabled">Désactivée</option>
                </select>
            </div>
        );
    };

    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;
        }
    }

    const clientOptionsGlobal = [
        { id: 'opt_collab', label: 'Travail en collaboration' },
        { id: 'opt_messaging', label: 'Messagerie des riverains' },
        { id: 'opt_newsletter', label: 'Info riverains' }
    ];

    const clientOptionsChamps = [
        { id: 'simp_opt_description', label: 'Description des travaux' },
        { id: 'simp_opt_image', label: 'Vue du projet (Image)' },
        { id: 'simp_opt_theme', label: 'Couleur du thème' },
        { id: 'simp_opt_link', label: 'Lien vers le promoteur' },
        { id: 'simp_opt_emergency', label: 'Téléphone d\'urgence' },
        { id: 'simp_opt_schedule', label: 'Horaires de nuisances' }
    ];

    const clientOptionsOnglets = [
        { id: 'simp_opt_hide_intervenants', label: 'Masquer l\'onglet Intervenants' },
        { id: 'simp_opt_hide_lots', label: 'Masquer l\'onglet Lots de travaux' },
        { id: 'simp_opt_hide_legal', label: 'Masquer l\'affichage public de l\'Arrêté' }
    ];

    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">Règles et Options</h1>
                        <p className="text-slate-500 font-medium flex items-center flex-wrap gap-1">Personnalisation des règles métier de <TextLogo className="text-sm" />.</p>
                    </div>
                </div>

                {/* TITRE DE SECTION: OPTIONS CLIENTS */}
                <div className="pt-2 pb-2 border-b border-slate-200 min-w-0 w-full">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 break-words">
                        <SettingsIcon size={22} className="text-slate-600 shrink-0"/> 
                        Options côté clients
                    </h2>
                    <p className="text-sm text-slate-500 mt-1 break-words">Gérez la disponibilité globale des fonctionnalités pour l'ensemble des clients. L'état "En option" leur permet d'activer ou masquer eux-mêmes ces champs par projet.</p>
                </div>

                {/* GRILLE ÉCLATÉE DES SOUS-CARTES OPTIONS CLIENTS */}
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 min-w-0 w-full items-start">
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <SettingsIcon size={18} className="text-slate-600 shrink-0"/> Fonctionnalités globales
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {clientOptionsGlobal.map(opt => renderSelectRow(opt.id, opt.label))}
                        </div>
                    </DataCard>

                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <EditIcon size={18} className="text-emerald-600 shrink-0"/> Champs de l'éditeur
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {clientOptionsChamps.map(opt => renderSelectRow(opt.id, opt.label))}
                        </div>
                    </DataCard>

                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <EyeIcon size={18} className="text-amber-500 shrink-0"/> Masquage d'onglets
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {clientOptionsOnglets.map(opt => renderSelectRow(opt.id, opt.label))}
                        </div>
                    </DataCard>
                </div>

                {/* TITRE DE SECTION: SEUILS SYSTÈME */}
                <div className="pt-6 pb-2 border-b border-slate-200 mt-8 min-w-0 w-full">
                    <h2 className="text-xl font-black text-slate-800 flex items-center gap-2 break-words">
                        <DBIconToUse size={22} className="text-red-600 shrink-0"/> 
                        Règles métier et seuils du système
                    </h2>
                    <p className="text-sm text-slate-500 mt-1 break-words">Configuration des limites techniques, des purges automatiques et des expirations de l'application.</p>
                </div>

                {/* GRILLE ÉCLATÉE DES SOUS-CARTES SEUILS */}
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 min-w-0 w-full items-start">
                    
                    {/* MESSAGERIE ET TIMELINE */}
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <MessageIconToUse size={18} className="text-indigo-500 shrink-0"/> Messagerie et Timeline
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {FormInput && <FormInput label="Longueur max. d'un message" type="number" min="10" value={settings.timeline_max_chars || '1000'} onChange={e=>updateSetting('timeline_max_chars', e.target.value)} className="min-w-0 w-full" hint="En caractères" />}
                            {FormInput && <FormInput label="Clôture auto. inactivité (Jours)" type="number" min="1" value={settings.timeline_auto_close_days || '60'} onChange={e=>updateSetting('timeline_auto_close_days', e.target.value)} className="min-w-0 w-full" hint="Clôture la discussion au bout de ce délai" />}
                            
                            <div className="pt-2 border-t border-slate-100">
                                <h5 className="font-bold text-slate-700 text-xs flex items-center gap-2 mb-3 break-words">
                                    {ShieldAlertIcon && <ShieldAlertIcon size={14} className="text-red-500 shrink-0"/>} Anti-Flood Riverain
                                </h5>
                                <div className="space-y-4">
                                    {FormInput && <FormInput label="Seuil de déclenchement (Nb. msg)" type="number" min="1" value={settings.timeline_spam_max_msg || '5'} onChange={e=>updateSetting('timeline_spam_max_msg', e.target.value)} className="min-w-0 w-full" hint="S'active après ce nombre de messages..." />}
                                    {FormInput && <FormInput label="Fenêtre de tir (Sec.)" type="number" min="1" value={settings.timeline_spam_window_sec || '60'} onChange={e=>updateSetting('timeline_spam_window_sec', e.target.value)} className="min-w-0 w-full" hint="... envoyés en moins de (secondes)." />}
                                    {FormInput && <FormInput label="Durée du blocage (Sec.)" type="number" min="0" value={settings.timeline_anti_spam_sec || '30'} onChange={e=>updateSetting('timeline_anti_spam_sec', e.target.value)} className="min-w-0 w-full" hint="Remis à 0 si le client ou support répond." />}
                                </div>
                            </div>
                        </div>
                    </DataCard>

                    {/* DÉLAIS D'INACTIVITÉ */}
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <ClockIconToUse size={18} className="text-red-500 shrink-0"/> Délais d'inactivité
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {FormInput && <FormInput label="Purge RGPD complète (Jours)" type="number" min="30" value={settings.limit_rgpd_delete || '1095'} onChange={e=>updateSetting('limit_rgpd_delete', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Purge brouillon inactif (Jours)" type="number" min="10" value={settings.limit_draft_delete || '100'} onChange={e=>updateSetting('limit_draft_delete', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Expiration Achat Unique (Jours)" type="number" min="365" value={settings.limit_keepalive_delete || '455'} onChange={e=>updateSetting('limit_keepalive_delete', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Expiration verrou édition (Min.)" type="number" min="1" value={settings.editor_lock_timeout || '15'} onChange={e=>updateSetting('editor_lock_timeout', e.target.value)} className="min-w-0 w-full" />}
                        </div>
                    </DataCard>

                    {/* EXPIRATION DES JETONS ET ACCÈS (Désormais sur 2 colonnes) */}
                    <DataCard className="min-w-0 w-full md:col-span-2 xl:col-span-1">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <KeyRoundIcon size={18} className="text-amber-500 shrink-0"/> Expiration des jetons
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 min-w-0 w-full">
                            {FormInput && <FormInput label="Récupération (Heures)" type="number" min="1" value={settings.token_recovery_hours || '2'} onChange={e=>updateSetting('token_recovery_hours', e.target.value)} className="min-w-0 w-full" hint="Lien de survie" />}
                            {FormInput && <FormInput label="Lien messagerie (Jours)" type="number" min="1" value={settings.magic_link_expire_days || '365'} onChange={e=>updateSetting('magic_link_expire_days', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Inscription (Heures)" type="number" min="1" value={settings.token_register_hours || '24'} onChange={e=>updateSetting('token_register_hours', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Mot de passe oublié (H)" type="number" min="1" value={settings.token_reset_hours || '1'} onChange={e=>updateSetting('token_reset_hours', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Invitation équipe (Jours)" type="number" min="1" value={settings.token_invite_days || '30'} onChange={e=>updateSetting('token_invite_days', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Demande support (Jours)" type="number" min="1" value={settings.token_support_days || '7'} onChange={e=>updateSetting('token_support_days', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Accès autorisé (Heures)" type="number" min="1" value={settings.support_access_hours || '24'} onChange={e=>updateSetting('support_access_hours', e.target.value)} className="min-w-0 w-full sm:col-span-2" hint="Temps accordé à l'Admin" />}
                        </div>
                    </DataCard>
                    
                    {/* LIMITES ET LOGISTIQUE */}
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <EyeIcon size={18} className="text-amber-500 shrink-0"/> Limites et Logistique
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {FormInput && <FormInput label="Avertissements avant suspension" type="number" min="1" value={settings.limit_strikes_suspend || '5'} onChange={e=>updateSetting('limit_strikes_suspend', e.target.value)} className="min-w-0 w-full" hint="Signalements riverains modérés" />}
                            {FormInput && <FormInput label="Forçage livraison expédiée (Jours)" type="number" min="7" value={settings.limit_shipping_force || '90'} onChange={e=>updateSetting('limit_shipping_force', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Max. cartes Historique Logistique" type="number" min="10" value={settings.limit_history_max || '500'} onChange={e=>updateSetting('limit_history_max', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Max. pages PDF extraites (Aperçus)" type="number" min="1" value={settings.limit_pdf_pages || '20'} onChange={e=>updateSetting('limit_pdf_pages', e.target.value)} className="min-w-0 w-full" />}
                        </div>
                    </DataCard>

                    {/* QUOTAS ET FICHIERS */}
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                            <HardDriveIconToUse size={18} className="text-blue-500 shrink-0"/> Quotas et Fichiers
                        </h3>
                        <div className="space-y-4 min-w-0 w-full">
                            {FormInput && <FormInput label="Quota global par compte (Mo)" type="number" min="50" value={settings.quota_global_mb || '5000'} onChange={e=>updateSetting('quota_global_mb', e.target.value)} className="min-w-0 w-full" hint="Espace de stockage total par client" />}
                            {FormInput && <FormInput label="Quota Coffre-fort par panneau (Mo)" type="number" min="10" value={settings.quota_vault_mb || '250'} onChange={e=>updateSetting('quota_vault_mb', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Max upload fichiers Privés (Mo)" type="number" min="1" value={settings.quota_upload_private_mb || '10'} onChange={e=>updateSetting('quota_upload_private_mb', e.target.value)} className="min-w-0 w-full" />}
                            {FormInput && <FormInput label="Max upload fichiers Publics (Mo)" type="number" min="1" value={settings.quota_upload_public_mb || '5'} onChange={e=>updateSetting('quota_upload_public_mb', e.target.value)} className="min-w-0 w-full" />}
                        </div>
                    </DataCard>

                    {/* PURGE TEMPORAIRE ET CRON */}
                    <div className="space-y-6 min-w-0 w-full">
                        <DataCard className="min-w-0 w-full">
                            <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                                <Trash2Icon size={18} className="text-slate-500 shrink-0"/> Purge auto (Heures)
                            </h3>
                            <div className="space-y-4 min-w-0 w-full">
                                {FormInput && <FormInput label="Archives en transit (ZIP)" type="number" min="1" value={settings.purge_zip_transit_hours || '24'} onChange={e=>updateSetting('purge_zip_transit_hours', e.target.value)} className="min-w-0 w-full" />}
                                {FormInput && <FormInput label="Archives légales (D.O.E)" type="number" min="1" value={settings.purge_zip_doe_hours || '72'} onChange={e=>updateSetting('purge_zip_doe_hours', e.target.value)} className="min-w-0 w-full" />}
                            </div>
                        </DataCard>
                        
                        <DataCard className="min-w-0 w-full">
                            <h3 className="font-black text-slate-800 mb-4 flex items-center gap-2 break-words">
                                <ZapIcon size={18} className="text-purple-500 shrink-0"/> Moteur asynchrone (CRON)
                            </h3>
                            <div className="space-y-4 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>
                        </DataCard>
                    </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-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 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_regles.jsx] */