// ECO-PANNEAU.FR - _react/_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
    } = window.pano_getIcons();

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

    // Fallback pour les icônes si manquantes
    const DBIconToUse = DatabaseIcon || ServerIcon || SettingsIcon;
    const ClockIconToUse = ClockIcon || RefreshCwIcon || ZapIcon;
    const HardDriveIconToUse = HardDriveIcon || SaveIcon || UploadCloudIcon;

    // Méthodes métier
    const updateSetting = (key, val) => setSettings({ ...settings, [key]: val });

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

        // Champs nécessitant une protection par mot de passe dans cet onglet
        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'
        ];

        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: "Confirmation de sécurité",
                desc: "La modification des seuils du système nécessite le mot de passe administrateur :",
                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;
    };

    // Helper pour le rendu des menus déroulants à 4 choix stricts
    const renderSelectRow = (key, label) => {
        const val = settings[key] || 'active'; // Par défaut
        return (
            <div key={key} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-slate-50 border border-slate-100 rounded-xl shadow-sm gap-3 min-w-0 transition hover:border-emerald-300">
                <span className="font-bold text-slate-700 text-sm break-words leading-tight flex-1">{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 sm:w-auto shrink-0 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>
        );
    };

    // Calcul de "hasChanges" pour afficher/griser le bouton "Sauvegarder"
    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;
        }
    }

    // Configuration des rendus répétitifs
    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é' }
    ];

    // Rendu UI
    return (
        <>
            <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 relative pb-24 min-w-0 w-full overflow-x-hidden">
                <div className="flex justify-between items-center mb-2 min-w-0">
                    <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>

                <div className="grid grid-cols-1 xl:grid-cols-2 gap-6 min-w-0 w-full items-start">
                    
                    {/* Options clients Unifiées */}
                    <DataCard className="min-w-0 w-full">
                        <h3 className="font-black text-slate-800 mb-2 flex items-center gap-2 break-words">
                            <SettingsIcon size={18} className="text-slate-600 shrink-0"/> Options côté clients
                        </h3>
                        <p className="text-sm text-slate-500 leading-relaxed mb-4 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 className="space-y-6 min-w-0 w-full">
                            <div className="space-y-3">
                                <h4 className="font-bold text-slate-700 text-xs uppercase tracking-widest border-b border-slate-100 pb-2">Fonctionnalités globales</h4>
                                {clientOptionsGlobal.map(opt => renderSelectRow(opt.id, opt.label))}
                            </div>

                            <div className="space-y-3">
                                <h4 className="font-bold text-slate-700 text-xs uppercase tracking-widest border-b border-slate-100 pb-2 flex items-center gap-2">
                                    <EditIcon size={14} className="shrink-0"/> Champs de l'éditeur
                                </h4>
                                {clientOptionsChamps.map(opt => renderSelectRow(opt.id, opt.label))}
                            </div>

                            <div className="space-y-3">
                                <h4 className="font-bold text-slate-700 text-xs uppercase tracking-widest border-b border-slate-100 pb-2 flex items-center gap-2">
                                    <EyeIcon size={14} className="shrink-0"/> Masquage d'onglets
                                </h4>
                                {clientOptionsOnglets.map(opt => renderSelectRow(opt.id, opt.label))}
                            </div>
                        </div>
                    </DataCard>

                    {/* Règles métier et seuils */}
                    <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">
                            <DBIconToUse size={18} className="text-red-600 shrink-0"/> Règles métier et seuils du système
                        </h3>
                        
                        <div className="space-y-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"><ClockIconToUse size={14} className="shrink-0 text-red-500"/> Délais d'inactivité (Jours)</h5>
                                {FormInput && <FormInput label="Purge RGPD complète" 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" 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" 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" />}
                            </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"><EyeIcon size={14} className="shrink-0 text-amber-500"/> Limites d'interface et Logistique</h5>
                                {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>

                            <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"><HardDriveIconToUse size={14} className="shrink-0 text-blue-500"/> Quotas et Fichiers (Mo)</h5>
                                {FormInput && <FormInput label="Quota Coffre-fort par panneau" 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" 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" 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>
                            
                            <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"><Trash2Icon size={14} className="shrink-0 text-slate-500"/> Purge des fichiers temporaires (Heures)</h5>
                                {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>
                            
                            <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"><KeyRoundIcon size={14} className="shrink-0 text-amber-500"/> Expiration des jetons et accès</h5>
                                {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é (Heures)" 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é support (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" />}
                            </div>
                        </div>
                    </DataCard>
                </div>
            </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 transition-opacity ${!hasChanges ? 'opacity-50 pointer-events-none' : 'opacity-100'}`}>
                <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>

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

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