/**
 * Maintenance GENIUS - Admin JS
 * Version 2.9.124
 * 
 * Utilise mgAdmin passé via wp_localize_script:
 * - mgAdmin.ajaxurl
 * - mgAdmin.nonce
 * - mgAdmin.preview_url
 * - mgAdmin.version
 */

jQuery(document).ready(function($) {
    'use strict';


    function mgShowTab($btn) {
        if (!$btn || !$btn.length) { return; }
        $('.mg-accordion.is-open').removeClass('is-open').children('.mg-accordion-body').hide();
        var $bgU = $('#mg-bg-unified');
        if ($bgU.hasClass('is-open')) {
            $bgU.removeClass('is-open');
            $('#mg-bg-host').hide();
            $bgU.find('.mg-bg-toggle').attr('aria-expanded', 'false');
        }
        var tabName = $btn.attr('data-tab');
        var panels = $btn.attr('data-panels');
        $('.mg-tab').removeClass('active');
        $btn.addClass('active');
        $('.mg-tab-content').removeClass('active').hide();
        if (panels) {
            panels.split(/[\s,]+/).forEach(function(id) {
                if (id) { $('#' + id).addClass('active').show(); }
            });
        } else {
            $('#tab-' + tabName).addClass('active').show();
        }
    }
    window.mgShowTab = mgShowTab;

    function mgApplyUiMode(mode) {
        if (mode !== 'expert') { mode = 'simple'; }
        $('.mg-wrapper').removeClass('mg-mode-simple mg-mode-expert').addClass('mg-mode-' + mode);
        $('.mg-mode-seg').removeClass('is-active').filter('[data-mode="' + mode + '"]').addClass('is-active');
        if (mode === 'simple' && $('.mg-tab.active').first().attr('data-mg-level') === 'advanced') {
            mgShowTab($('.mg-tab[data-tab="general"]'));
            localStorage.setItem('mg_active_tab', 'general');
        }
    }
    window.mgApplyUiMode = mgApplyUiMode;
    $(document).on('click', '.mg-mode-seg, .mg-mode-hint-link', function() {
        var m = $(this).attr('data-mode');
        if (!m) { return; }
        localStorage.setItem('mg_ui_mode', m);
        mgApplyUiMode(m);
    });

    $(document).on('click', '.mg-tab', function(e) {
        e.preventDefault();
        e.stopPropagation();
        mgShowTab($(this));
        localStorage.setItem('mg_active_tab', $(this).attr('data-tab'));
    });

    setTimeout(function() {
        // Restaurer l'onglet sauvegardé (ex: après reload depuis modale remote)
        var savedTab = localStorage.getItem('mg_active_tab');
        var $btn = savedTab ? $('.mg-tab[data-tab="' + savedTab + '"]') : $();
        if (!$btn.length) { $btn = $('.mg-tab.active').first(); }
        if (!$btn.length) { $btn = $('.mg-tab').first(); }
        mgShowTab($btn);
        mgApplyUiMode(localStorage.getItem('mg_ui_mode') || 'simple');
    }, 100);

    if (typeof $.fn.wpColorPicker !== 'undefined') {
        $('.mg-color-picker').wpColorPicker();
    }

    $('.mg-opacity-slider').on('input', function() {
        var targetId = $(this).data('target');
        var value = $(this).val();
        var suffix = targetId.includes('width') || targetId.includes('padding') || targetId.includes('radius') ? 'px' : '%';
        $('#' + targetId).text(value + suffix);
    });

    $('#mg-title-size, #mg-message-size').on('input', function() {
        $(this).siblings('.mg-range-value').text($(this).val() + 'px');
    });

    $('#mg-logo-size').on('input', function() {
        $(this).siblings('.mg-range-value').text($(this).val() + 'px');
    });

    $('#mg-reset-font-sizes').on('click', function() {
        $('#mg-title-size').val(42).siblings('.mg-range-value').text('42px');
        $('#mg-message-size').val(18).siblings('.mg-range-value').text('18px');
        showNotice(mgAdmin.i18n.h1h2_reset, 'success');
    });

    $('#mg-notification-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-notification-options').slideDown();
        } else {
            $('#mg-notification-options').slideUp();
        }
    });

    $('#mg-turnstile-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-turnstile-options').slideDown();
        } else {
            $('#mg-turnstile-options').slideUp();
        }
    });

    $('#mg-countdown-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-countdown-options').slideDown();
        } else {
            $('#mg-countdown-options').slideUp();
        }
    });

    $('#mg-countdown-time').on('focus', function() {
        if (!$(this).val() || $(this).val() === '00:00') {
            const now = new Date();
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            $(this).val(hours + ':' + minutes);
        }
    });

    $('#mg-countdown-date').on('focus', function() {
        if (!$(this).val()) {
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            const year = tomorrow.getFullYear();
            const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
            const day = String(tomorrow.getDate()).padStart(2, '0');
            $(this).val(year + '-' + month + '-' + day);
        }
    });

    $('#mg-export-emails').on('click', function() {
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_export_notification_emails',
                nonce: mgAdmin.nonce
            },
            success: function(response) {
                if (response.success && response.data.csv) {
                    var blob = new Blob([response.data.csv], { type: 'text/csv;charset=utf-8;' });
                    var link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = 'maintenance-genius-emails-' + new Date().toISOString().split('T')[0] + '.csv';
                    link.click();
                    showNotice(mgAdmin.i18n.csv_exported, 'success');
                } else {
                    showNotice(mgAdmin.i18n.no_email_export, 'warning');
                }
            }
        });
    });

    $('#mg-clear-emails').on('click', function() {
        if (confirm(mgAdmin.i18n.confirm_delete_emails)) {
            $.ajax({
                url: mgAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mg_clear_notification_emails',
                    nonce: mgAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $('#mg-email-count').text('0');
                        $('#mg-export-emails, #mg-clear-emails').hide();
                        showNotice(mgAdmin.i18n.emails_deleted, 'success');
                    }
                }
            });
        }
    });

    $('#mg-check-update').on('click', function() {
        var $btn = $(this);
        var $result = $('#mg-update-result');
        
        $btn.prop('disabled', true).text(mgAdmin.i18n.checking);
        $result.html('<span style="color:#666;">'+mgAdmin.i18n.checking_in_progress+'</span>');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_check_update',
                nonce: mgAdmin.nonce
            },
            success: function(response) {
                $btn.prop('disabled', false).text(mgAdmin.i18n.check_updates);
                if (response.success) {
                    if (response.data.current_version) {
                        $('#mg-current-version-display').text(response.data.current_version);
                    }
                    if (response.data.update_available) {
                        $result.html(
                            '<div style="background:#fff3cd;padding:12px;border-radius:8px;border-left:4px solid #ffc107;">' +
                            '<strong>🆕 '+mgAdmin.i18n.new_version_available+'</strong><br>' +
                            'Version ' + response.data.latest_version + ' '+mgAdmin.i18n.is_available+'<br>' +
                            '<a href="' + response.data.download_url + '" target="_blank" class="mg-btn mg-btn-primary mg-btn-sm" style="margin-top:10px;">'+mgAdmin.i18n.download+'</a>' +
                            '</div>'
                        );
                    } else {
                        $result.html(
                            '<div style="background:#d4edda;padding:12px;border-radius:8px;border-left:4px solid #28a745;">' +
                            '<strong>✅ '+mgAdmin.i18n.up_to_date+'</strong><br>' +
                            'Version ' + response.data.current_version + ' '+mgAdmin.i18n.is_latest_version +
                            '</div>'
                        );
                    }
                } else {
                    var errorMsg = (response.data && response.data.message) ? response.data.message : mgAdmin.i18n.check_error;
                    $result.html(
                        '<div style="background:#fff3cd;padding:12px;border-radius:8px;border-left:4px solid #ffc107;">' +
                        '<strong>⚠️ ' + errorMsg + '</strong>' +
                        '</div>'
                    );
                }
            },
            error: function() {
                $btn.prop('disabled', false).text(mgAdmin.i18n.check_updates);
                $result.html('<span style="color:#dc3545;">'+mgAdmin.i18n.connection_error+'</span>');
            }
        });
    });

    $('#mg-toggle').on('change', function() {
        var enabled = $(this).is(':checked');
        var $badge = $('#mg-status-badge');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_toggle',
                nonce: mgAdmin.nonce,
                enabled: enabled
            },
            beforeSend: function() {
                $badge.text('...');
            },
            success: function(response) {
                if (response.success) {
                    var isCS = $('input[name="page_mode"]:checked').val() === 'coming_soon';
                    var badgeText = enabled ? (isCS ? mgAdmin.i18n.coming_soon_label || 'COMING SOON' : 'ON') : 'OFF';
                    $badge.text(badgeText)
                          .removeClass('active inactive coming-soon')
                          .addClass(enabled ? 'active' : 'inactive');
                    if (enabled && isCS) { $badge.addClass('coming-soon'); }
                    $('#mg-mode-label').text(isCS ? (mgAdmin.i18n.coming_soon_mode || 'COMING SOON MODE') : (mgAdmin.i18n.maintenance_mode || 'MAINTENANCE MODE'));
                    showNotice(response.data.message, 'success');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            }
        });
    });

    $('#mg-visitor-access').on('change', function() {
        var $section = $('#mg-visitor-password-section');
        if ($(this).is(':checked')) {
            $section.slideDown(300);
        } else {
            $section.slideUp(300);
        }
    });

    $('#mg-sidebar-enabled').on('change', function() {
        var $options = $('#mg-sidebar-options');
        if ($(this).is(':checked')) {
            $options.slideDown(300);
        } else {
            $options.slideUp(300);
        }
    });

    $('#mg-custom-bg-enabled').on('change', function() {
        var $options = $('#mg-custom-bg-options');
        if ($(this).is(':checked')) {
            $options.slideDown(300);
        } else {
            $options.slideUp(300);
        }
    });

    $('#mg-upload-custom-bg').on('click', function(e) {
        e.preventDefault();
        
        var frame = wp.media({
            title: mgAdmin.i18n.choose_bg_image,
            button: { text: mgAdmin.i18n.use_this_image },
            multiple: false,
            library: { type: 'image' }
        });
        
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            $('#mg-custom-bg-url').val(attachment.url);
            $('#mg-custom-bg-preview').html('<img src="' + attachment.url + '" alt="Background">');
            $('#mg-remove-custom-bg').show();
        });
        
        frame.open();
    });

    $('#mg-remove-custom-bg').on('click', function() {
        $('#mg-custom-bg-url').val('');
        $('#mg-custom-bg-preview').html('<span class="mg-upload-placeholder">'+mgAdmin.i18n.no_image_selected+'</span>');
        $(this).hide();
    });

    try {
        var $passwordInput = $('#mg-visitor-password');

        $(document).on('click', '.mg-toggle-password', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $input = $('#mg-visitor-password');
            var isPassword = $input.attr('type') === 'password';
            $input.attr('type', isPassword ? 'text' : 'password');
            $(this).toggleClass('active', isPassword);
            $input.focus();
        });
        
        $(document).on('click', '.mg-generate-password', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#$%&*?';
            var password = '';
            for (var i = 0; i < 12; i++) {
                password += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            var $input = $('#mg-visitor-password');
            $input.val(password).attr('type', 'text');
            $('.mg-toggle-password').addClass('active');
            $('.mg-copy-password').prop('disabled', false);
            $input.focus().select();
            showNotice(mgAdmin.i18n.password_generated || 'Password generated!', 'success');
        });

        $(document).on('click', '.mg-copy-password', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var password = $('#mg-visitor-password').val();
            if (!password) return;
            var $btn = $(this);
            
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(password).then(function() {
                    $btn.addClass('copied');
                    showNotice(mgAdmin.i18n.password_copied || 'Password copied!', 'success');
                    setTimeout(function() { $btn.removeClass('copied'); }, 2000);
                });
            } else {
                var $input = $('#mg-visitor-password');
                var originalType = $input.attr('type');
                $input.attr('type', 'text').select();
                document.execCommand('copy');
                $input.attr('type', originalType);
                showNotice(mgAdmin.i18n.password_copied || 'Password copied!', 'success');
            }
        });
        
        $(document).on('input', '#mg-visitor-password', function() {
            $('.mg-copy-password').prop('disabled', !$(this).val());
        });

    } catch(err) {
    }

    $('#mg-bg-image-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-bg-image-group').slideDown(300);
        } else {
            $('#mg-bg-image-group').slideUp(300);
        }
    });

    $('#mg-container-shadow').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-container-shadow-group').slideDown(300);
        } else {
            $('#mg-container-shadow-group').slideUp(300);
        }
    });

    $('#mg-animation-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-animation-controls').slideDown(300);
        } else {
            $('#mg-animation-controls').slideUp(300);
        }
    });

    $(document).on('click', '#mg-revoke-visitor-access', function(e) {
        e.preventDefault();

        if (!confirm(mgAdmin.i18n.confirm_disconnect_all)) {
            return;
        }

        var $btn = $(this);
        var originalText = $btn.html();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_clear_visitor_cache',
                nonce: mgAdmin.nonce
            },
            beforeSend: function() {
                $btn.prop('disabled', true).html(mgAdmin.i18n.resetting || 'Revoking...');
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                } else {
                    showNotice(mgAdmin.i18n.error_prefix + ' ' + (response.data ? response.data.message : mgAdmin.i18n.unknown), 'error');
                }
            },
            error: function(xhr, status, error) {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });

    $(document).on('click', '#mg-save-visitor-access', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var originalText = $btn.html();

        var vaEnabled = $('#mg-visitor-access').is(':checked');
        var vaPwd = $('#mg-visitor-password').val();
        var vaClear = $('#mg-clear-visitor-password').is(':checked');
        var vaHasExisting = $('.mg-password-status .mg-status-ok').length > 0 && !vaClear;
        if (vaEnabled && !vaPwd && !vaHasExisting) {
            showNotice(mgAdmin.i18n.visitor_password_required || "Un mot de passe est requis pour activer l'accès visiteur.", 'error');
            return;
        }

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: mgCollectData({
                visitor_password: $('#mg-visitor-password').val(),
                clear_password: vaClear
            }),
            beforeSend: function() {
                $btn.prop('disabled', true).html(mgAdmin.i18n.saving || 'Saving...');
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                } else {
                    showNotice(mgAdmin.i18n.error_prefix + ' ' + (response.data ? response.data.message : mgAdmin.i18n.unknown), 'error');
                }
            },
            error: function(xhr, status, error) {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Endpoint dédié mg_save_ai_key (hors mg_save)
    function mgSaveAiKey(clearKey) {
        var $btn = clearKey ? $('#mg-clear-ai-key') : $('#mg-save-ai-key');
        var originalText = $btn.html();
        var $feedback = $('#mg-ai-key-feedback');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_save_ai_key',
                nonce: mgAdmin.nonce,
                api_key: clearKey ? '' : $('#mg-ai-api-key').val(),
                clear_key: clearKey ? 1 : 0
            },
            beforeSend: function() {
                $btn.prop('disabled', true).html(mgAdmin.i18n.saving || 'Saving...');
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    $feedback.text(response.data.message);
                    // Write-only : on vide le champ, on met à jour le placeholder
                    $('#mg-ai-api-key').val('');
                    if (response.data.status === 'option') {
                        $('#mg-ai-api-key').attr('placeholder', '••••••••••••' + response.data.last4);
                    } else {
                        $('#mg-ai-api-key').attr('placeholder', 'sk-ant-...');
                    }
                } else {
                    showNotice(response.data ? response.data.message : mgAdmin.i18n.unknown, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).html(originalText);
            }
        });
    }

    $(document).on('click', '#mg-save-ai-key', function(e) {
        e.preventDefault();
        mgSaveAiKey(false);
    });

    $(document).on('click', '#mg-clear-ai-key', function(e) {
        e.preventDefault();
        mgSaveAiKey(true);
    });

    // Compat CSP stricte : plus aucun handler inline dans le template.
    // Overlays PRO (×19 — un seul handler au lieu de 19 copies)
    $(document).on('click', '.mg-pro-locked-overlay', function(e) {
        e.preventDefault();
        var $tab = $('[data-tab=pro]');
        if ($tab.length) { $tab.trigger('click'); }
    });
    // Ouverture du chat IA
    $(document).on('click', '[data-mg-open-chat]', function(e) {
        e.preventDefault();
        $('#mg-chat-modal').css('display', 'flex');
        $('#mg-chat-input').trigger('focus');
    });
    // Wizard (fonctions globales existantes conservées telles quelles)
    $(document).on('click', '[data-mg-wizard-next]', function() {
        if (window.mgWizardNext) { window.mgWizardNext(parseInt($(this).attr('data-mg-wizard-next'), 10)); }
    });
    $(document).on('click', '[data-mg-wizard-finish]', function() {
        if (window.mgWizardFinish) { window.mgWizardFinish($(this).attr('data-mg-wizard-finish') === 'true'); }
    });
    $(document).on('click', '[data-mg-wizard-complete]', function() {
        if (window.mgWizardComplete) { window.mgWizardComplete(); }
    });
    $(document).on('click', '[data-mg-wizard-license]', function() {
        if (window.mgWizardActivateLicense) { window.mgWizardActivateLicense(); }
    });
    $(document).on('click', '[data-mg-wizard-preset]', function() {
        if (window.mgWizardSelectPreset) { window.mgWizardSelectPreset(this, $(this).attr('data-mg-wizard-preset')); }
    });

    $('#mg-reset-design').on('click', function(e) {
        e.preventDefault();

        if (!confirm(mgAdmin.i18n.confirm_reset_design)) {
            return;
        }

        var $btn = $(this);
        var originalText = $btn.text();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_reset_design',
                nonce: mgAdmin.nonce
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.resetting);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    setTimeout(function() { location.reload(); }, 1000);
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#mg-settings-form').on('submit', function(e) {
        e.preventDefault();

        var $btn = $(this).find('.mg-btn-primary');
        var originalText = $btn.text();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: mgCollectData({
                visitor_password: $('#mg-visitor-password').val()
            }),
            beforeSend: function() {
                // (isFab n'existe pas dans ce scope → ReferenceError). Bouton texte normal.
                $btn.prop('disabled', true).text(mgAdmin.i18n.saving);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    var sectionButtons = [
        { id: '#mg-save-background', msg: mgAdmin.i18n.background_saved },
        { id: '#mg-save-text-colors', msg: mgAdmin.i18n.text_colors_saved },
        { id: '#mg-save-button-colors', msg: mgAdmin.i18n.button_colors_saved },
        { id: '#mg-save-container', msg: mgAdmin.i18n.container_saved },
        { id: '#mg-save-typography', msg: mgAdmin.i18n.typography_saved },
        { id: '#mg-save-dimensions', msg: mgAdmin.i18n.dimensions_saved },
        { id: '#mg-save-animations', msg: mgAdmin.i18n.animations_saved },
        { id: '#mg-save-design', msg: mgAdmin.i18n.design_saved }
    ];

    sectionButtons.forEach(function(btn) {
        $(btn.id).on('click', function(e) {
            e.preventDefault();
            saveAllSettings($(this), btn.msg);
        });
    });

    function saveAllSettings($btn, successMsg) {
        // $btn.text() sur le FAB détruisait son SVG interne et le remplaçait par du
        // texte nu (« Enregistrer »), puis par du vide en v2.9.111. Le FAB ne doit
        // JAMAIS subir de swap de texte — ses états sont 100 % CSS (classes + ::before).
        var isFab = $btn.hasClass('mg-float-btn');
        var originalText = $btn.text();

        // (incluant le champ FANTÔME #mg-container-border-radius qui n'existe pas
        // dans le template) est remplacé par mgCollectData().
        var data = mgCollectData({
            visitor_password: $('#mg-visitor-password').val()
        });

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: data,
            beforeSend: function() {
                $btn.prop('disabled', true);
                if (!isFab) { $btn.text(mgAdmin.i18n.saving); }
            },
            success: function(response) {
                if (response.success) {
                    showNotice(successMsg, 'success');
                } else {
                    showNotice(mgAdmin.i18n.error_prefix + ' ' + response.data.message, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false);
                if (!isFab) { $btn.text(originalText); }
            }
        });
    }

    var mgAutoSaveTimer = null;
    var mgLastAutoSaveToast = 0;
    var mgAutoSaveDelay = 1500; // 1.5s debounce
    var mgAutoSavePending = false;

    // Champs ignorés par l'auto-save (sécurité ou logique propre)
    var mgAutoSaveExcluded = [
        'mg-visitor-password',           // Mot de passe = action explicite
        'mg-toggle',                     // Toggle maintenance = handler propre
        'mg-license-key',                // Licence = action explicite
        'mg-mailbaby-pass',              // SMTP password
        'mg-anthropic-api-key'           // API key
    ];

    function mgIsExcluded($el) {
        var id = $el.attr('id') || '';
        return mgAutoSaveExcluded.indexOf(id) !== -1 ||
               $el.closest('[data-mg-no-autosave]').length > 0;
    }

    function mgSetSaveButtonState(state) {
        // FAB (#mg-float-save) : on ne modifie PAS le texte interne (icône SVG + label séparé),
        //   on change uniquement les classes CSS pour l'apparence.
        // Boutons texte (.mg-section-save, etc.) : on swap le texte normalement.
        $('.mg-section-save, #mg-save-design, #mg-save-animations').each(function() {
            var $btn = $(this);
            if (!$btn.data('mg-original-text')) {
                $btn.data('mg-original-text', $btn.text());
            }
            var orig = $btn.data('mg-original-text');
            $btn.removeClass('is-pending is-saving is-saved is-error');
            switch (state) {
                case 'pending':
                    $btn.addClass('is-pending').text('● ' + (mgAdmin.i18n.unsaved || 'Unsaved'));
                    break;
                case 'saving':
                    $btn.addClass('is-saving').text('⏳ ' + (mgAdmin.i18n.saving || 'Saving...'));
                    break;
                case 'saved':
                    $btn.addClass('is-saved').text('✓ ' + (mgAdmin.i18n.saved || 'Saved'));
                    setTimeout(function() {
                        $btn.removeClass('is-saved').text(orig);
                    }, 2000);
                    break;
                case 'error':
                    $btn.addClass('is-error').text('⚠ ' + (mgAdmin.i18n.retry || 'Retry'));
                    break;
                default:
                    $btn.text(orig);
            }
        });

        // FAB Save : seulement les classes CSS (pas de texte écrit dessus)
        var $fab = $('#mg-float-save');
        if ($fab.length) {
            $fab.removeClass('is-pending is-saving is-saved is-error');
            if (state && state !== 'idle') {
                $fab.addClass('is-' + state);
            }
            // Auto-clear is-saved après 2s
            if (state === 'saved') {
                setTimeout(function() { $fab.removeClass('is-saved'); }, 2000);
            }
        }
    }

    // Extraite de mgAutoSave. Les 4 chemins de save (3 manuels + autosave)
    // passent tous ici. Un nouveau champ = UNE entrée fieldMap, point.
    // `extra` = champs hors-fieldMap (credentials : visitor_password, clear_password).
    function mgCollectData(extra) {
        var collectData = function() {
            var data = {
                action: 'mg_save',
                nonce: mgAdmin.nonce
            };
            var fieldMap = [
                // Général
                ['page_mode', null, 'radio'],
                ['title', 'mg-title', 'val'],
                ['subtitle', 'mg-subtitle', 'val'],
                ['message', 'mg-message', 'val'],
                ['logo_url', 'mg-logo-url', 'val'],
                ['logo_size', 'mg-logo-size', 'val'],
                ['show_admin_button', 'mg-show-admin-button', 'check'],

                // Couleurs background
                ['bg_color_1', 'mg-bg-color-1', 'val'],
                ['bg_color_1_opacity', 'mg-bg1-opacity', 'val'],
                ['bg_color_2', 'mg-bg-color-2', 'val'],
                ['bg_color_2_opacity', 'mg-bg2-opacity', 'val'],

                // Couleurs texte
                ['title_color', 'mg-title-color', 'val'],
                ['title_opacity', 'mg-title-opacity', 'val'],
                ['message_color', 'mg-message-color', 'val'],
                ['message_opacity', 'mg-message-opacity', 'val'],
                ['button_color', 'mg-button-color', 'val'],
                ['button_opacity', 'mg-button-opacity', 'val'],

                // Image background standard + custom
                ['bg_image_enabled', 'mg-bg-image-enabled', 'check'],
                ['bg_image_url', 'mg-bg-image-url', 'val'],
                ['bg_overlay_opacity', 'mg-bg-overlay-opacity', 'val'],

                // Container
                ['container_bg_color', 'mg-container-bg-color', 'val'],
                ['container_bg_opacity', 'mg-container-opacity', 'val'],
                ['container_shadow_enabled', 'mg-container-shadow', 'check'],
                ['container_shadow_intensity', 'mg-shadow-intensity', 'val'],
                ['container_max_width', 'mg-container-max-width', 'val'],
                ['container_padding', 'mg-container-padding', 'val'],
                ['container_border_radius', 'mg-container-radius', 'val'],

                // Typographie
                ['title_font', 'mg-title-font', 'val'],
                ['message_font', 'mg-message-font', 'val'],
                ['title_size', 'mg-title-size', 'val'],
                ['message_size', 'mg-message-size', 'val'],

                // Animations
                ['animation_enabled', 'mg-animation-enabled', 'check'],
                ['logo_animation', 'mg-logo-animation', 'val'],
                ['text_animation', 'mg-text-animation', 'val'],
                ['button_animation', 'mg-button-animation', 'val'],
                ['animation_duration', 'mg-animation-duration', 'val'],
                ['parallax_enabled', 'mg-parallax-enabled', 'check'],
                ['parallax_intensity', 'mg-parallax-intensity', 'val'],

                // Lottie
                ['lottie_enabled', 'mg-lottie-enabled', 'check'],
                ['lottie_url', 'mg-lottie-url', 'val'],
                ['lottie_size', 'mg-lottie-size', 'val'],
                ['lottie_speed', 'mg-lottie-speed', 'val'],
                ['lottie_loop', 'mg-lottie-loop', 'check'],
                ['lottie_autoplay', 'mg-lottie-autoplay', 'check'],
                ['lottie_position', 'mg-lottie-position', 'val'],

                // Vidéo background
                ['video_bg_enabled', 'mg-video-bg-enabled', 'check'],
                ['video_bg_url', 'mg-video-bg-url', 'val'],
                ['video_bg_opacity', 'mg-video-bg-opacity', 'val'],
                ['video_bg_loop', 'mg-video-bg-loop', 'check'],
                ['video_bg_autoplay', 'mg-video-bg-autoplay', 'check'],
                ['video_bg_muted', 'mg-video-bg-muted', 'check'],

                // SEO & Tech
                ['rgpd_mode', 'mg-rgpd-mode', 'check'],
                ['seo_503_enabled', 'mg-seo-503', 'check'],
                ['retry_after_hours', 'mg-retry-after', 'val'],
                ['noindex_enabled', 'mg-noindex', 'check'],
                ['show_powered_by', 'mg-show-powered-by', 'check'],
                ['purge_data_on_uninstall', 'mg-purge-data-on-uninstall', 'check'],

                // Sidebar
                ['sidebar_enabled', 'mg-sidebar-enabled', 'check'],
                ['sidebar_position', 'mg-sidebar-position', 'val'],
                ['sidebar_tab_color', 'mg-sidebar-tab-color', 'val'],

                // Social
                ['social_facebook', 'mg-social-facebook', 'val'],
                ['social_twitter', 'mg-social-twitter', 'val'],
                ['social_instagram', 'mg-social-instagram', 'val'],
                ['social_linkedin', 'mg-social-linkedin', 'val'],
                ['social_youtube', 'mg-social-youtube', 'val'],
                ['social_tiktok', 'mg-social-tiktok', 'val'],

                // Contact
                ['contact_email', 'mg-contact-email', 'val'],
                ['contact_phone', 'mg-contact-phone', 'val'],
                ['contact_whatsapp', 'mg-contact-whatsapp', 'val'],

                // Visitor access
                ['visitor_access_enabled', 'mg-visitor-access', 'check'],
                ['visitor_access_duration', 'mg-visitor-duration', 'val'],

                // Notification (collecte emails)
                ['notification_enabled', 'mg-notification-enabled', 'check'],
                ['notification_button_text', 'mg-notification-button-text', 'val'],
                ['notification_success_msg', 'mg-notification-success-msg', 'val'],
                // dans le template, aucun traitement PHP — même classe de bug que v2.9.109).

                // Stats
                ['stats_enabled', 'mg-stats-enabled', 'check'],

                // Countdown
                ['countdown_enabled', 'mg-countdown-enabled', 'check'],
                ['countdown_title', 'mg-countdown-title', 'val'],
                ['countdown_date', 'mg-countdown-date', 'val'],
                ['countdown_time', 'mg-countdown-time', 'val'],
                ['countdown_end_text', 'mg-countdown-end-text', 'val'],
                ['countdown_style', 'mg-countdown-style', 'val'],
                ['countdown_auto_disable', 'mg-countdown-auto-disable', 'check'],
                ['countdown_show_days', 'mg-countdown-show-days', 'check'],
                ['countdown_show_hours', 'mg-countdown-show-hours', 'check'],
                ['countdown_show_minutes', 'mg-countdown-show-minutes', 'check'],
                ['countdown_show_seconds', 'mg-countdown-show-seconds', 'check'],

                // Schedule
                ['schedule_enabled', 'mg-schedule-enabled', 'check'],
                ['schedule_start_date', 'mg-schedule-start-date', 'val'],
                ['schedule_start_time', 'mg-schedule-start-time', 'val'],
                ['schedule_end_date', 'mg-schedule-end-date', 'val'],
                ['schedule_end_time', 'mg-schedule-end-time', 'val'],
                ['schedule_timezone', 'mg-schedule-timezone', 'val']
            ];

            fieldMap.forEach(function(f) {
                var key = f[0], id = f[1], type = f[2];
                if (type === 'radio') {
                    data[key] = $('input[name="' + key + '"]:checked').val() || 'maintenance';
                    return;
                }
                var $el = $('#' + id);
                if (!$el.length) return; // Champ pas dans cette page → skip
                if (type === 'check') {
                    data[key] = $el.is(':checked') ? 'true' : 'false';
                } else {
                    data[key] = $el.val();
                }
            });

            return data;
        };

        var result = collectData();
        if (extra) {
            for (var k in extra) {
                if (Object.prototype.hasOwnProperty.call(extra, k)) {
                    result[k] = extra[k];
                }
            }
        }
        return result;
    }

    function mgAutoSave() {
        if (mgAutoSavePending) return;
        mgAutoSavePending = true;
        mgSetSaveButtonState('saving');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: mgCollectData(),
            success: function(response) {
                mgAutoSavePending = false;
                if (response.success) {
                    mgSetSaveButtonState('saved');
                    // pour ne pas spammer pendant l'ajustement d'un slider.
                    var now = Date.now();
                    if (now - mgLastAutoSaveToast > 4000) {
                        showNotice('✓ ' + (mgAdmin.i18n.saved || 'Saved'), 'success');
                        mgLastAutoSaveToast = now;
                    }
                } else {
                    mgSetSaveButtonState('error');
                    // Erreur = toujours un toast (jamais silencieux)
                    showNotice((response.data && response.data.message) ? response.data.message : (mgAdmin.i18n.unknown || 'Save error'), 'error');
                }
            },
            error: function() {
                mgAutoSavePending = false;
                mgSetSaveButtonState('error');
                showNotice(mgAdmin.i18n.connection_error || 'Connection error', 'error');
            }
        });
    }

    function mgScheduleAutoSave() {
        clearTimeout(mgAutoSaveTimer);
        mgSetSaveButtonState('pending');
        mgAutoSaveTimer = setTimeout(mgAutoSave, mgAutoSaveDelay);
    }

    // Hook sur les changements de tous les inputs/sliders/selects de la page settings
    // checkbox d'activation incluses (bg-image, vidéo, lottie, parallaxe, etc.).
    $(document).on('input change', '.mg-settings-area input, .mg-settings-area select, .mg-settings-area textarea, '
        + '.mg-color-picker, .mg-opacity-slider, .mg-range-slider, '
        + 'input[name="page_mode"], '
        + '#mg-animation-duration, #mg-animation-enabled, #mg-bg-color-1, #mg-bg-color-2, #mg-bg-image-enabled, #mg-bg-image-url, #mg-bg-overlay-opacity, #mg-bg1-opacity, #mg-bg2-opacity, #mg-button-animation, #mg-button-color, #mg-button-opacity, #mg-contact-email, #mg-contact-phone, #mg-contact-whatsapp, #mg-container-bg-color, #mg-container-max-width, #mg-container-opacity, #mg-container-padding, #mg-container-radius, #mg-container-shadow, #mg-countdown-auto-disable, #mg-countdown-date, #mg-countdown-enabled, #mg-countdown-end-text, #mg-countdown-show-days, #mg-countdown-show-hours, #mg-countdown-show-minutes, #mg-countdown-show-seconds, #mg-countdown-style, #mg-countdown-time, #mg-countdown-title, #mg-show-powered-by, #mg-purge-data-on-uninstall, #mg-logo-animation, #mg-logo-size, #mg-logo-url, #mg-lottie-autoplay, #mg-lottie-enabled, #mg-lottie-loop, #mg-lottie-position, #mg-lottie-size, #mg-lottie-speed, #mg-lottie-url, #mg-message, #mg-message-color, #mg-message-font, #mg-message-opacity, #mg-message-size, #mg-noindex, #mg-notification-button-text, #mg-notification-emails, #mg-notification-enabled, #mg-notification-success-msg, #mg-parallax-enabled, #mg-parallax-intensity, #mg-retry-after, #mg-rgpd-mode, #mg-schedule-enabled, #mg-schedule-end-date, #mg-schedule-end-time, #mg-schedule-start-date, #mg-schedule-start-time, #mg-schedule-timezone, #mg-seo-503, #mg-shadow-intensity, #mg-show-admin-button, #mg-sidebar-enabled, #mg-sidebar-position, #mg-sidebar-tab-color, #mg-social-facebook, #mg-social-instagram, #mg-social-linkedin, #mg-social-tiktok, #mg-social-twitter, #mg-social-youtube, #mg-stats-enabled, #mg-text-animation, #mg-subtitle, #mg-title, #mg-title-color, #mg-title-font, #mg-title-opacity, #mg-title-size, #mg-video-bg-autoplay, #mg-video-bg-enabled, #mg-video-bg-loop, #mg-video-bg-muted, #mg-video-bg-opacity, #mg-video-bg-url, #mg-visitor-access, #mg-visitor-duration', function(e) {
        var $el = $(this);
        if (mgIsExcluded($el)) return;
        // Évite les doubles déclenchements wp-color-picker (input + change)
        mgScheduleAutoSave();
    });

    // Avertir si quitte la page pendant un debounce (sauvegarde non terminée)
    $(window).on('beforeunload', function() {
        if (mgAutoSaveTimer && $('.mg-section-save').hasClass('is-pending')) {
            return (window.mgAdmin && mgAdmin.i18n && mgAdmin.i18n.unsaved_warning)
                || 'You have unsaved changes. Leave anyway?';
        }
    });

    var mediaUploader;

    $('#mg-upload-logo').on('click', function(e) {
        e.preventDefault();

        if (mediaUploader) {
            mediaUploader.open();
            return;
        }

        mediaUploader = wp.media({
            title: mgAdmin.i18n.choose_logo,
            button: { text: mgAdmin.i18n.use },
            multiple: false,
            library: { type: 'image' }
        });

        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#mg-logo-url').val(attachment.url).trigger('change');

            var $preview = $('#mg-logo-preview');
            $preview.find('img').attr('src', attachment.url);
            $preview.show();
            $('#mg-logo-placeholder').hide();
            $('#mg-remove-logo').show();
            $('#mg-logo-size-container').show(); // Afficher slider taille
        });

        mediaUploader.open();
    });

    $('#mg-remove-logo').on('click', function(e) {
        e.preventDefault();
        $('#mg-logo-url').val('').trigger('change');
        $('#mg-logo-preview').hide();
        $('#mg-logo-placeholder').show();
        $(this).hide();
        $('#mg-logo-size-container').hide(); // Masquer slider taille
    });

    var bgImageUploader;

    $('#mg-upload-bg-image').on('click', function(e) {
        e.preventDefault();

        if (bgImageUploader) {
            bgImageUploader.open();
            return;
        }

        bgImageUploader = wp.media({
            title: mgAdmin.i18n.choose_bg_image,
            button: { text: mgAdmin.i18n.use },
            multiple: false,
            library: { type: 'image' }
        });

        bgImageUploader.on('select', function() {
            var attachment = bgImageUploader.state().get('selection').first().toJSON();
            $('#mg-bg-image-url').val(attachment.url).trigger('change');

            var $preview = $('#mg-bg-image-preview');
            if ($preview.length === 0) {
                $preview = $('<div class="mg-bg-image-preview" id="mg-bg-image-preview"><img src="" alt="BG"></div>');
                $('#mg-bg-image-group').prepend($preview);
            }

            $preview.find('img').attr('src', attachment.url);
            $preview.show();
            $('#mg-remove-bg-image').show();
        });

        bgImageUploader.open();
    });

    $('#mg-remove-bg-image').on('click', function(e) {
        e.preventDefault();
        $('#mg-bg-image-url').val('').trigger('change');
        $('#mg-bg-image-preview').hide();
        $(this).hide();
    });

    $('#mg-preview-btn, #mg-preview-btn-design').on('click', function(e) {
        e.preventDefault();
        if (mgAdmin.preview_url) {
            window.open(mgAdmin.preview_url, '_blank');
        } else {
            alert(mgAdmin.i18n.preview_url_error);
        }
    });

    function showNotice(message, type) {
        var $container = $('#mg-notice-container');

        if ($container.length === 0) {
            $container = $('<div id="mg-notice-container"></div>').css({
                position: 'fixed',
                top: '32px',
                right: '20px',
                zIndex: 999999
            });
            $('body').append($container);
        }

        var bgColor = type === 'success' ? '#4CAF50' : '#f44336';

        var $notice = $('<div></div>').text(message).css({
            background: bgColor,
            color: '#fff',
            padding: '15px 25px',
            borderRadius: '8px',
            marginBottom: '10px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            fontSize: '14px',
            fontWeight: '600',
            minWidth: '300px',
            opacity: '0',
            transform: 'translateX(400px)',
            transition: 'all 0.3s'
        });

        $container.append($notice);

        setTimeout(function() {
            $notice.css({ opacity: '1', transform: 'translateX(0)' });
        }, 10);

        setTimeout(function() {
            $notice.css({ opacity: '0', transform: 'translateX(400px)' });
            setTimeout(function() { $notice.remove(); }, 300);
        }, 4000);
    }

    // THÈMES COMPLETS v2.9.118

    // Appliquer un thème
    $(document).on('click', '.mg-theme-card', function() {
        var $card    = $(this);
        var themeId  = $card.data('theme-id');
        var label    = $card.find('.mg-theme-label').text().trim();
        var confirmMsg = mgAdmin.i18n.theme_confirm
            ? mgAdmin.i18n.theme_confirm.replace('%s', label)
            : 'Apply theme "' + label + '"? Your current visual settings will be saved for undo.';

        if (!window.confirm(confirmMsg)) { return; }

        $card.prop('disabled', true);
        $.ajax({
            url:  mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action:   'mg_apply_theme',
                nonce:    mgAdmin.nonce,
                theme_id: themeId
            },
            success: function(response) {
                $card.prop('disabled', false);
                if (response && response.success) {
                    // Badge actif sur la carte choisie
                    $('.mg-theme-card').removeClass('is-active')
                        .find('.mg-theme-active-badge').remove();
                    $card.addClass('is-active');
                    if (!$card.find('.mg-theme-active-badge').length) {
                        $card.find('.mg-theme-info').prepend(
                            $('<span class="mg-theme-active-badge"></span>')
                                .text(mgAdmin.i18n.theme_applied_badge || 'applied')
                        );
                    }
                    // Afficher le bouton Annuler si absent
                    if (!$('#mg-revert-theme').length) {
                        var $revertBtn = $('<button type="button" class="mg-btn mg-btn-sm mg-btn-secondary" id="mg-revert-theme"></button>')
                            .text('\u21A9 ' + (mgAdmin.i18n.revert_theme || 'Revert Theme'));
                        $('#mg-themes-section .mg-themes-header').append($revertBtn);
                    }
                    showNotice(response.data.message, 'success');
                } else {
                    var errMsg = (response && response.data && response.data.message) ? response.data.message : 'Error';
                    showNotice(errMsg, 'error');
                }
            },
            error: function() {
                $card.prop('disabled', false);
                showNotice(mgAdmin.i18n.connection_error || 'Connection error', 'error');
            }
        });
    });

    // Annuler le thème
    $(document).on('click', '#mg-revert-theme', function() {
        var $btn = $(this);
        $btn.prop('disabled', true);
        $.ajax({
            url:  mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_revert_theme', nonce: mgAdmin.nonce },
            success: function(response) {
                $btn.prop('disabled', false);
                if (response && response.success) {
                    // Retirer badge + bouton Annuler
                    $('.mg-theme-card').removeClass('is-active')
                        .find('.mg-theme-active-badge').remove();
                    $btn.remove();
                    showNotice(response.data.message, 'success');
                } else {
                    var errMsg = (response && response.data && response.data.message) ? response.data.message : 'Error';
                    showNotice(errMsg, 'error');
                }
            },
            error: function() {
                $btn.prop('disabled', false);
                showNotice(mgAdmin.i18n.connection_error || 'Connection error', 'error');
            }
        });
    });


    $('.mg-preset-btn').on('click', function() {
        var preset = $(this).data('preset');
        var $btn = $(this);

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_apply_preset',
                nonce: mgAdmin.nonce,
                preset: preset
            },
            beforeSend: function() {
                $btn.css('opacity', '0.5');
            },
            success: function(response) {
                if (response.success) {
                    var p = response.data.preset;
                    $('#mg-bg-color-1').val(p.bg_color_1).trigger('change');
                    $('#mg-bg-color-2').val(p.bg_color_2).trigger('change');
                    $('#mg-title-color').val(p.title_color).trigger('change');
                    $('#mg-message-color').val(p.message_color).trigger('change');
                    $('#mg-button-color').val(p.button_color).trigger('change');
                    $('#mg-container-bg-color').val(p.container_bg_color).trigger('change');
                    
                    if (p.bg_image_enabled && p.bg_image_url) {
                        $('#mg-bg-image-enabled').prop('checked', true).trigger('change');
                        $('#mg-bg-image-url').val(p.bg_image_url).trigger('change');
                        $('#mg-bg-image-group').slideDown(300);
                        var $preview = $('#mg-bg-image-preview');
                        if ($preview.length) {
                            $preview.find('img').attr('src', p.bg_image_url);
                            $preview.show();
                        }
                    } else {
                        $('#mg-bg-image-enabled').prop('checked', false).trigger('change');
                        $('#mg-bg-image-url').val('').trigger('change');
                        $('#mg-bg-image-group').slideUp(300);
                    }

                    if (p.video_bg_enabled && p.video_bg_url) {
                        $('#mg-video-bg-enabled').prop('checked', true).trigger('change');
                        $('#mg-video-bg-url').val(p.video_bg_url).trigger('input');
                        if (p.video_bg_opacity) { $('#mg-video-bg-opacity').val(p.video_bg_opacity).trigger('change'); }
                        if (typeof p.video_bg_muted !== 'undefined') { $('#mg-video-bg-muted').prop('checked', !!p.video_bg_muted).trigger('change'); }
                    } else {
                        $('#mg-video-bg-enabled').prop('checked', false).trigger('change');
                        $('#mg-video-bg-url').val('').trigger('input');
                    }

                    $('#mg-lottie-enabled').prop('checked', false).trigger('change');
                    $('#mg-lottie-url').val('').trigger('change');
                    $('#mg-lottie-options').slideUp();
                    $('#mg-lottie-dropzone-content').html(
                        '<div style="font-size: 40px; margin-bottom: 10px;">📁</div>' +
                        '<p style="color: #666; margin: 0; font-size: 14px;">' +
                        '<strong>'+mgAdmin.i18n.drag_drop+'</strong> '+mgAdmin.i18n.your_file_here +
                        '</p>' +
                        '<p style="color: #999; margin: 5px 0 0 0; font-size: 12px;">'+mgAdmin.i18n.or_click_select+'</p>'
                    );
                    $('#mg-lottie-actions').hide();
                    $('#mg-lottie-preview').empty();
                    $('#mg-lottie-preview-placeholder').show();

                    $('.mg-preset-btn').removeClass('active');
                    $btn.addClass('active');

                    showNotice(response.data.message, 'success');
                }
            },
            complete: function() {
                $btn.css('opacity', '1');
            }
        });
    });

    
    $('#mg-float-toggle').on('click', function() {
        var $btn = $(this);
        var $mainToggle = $('#mg-toggle');
        var isCurrentlyActive = $btn.hasClass('active');
        var newState = !isCurrentlyActive;
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_toggle',
                nonce: mgAdmin.nonce,
                enabled: newState
            },
            beforeSend: function() {
                $btn.css('opacity', '0.5');
            },
            success: function(response) {
                if (response.success) {
                    $btn.toggleClass('active', newState);
                    $btn.find('.mg-float-label').text(newState ? 'ON' : 'OFF');
                    $btn.attr('title', newState ? mgAdmin.i18n.disable_maintenance : mgAdmin.i18n.enable_maintenance);
                    
                    $mainToggle.prop('checked', newState);
                    $('#mg-status-badge').text(newState ? 'ON' : 'OFF')
                        .removeClass('active inactive')
                        .addClass(newState ? 'active' : 'inactive');
                    
                    showNotice(response.data.message, 'success');
                }
            },
            complete: function() {
                $btn.css('opacity', '1');
            }
        });
    });
    
    $('#mg-float-preview').on('click', function() {
        window.open(mgAdmin.preview_url, '_blank');
    });
    
    $('#mg-float-save').on('click', function() {
        var $btn = $(this);
        $btn.addClass('saving');
        
        // Si on est sur l'onglet monitoring, sauver aussi les settings monitoring
        var activeTab = $('.mg-tab.active').attr('data-tab');
        if (activeTab === 'monitoring') {
            $('.mg-monitoring-save-btn').first().trigger('click');
        } else {
            saveAllSettings($btn, mgAdmin.i18n.all_saved);
        }
        
        setTimeout(function() {
            $btn.removeClass('saving').addClass('saved');
            setTimeout(function() {
                $btn.removeClass('saved');
            }, 2000);
        }, 500);
    });

    $('#mg-whitelist-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-whitelist-options').slideDown(300);
        } else {
            $('#mg-whitelist-options').slideUp(300);
        }
    });

    $('#mg-blacklist-enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#mg-blacklist-options').slideDown(300);
        } else {
            $('#mg-blacklist-options').slideUp(300);
        }
    });

    $('#mg-save-whitelist').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();

        var roles = [];
        $('input[name="whitelist_roles[]"]:checked').each(function() {
            roles.push($(this).val());
        });
        if (roles.indexOf('administrator') === -1) {
            roles.push('administrator');
        }

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_save_access',
                nonce: mgAdmin.nonce,
                whitelist_enabled: $('#mg-whitelist-enabled').is(':checked'),
                whitelist_urls: $('#mg-whitelist-urls').val(),
                whitelist_ips: $('#mg-whitelist-ips').val(),
                whitelist_roles: roles,
                whitelist_user_agents: $('#mg-whitelist-user-agents').val()
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.saving);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(mgAdmin.i18n.whitelist_saved, 'success');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#mg-save-blacklist').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();

        var countries = [];
        $('input[name="blacklist_countries[]"]:checked').each(function() {
            countries.push($(this).val());
        });

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_save_access',
                nonce: mgAdmin.nonce,
                blacklist_enabled: $('#mg-blacklist-enabled').is(':checked'),
                blacklist_ips: $('#mg-blacklist-ips').val(),
                blacklist_user_agents: $('#mg-blacklist-user-agents').val(),
                blacklist_referrers: $('#mg-blacklist-referrers').val(),
                blacklist_countries: countries,
                blacklist_message: $('#mg-blacklist-message').val(),
                blacklist_logging: $('#mg-blacklist-logging').is(':checked')
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.saving);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(mgAdmin.i18n.blacklist_saved, 'success');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#mg-load-logs').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_get_blacklist_logs',
                nonce: mgAdmin.nonce
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.loading);
            },
            success: function(response) {
                if (response.success) {
                    var logs = response.data.logs;
                    var $tbody = $('#mg-logs-body');
                    $tbody.empty();

                    if (logs.length === 0) {
                        $('#mg-logs-container').hide();
                        $('#mg-logs-empty').text('Aucun log de blocage').show();
                    } else {
                        $('#mg-logs-empty').hide();
                        logs.forEach(function(log) {
                            $tbody.append(
                                '<tr>' +
                                '<td>' + log.time + '</td>' +
                                '<td>' + log.ip + '</td>' +
                                '<td>' + log.reason + '</td>' +
                                '<td title="' + log.uri + '">' + log.uri + '</td>' +
                                '</tr>'
                            );
                        });
                        $('#mg-logs-container').show();
                    }
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#mg-clear-logs').on('click', function() {
        if (!confirm(mgAdmin.i18n.confirm_clear_logs)) {
            return;
        }

        var $btn = $(this);
        var originalText = $btn.text();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_clear_blacklist_logs',
                nonce: mgAdmin.nonce
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.deleting);
            },
            success: function(response) {
                if (response.success) {
                    $('#mg-logs-body').empty();
                    $('#mg-logs-container').hide();
                    $('#mg-logs-empty').text(mgAdmin.i18n.logs_cleared).show();
                    showNotice(mgAdmin.i18n.logs_cleared, 'success');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    
    function escapeHtml(str) {
        if (!str) return '';
        return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
    }
    
    function loadTokens() {
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_get_tokens', nonce: mgAdmin.nonce },
            success: function(response) {
                if (response.success) {
                    renderTokens(response.data.tokens);
                }
            }
        });
    }
    
    // d'une table #mg-tokens-body qui n'a jamais existé dans le template.
    function renderTokens(tokens) {
        var $list = $('#mg-tokens-list');
        if (!$list.length) { return; }
        $list.empty();

        if (!tokens || tokens.length === 0) {
            $list.append($('<p/>', {
                'class': 'mg-no-tokens',
                'style': 'color: #666; font-style: italic;',
                text: mgAdmin.i18n.no_tokens || 'No token created'
            }));
            return;
        }

        tokens.forEach(function(t) {
            var $item = $('<div/>', { 'class': 'mg-token-item' + (t.is_expired ? ' mg-token-expired' : ''), 'data-token': t.token });
            var $info = $('<div/>', { 'class': 'mg-token-info' });
            $info.append($('<strong/>', { text: t.name }));
            $info.append($('<span/>', { 'class': 'mg-token-meta', text: t.expires + ' | ' + t.visits + ' ' + (mgAdmin.i18n.visits || 'visits') }));
            var $actions = $('<div/>', { 'class': 'mg-token-actions' });
            $actions.append($('<button/>', { type: 'button', 'class': 'mg-btn mg-btn-secondary mg-copy-token', 'data-url': t.url, text: mgAdmin.i18n.copy_link || 'Copy link' }));
            $actions.append($('<button/>', { type: 'button', 'class': 'mg-btn mg-btn-danger mg-delete-token', 'data-token': t.token, 'data-name': t.name, html: '&times;' }));
            $item.append($info).append($actions);
            $list.append($item);
        });
    }

    function updateStats(stats) {
        $('#mg-stat-active').text(stats.active);
        $('#mg-stat-expired').text(stats.expired);
        $('#mg-stat-visits').text(stats.total_visits);
        $('#mg-stat-today').text(stats.today_visits);
        $('#mg-tokens-used').text(stats.active);
        $('#mg-tokens-limit').text(stats.limit === 0 ? '∞' : stats.limit);
    }
    
    if ($('#tab-access').is(':visible') || $('.mg-tab[data-tab="access"]').hasClass('active')) {
        loadTokens();
    }
    
    $('.mg-tab[data-tab="access"]').on('click', function() {
        setTimeout(loadTokens, 100);
    });
    
    $(document).on('click', '.mg-copy-token', function() {
        var $btn = $(this);
        var url = $btn.data('url');
        navigator.clipboard.writeText(url).then(function() {
            $btn.text(mgAdmin.i18n.copied).addClass('copied');
            setTimeout(function() { $btn.text('Copier').removeClass('copied'); }, 2000);
        });
    });
    
    $(document).on('click', '.mg-delete-token', function() {
        var token = $(this).data('token');
        var name = $(this).data('name');
        if (!confirm(mgAdmin.i18n.confirm_delete_access.replace('%s', name))) return;
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_delete_token', nonce: mgAdmin.nonce, token: token },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    loadTokens();
                } else {
                    showNotice(response.data.message, 'error');
                }
            }
        });
    });
    
    $(document).on('click', '.mg-token-action-btn.email', function() {
        var $btn = $(this);
        var token = $btn.data('token');
        $btn.prop('disabled', true);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_resend_token_email', nonce: mgAdmin.nonce, token: token },
            success: function(response) {
                showNotice(response.success ? response.data.message : response.data.message, response.success ? 'success' : 'error');
            },
            complete: function() { $btn.prop('disabled', false); }
        });
    });
    
    // de token (JS écrit pour une modale-formulaire jamais présente dans le
    // template). Câblage réel sur le formulaire inline.
    $('#mg-create-token').on('click', function() {
        var $btn = $(this);
        var name = $.trim($('#mg-new-token-name').val() || '');
        if (!name) {
            showNotice(mgAdmin.i18n.token_name_required || 'Name is required', 'error');
            $('#mg-new-token-name').focus();
            return;
        }

        var durationMap = { '3600': '1h', '86400': '24h', '604800': '7d', '2592000': '30d' };
        var seconds = String($('#mg-new-token-duration').val());
        var expiration = durationMap[seconds] || '7d';
        var customDate = '';
        if (seconds === '0') {
            expiration = 'custom';
            customDate = '2099-12-31';
        }

        var originalText = $btn.text();

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_create_token',
                nonce: mgAdmin.nonce,
                name: name,
                expiration: expiration,
                custom_date: customDate
            },
            beforeSend: function() { $btn.prop('disabled', true).text('...'); },
            success: function(response) {
                if (response.success) {
                    $('#mg-new-token-name').val('');
                    $('#mg-created-url').val(response.data.url);
                    $('#mg-email-status').hide();
                    $('#mg-token-modal').show();
                    loadTokens();
                } else {
                    showNotice(response.data.message, 'error');
                }
            },
            complete: function() { $btn.prop('disabled', false).text(originalText); }
        });
    });
    
    $(document).on('click', '.mg-modal-close, .mg-modal-overlay, #mg-token-cancel, #mg-config-cancel, #mg-success-close', function() {
        $(this).closest('.mg-modal').hide();
        if ($('#mg-token-form').length) $('#mg-token-form')[0].reset();
        $('#mg-token-custom-date-group, #mg-token-ip-group').hide();
    });
    
    $('#mg-token-expiration').on('change', function() {
        $('#mg-token-custom-date-group').toggle($(this).val() === 'custom');
    });
    
    $('#mg-token-ip-restrict-toggle').on('change', function() {
        $('#mg-token-ip-group').toggle($(this).is(':checked'));
    });
    
    $('#mg-token-form').on('submit', function(e) {
        e.preventDefault();
        var $btn = $('#mg-token-submit');
        var originalText = $btn.text();
        var emailVal = $('#mg-token-email').val();
        var sendEmail = $('#mg-token-send-email').is(':checked') && emailVal ? 'true' : 'false';
        var passwordToInclude = $('#mg-token-password').val();
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_create_token',
                nonce: mgAdmin.nonce,
                name: $('#mg-token-name').val(),
                email: emailVal,
                expiration: $('#mg-token-expiration').val(),
                custom_date: $('#mg-token-custom-date').val(),
                single_use: $('#mg-token-single-use').is(':checked') ? 'true' : 'false',
                ip_restrict: $('#mg-token-ip-restrict-toggle').is(':checked') ? $('#mg-token-ip').val() : '',
                send_email: sendEmail,
                include_password: passwordToInclude
            },
            beforeSend: function() { $btn.prop('disabled', true).text(mgAdmin.i18n.creating); },
            success: function(response) {
                if (response.success) {
                    $('#mg-token-modal').hide();
                    $('#mg-token-form')[0].reset();
                    $('#mg-created-url').val(response.data.url);
                    $('#mg-email-status').toggle(response.data.email_sent);
                    $('#mg-success-modal').show();
                    loadTokens();
                } else {
                    showNotice(response.data.message, 'error');
                }
            },
            complete: function() { $btn.prop('disabled', false).text(originalText); }
        });
    });
    
    $('#mg-copy-created-url').on('click', function() {
        var $btn = $(this);
        navigator.clipboard.writeText($('#mg-created-url').val()).then(function() {
            $btn.text(mgAdmin.i18n.copied);
            setTimeout(function() { $btn.text('Copier'); }, 2000);
        });
    });
    
    $('#mg-config-tokens').on('click', function() { $('#mg-config-modal').show(); });
    
    $('#mg-config-form').on('submit', function(e) {
        e.preventDefault();
        var $btn = $('#mg-config-submit');
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_save_token_settings',
                nonce: mgAdmin.nonce,
                custom_access_limit: $('#mg-config-limit').val(),
                custom_access_max_days: $('#mg-config-max-days').val(),
                custom_access_default_days: $('#mg-config-default-days').val()
            },
            beforeSend: function() { $btn.prop('disabled', true).text('...'); },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    $('#mg-config-modal').hide();
                    loadTokens();
                }
            },
            complete: function() { $btn.prop('disabled', false).text(mgAdmin.i18n.save); }
        });
    });
    
    $('#mg-load-access-logs').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text(mgAdmin.i18n.loading);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_get_access_logs', nonce: mgAdmin.nonce },
            success: function(response) {
                if (response.success) {
                    var $tbody = $('#mg-access-logs-body').empty();
                    if (response.data.logs.length === 0) {
                        $('#mg-access-logs-container').hide();
                        $('#mg-access-logs-empty').text('Aucun log').show();
                    } else {
                        $('#mg-access-logs-empty').hide();
                        response.data.logs.forEach(function(log) {
                            $tbody.append('<tr><td>' + log.time + '</td><td>' + escapeHtml(log.name) + '</td><td><code>' + log.ip + '</code></td><td>' + log.device + '</td></tr>');
                        });
                        $('#mg-access-logs-container').show();
                    }
                }
            },
            complete: function() { $btn.prop('disabled', false).text(mgAdmin.i18n.load_logs); }
        });
    });
    
    $('#mg-clear-access-logs').on('click', function() {
        if (!confirm(mgAdmin.i18n.confirm_clear_access_logs)) return;
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_clear_access_logs', nonce: mgAdmin.nonce },
            success: function(response) {
                if (response.success) {
                    $('#mg-access-logs-body').empty();
                    $('#mg-access-logs-container').hide();
                    $('#mg-access-logs-empty').text(mgAdmin.i18n.logs_cleared).show();
                    showNotice(mgAdmin.i18n.logs_cleared, 'success');
                }
            }
        });
    });
    
    $('#mg-export-access-logs').on('click', function() {
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: { action: 'mg_get_access_logs', nonce: mgAdmin.nonce },
            success: function(response) {
                if (response.success && response.data.logs.length > 0) {
                    var csv = 'Date,Visiteur,IP,Appareil\n';
                    response.data.logs.forEach(function(log) {
                        csv += '"' + log.time + '","' + log.name + '","' + log.ip + '","' + log.device + '"\n';
                    });
                    var blob = new Blob([csv], { type: 'text/csv' });
                    var a = document.createElement('a');
                    a.href = URL.createObjectURL(blob);
                    a.download = 'access-logs.csv';
                    a.click();
                } else {
                    showNotice(mgAdmin.i18n.no_logs_export, 'error');
                }
            }
        });
    });

    
    var $floatToggle = $('#mg-float-toggle');
    var isMaintenanceOn = $('#mg-toggle').is(':checked');
    $floatToggle.toggleClass('is-on', isMaintenanceOn).toggleClass('is-off', !isMaintenanceOn);
    
    $(document).on('click', '#mg-float-toggle', function(e) {
        e.preventDefault();
        var $mainToggle = $('#mg-toggle');
        var newState = !$mainToggle.is(':checked');
        $mainToggle.prop('checked', newState).trigger('change');
        
        $(this).toggleClass('is-on', newState).toggleClass('is-off', !newState);
        $('#mg-float-status').text(newState ? 'ON' : 'OFF');
    });
    
    $('#mg-toggle').on('change', function() {
        var isOn = $(this).is(':checked');
        $('#mg-float-toggle').toggleClass('is-on', isOn).toggleClass('is-off', !isOn);
        $('#mg-float-status').text(isOn ? 'ON' : 'OFF');
    });

    (function() {
        var $tooltip = $('<div class="mg-tooltip-box"></div>').appendTo('body');
        
        $(document).on('mouseenter', '[data-tooltip], .mg-info-tooltip', function(e) {
            var $el = $(this);
            var text = $el.attr('data-tooltip');
            
            if (!text || text.length === 0) return;
            
            $tooltip.text(text);
            
            var rect = this.getBoundingClientRect();
            var tooltipWidth = $tooltip.outerWidth();
            var tooltipHeight = $tooltip.outerHeight();
            
            var left = rect.left + (rect.width / 2) - (tooltipWidth / 2);
            var top = rect.top - tooltipHeight - 12;
            
            if (top < 10) {
                top = rect.bottom + 12;
                $tooltip.removeClass('arrow-bottom').addClass('arrow-top');
            } else {
                $tooltip.removeClass('arrow-top').addClass('arrow-bottom');
            }
            
            if (left < 10) {
                left = 10;
            }
            
            if (left + tooltipWidth > window.innerWidth - 10) {
                left = window.innerWidth - tooltipWidth - 10;
            }
            
            $tooltip.css({
                left: left + 'px',
                top: top + 'px'
            }).addClass('visible');
        });
        
        $(document).on('mouseleave', '[data-tooltip], .mg-info-tooltip', function() {
            $tooltip.removeClass('visible');
        });
        
        $('.mg-wrapper [title]').each(function() {
            var $el = $(this);
            var title = $el.attr('title');
            if (title && title.length > 0) {
                $el.attr('data-tooltip', title);
                $el.removeAttr('title');
            }
        });
    })();

    
    $('#mg-activate-license').on('click', function() {
        var $btn = $(this);
        var licenseKey = $('#mg-license-key').val().trim();
        
        if (!licenseKey) {
            showNotice(mgAdmin.i18n.enter_license_key, 'error');
            return;
        }
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_activate_license',
                nonce: mgAdmin.nonce,
                license_key: licenseKey
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.activating);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    if (response.data.reload) {
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showNotice(response.data.message, 'error');
                    $btn.prop('disabled', false).text(mgAdmin.i18n.activate);
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
                $btn.prop('disabled', false).text(mgAdmin.i18n.activate);
            }
        });
    });

    $('#mg-deactivate-license').on('click', function() {
        if (!confirm(mgAdmin.i18n.confirm_deactivate_license)) {
            return;
        }
        
        var $btn = $(this);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_deactivate_license',
                nonce: mgAdmin.nonce
            },
            beforeSend: function() {
                $btn.prop('disabled', true).text(mgAdmin.i18n.deactivating);
            },
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    if (response.data.reload) {
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showNotice(response.data.message, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            }
        });
    });

    $(document).on('click', '.mg-pro-locked-overlay', function(e) {
        e.preventDefault();
        $('[data-tab="pro"]').click();
        $('html, body').animate({ scrollTop: 0 }, 300);
    });

    
    var $chatModal = $('#mg-chat-modal');
    var $chatMessages = $('#mg-chat-messages');
    var $chatInput = $('#mg-chat-input');
    var $chatSend = $('#mg-chat-send');
    var $chatRemaining = $('#mg-chat-remaining');
    
    $('#mg-float-help').on('click', function() {
        if ($chatModal.is(':visible')) {
            $chatModal.fadeOut(200);
        } else {
            $chatModal.fadeIn(200);
            $chatInput.focus();
        }
    });
    
    $('#mg-chat-close').on('click', function() {
        $chatModal.fadeOut(200);
    });
    
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $chatModal.is(':visible')) {
            $chatModal.fadeOut(200);
        }
    });
    
    function sendChatMessage() {
        var question = $chatInput.val().trim();
        
        if (!question) return;
        
        $chatInput.prop('disabled', true);
        $chatSend.prop('disabled', true);
        
        addChatMessage(question, 'user');
        $chatInput.val('');
        
        var $typing = $('<div class="mg-chat-message mg-chat-bot">' +
            '<div class="mg-chat-avatar">🤖</div>' +
            '<div class="mg-chat-typing"><span></span><span></span><span></span></div>' +
            '</div>');
        $chatMessages.append($typing);
        scrollChatToBottom();
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_chat_ask',
                nonce: mgAdmin.nonce,
                question: question
            },
            success: function(response) {
                $typing.remove();
                
                if (response.success) {
                    addChatMessage(response.data.message, 'bot');
                    
                    if (response.data.remaining >= 0 && $chatRemaining.length) {
                        $chatRemaining.text(response.data.remaining);
                    }
                } else {
                    if (response.data.limit_reached) {
                        var limitHtml = '<div class="mg-chat-limit">' +
                            '⚠️ ' + response.data.message + '<br><br>' +
                            '<a href="#" class="mg-go-pro">'+mgAdmin.i18n.go_pro+'</a>' +
                            '</div>';
                        $chatMessages.append(limitHtml);
                    } else {
                        addChatMessage(response.data.message, 'bot');
                    }
                }
                scrollChatToBottom();
            },
            error: function() {
                $typing.remove();
                addChatMessage(mgAdmin.i18n.chat_connection_error, 'bot');
            },
            complete: function() {
                $chatInput.prop('disabled', false);
                $chatSend.prop('disabled', false);
                $chatInput.focus();
            }
        });
    }
    
    function addChatMessage(message, type) {
        var avatar = type === 'bot' ? '🤖' : '👤';
        var html = '<div class="mg-chat-message mg-chat-' + type + '">' +
            '<div class="mg-chat-avatar">' + avatar + '</div>' +
            '<div class="mg-chat-bubble">' + escapeHtml(message).replace(/\n/g, '<br>') + '</div>' +
            '</div>';
        $chatMessages.append(html);
        scrollChatToBottom();
    }
    
    function scrollChatToBottom() {
        $chatMessages.scrollTop($chatMessages[0].scrollHeight);
    }
    
    $chatSend.on('click', sendChatMessage);
    
    $chatInput.on('keypress', function(e) {
        if (e.which === 13 && !e.shiftKey) {
            e.preventDefault();
            sendChatMessage();
        }
    });
    
    $(document).on('click', '.mg-go-pro', function(e) {
        e.preventDefault();
        $chatModal.fadeOut(200);
        $('[data-tab="pro"]').click();
        $('html, body').animate({ scrollTop: 0 }, 300);
    });


    $(document).on('change', '#mg-lottie-enabled', function() {
        if ($(this).is(':checked')) {
            $('#mg-lottie-options').slideDown();
        } else {
            $('#mg-lottie-options').slideUp();
        }
    });

    $(document).on('change', 'input[name="lottie_source"]', function() {
        var source = $(this).val();
        if (source === 'upload') {
            $('#mg-lottie-upload-section').show();
            $('#mg-lottie-url-section').hide();
        } else {
            $('#mg-lottie-upload-section').hide();
            $('#mg-lottie-url-section').show();
        }
    });

    (function() {
        var source = $('input[name="lottie_source"]:checked').val();
        if (source === 'url') {
            $('#mg-lottie-upload-section').hide();
            $('#mg-lottie-url-section').show();
        }
    })();

    $(document).on('input', '#mg-lottie-url-input', function() {
        var url = $(this).val();
        $('#mg-lottie-url').val(url).trigger('change');
        loadLottiePreview(url);
    });

    var $dropzone = $('#mg-lottie-dropzone');
    var $fileInput = $('#mg-lottie-file-input');

    $dropzone.on('click', function(e) {
        if (!$(e.target).is('button')) {
            $fileInput.click();
        }
    });

    $dropzone.on('dragover dragenter', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).css({
            'border-color': '#667eea',
            'background': '#f0f4ff'
        });
    });

    $dropzone.on('dragleave dragend drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).css({
            'border-color': '#ccc',
            'background': '#fafafa'
        });
    });

    $dropzone.on('drop', function(e) {
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            handleLottieFile(files[0]);
        }
    });

    $fileInput.on('change', function() {
        if (this.files.length > 0) {
            handleLottieFile(this.files[0]);
        }
    });

    function handleLottieFile(file) {
        
        var ext = file.name.split('.').pop().toLowerCase();
        if (ext !== 'json' && ext !== 'lottie') {
            alert(mgAdmin.i18n.format_not_supported);
            return;
        }

        if (file.size > 5 * 1024 * 1024) {
            alert(mgAdmin.i18n.file_too_large);
            return;
        }

        uploadLottieFile(file);
    }

    function uploadLottieFile(file) {
        var formData = new FormData();
        formData.append('action', 'mg_upload_lottie');
        formData.append('nonce', mgAdmin.nonce);
        formData.append('lottie_file', file);

        $('#mg-lottie-dropzone-content').hide();
        $('#mg-lottie-upload-progress').show();
        $('#mg-lottie-progress-bar').css('width', '30%');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function() {
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                        $('#mg-lottie-progress-bar').css('width', percent + '%');
                    }
                });
                return xhr;
            },
            success: function(response) {
                if (response.success) {
                    
                    $('#mg-lottie-url').val(response.data.url).trigger('change');
                    $('#mg-lottie-dropzone-content').html(
                        '<div style="color: #27ae60; font-size: 14px;">' +
                        '✅ <strong>' + response.data.filename + '</strong>' +
                        '</div>' +
                        '<p style="color: #666; margin: 10px 0 0 0; font-size: 12px;">Glissez un nouveau fichier pour remplacer</p>'
                    ).show();
                    $('#mg-lottie-upload-progress').hide();
                    $('#mg-lottie-actions').show();
                    
                    loadLottiePreview(response.data.url);
                } else {
                    alert(mgAdmin.i18n.error_prefix + ' ' + (response.data.message || mgAdmin.i18n.upload_failed));
                    resetDropzone();
                }
            },
            error: function(xhr, status, error) {
                alert(mgAdmin.i18n.connection_error_retry);
                resetDropzone();
            }
        });
    }

    function resetDropzone() {
        $('#mg-lottie-dropzone-content').html(
            '<div style="font-size: 40px; margin-bottom: 10px;">📁</div>' +
            '<p style="color: #666; margin: 0; font-size: 14px;">' +
            '<strong>'+mgAdmin.i18n.drag_drop+'</strong> '+mgAdmin.i18n.your_file_here +
            '</p>' +
            '<p style="color: #999; margin: 5px 0 0 0; font-size: 12px;">'+mgAdmin.i18n.or_click_select+'</p>'
        ).show();
        $('#mg-lottie-upload-progress').hide();
        $('#mg-lottie-progress-bar').css('width', '0%');
    }

    $(document).on('click', '#mg-remove-lottie', function() {
        if (!confirm(mgAdmin.i18n.confirm_delete_animation)) return;
        
        $('#mg-lottie-url').val('').trigger('change');
        $('#mg-lottie-actions').hide();
        resetDropzone();
        
        $('#mg-lottie-preview').empty();
        $('#mg-lottie-preview-placeholder').show();
    });

    $(document).on('input', '#mg-lottie-size', function() {
        var val = $(this).val();
        $('#mg-lottie-size-val').text(val + 'px');
    });

    $(document).on('input', '#mg-lottie-speed', function() {
        var val = $(this).val();
        $('#mg-lottie-speed-val').text(val + 'x');
        var player = document.querySelector('#mg-lottie-preview dotlottie-player');
        if (player && player.setSpeed) {
            player.setSpeed(parseFloat(val));
        }
    });

    function loadLottiePreview(url) {
        var $preview = $('#mg-lottie-preview');
        var $placeholder = $('#mg-lottie-preview-placeholder');
        
        
        if (!url || url.trim() === '') {
            $preview.empty();
            $placeholder.show();
            return;
        }
        
        $placeholder.hide();
        
        var previewSize = 150;
        var speed = parseFloat($('#mg-lottie-speed').val()) || 1;
        var loop = $('#mg-lottie-loop').is(':checked');
        var autoplay = $('#mg-lottie-autoplay').is(':checked');
        
        $preview.html(
            '<dotlottie-player ' +
            'src="' + url + '" ' +
            'style="width: ' + previewSize + 'px; height: ' + previewSize + 'px;" ' +
            'background="transparent" ' +
            'speed="' + speed + '" ' +
            (loop ? 'loop ' : '') +
            (autoplay ? 'autoplay ' : '') +
            '></dotlottie-player>'
        );
    }

    function renderLottiePreview(url) {
        loadLottiePreview(url);
    }

    (function() {
        if (!document.querySelector('script[src*="dotlottie-player"]')) {
            var playerUrl = (typeof mgAdmin !== 'undefined' && mgAdmin.lottie_player_url) ? mgAdmin.lottie_player_url : '';
            if (playerUrl) {
                var script = document.createElement('script');
                script.src = playerUrl;
                script.type = 'module';
                document.head.appendChild(script);
            }
        }
    })();

    setTimeout(function() {
        var initialLottieUrl = $('#mg-lottie-url').val();
        if (initialLottieUrl && initialLottieUrl.trim() !== '') {
            loadLottiePreview(initialLottieUrl);
        }
    }, 1000);

    $('#mg-lottie-loop, #mg-lottie-autoplay').on('change', function() {
        var url = $('#mg-lottie-url').val();
        if (url) {
            loadLottiePreview(url);
        }
    });

    $('#mg-save-preset').on('click', function() {
        var presetName = $('#mg-preset-name').val().trim();
        if (!presetName) {
            alert('Veuillez entrer un nom pour le preset');
            $('#mg-preset-name').focus();
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true).text(mgAdmin.i18n.saving_preset);

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_save_custom_preset',
                nonce: mgAdmin.nonce,
                preset_name: presetName
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    location.reload();
                } else {
                    alert(response.data.message || mgAdmin.i18n.save_error);
                }
            },
            error: function() {
                alert(mgAdmin.i18n.connection_error);
            },
            complete: function() {
                $btn.prop('disabled', false).text(mgAdmin.i18n.save_preset_btn);
            }
        });
    });

    $(document).on('click', '.mg-preset-apply', function() {
        var $card = $(this).closest('.mg-custom-preset-card');
        var presetId = $card.data('preset-id');
        var presetName = $card.find('div:first').text().trim();

        if (!confirm(mgAdmin.i18n.confirm_apply_preset.replace('%s', presetName))) {
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true).text('...');

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_apply_custom_preset',
                nonce: mgAdmin.nonce,
                preset_id: presetId
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    location.reload();
                } else {
                    alert(response.data.message || mgAdmin.i18n.error_generic);
                }
            },
            error: function() {
                alert(mgAdmin.i18n.connection_error);
            },
            complete: function() {
                $btn.prop('disabled', false).text('✓ ' + mgAdmin.i18n.apply);
            }
        });
    });

    $(document).on('click', '.mg-preset-delete', function() {
        var $card = $(this).closest('.mg-custom-preset-card');
        var presetId = $card.data('preset-id');
        var presetName = $card.find('div:first').text().trim();

        if (!confirm(mgAdmin.i18n.confirm_delete_preset.replace('%s', presetName))) {
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true);

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_delete_custom_preset',
                nonce: mgAdmin.nonce,
                preset_id: presetId
            },
            success: function(response) {
                if (response.success) {
                    $card.fadeOut(300, function() {
                        $(this).remove();
                        if ($('.mg-custom-preset-card').length === 0) {
                            $('#mg-custom-presets-list').html(
                                '<p class="mg-no-presets" style="color: #666; font-style: italic; padding: 15px; background: #f5f5f5; border-radius: 8px; text-align: center;">' +
                                ''+mgAdmin.i18n.no_custom_presets+'<br>' +
                                ''+mgAdmin.i18n.configure_design_hint+'</p>'
                            );
                        }
                    });
                } else {
                    alert(response.data.message || mgAdmin.i18n.error_generic);
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert(mgAdmin.i18n.connection_error);
                $btn.prop('disabled', false);
            }
        });
    });

    $(document).on('click', '.mg-preset-export', function() {
        var $card = $(this).closest('.mg-custom-preset-card');
        var presetId = $card.data('preset-id');
        
        var exportUrl = mgAdmin.ajaxurl + '?action=mg_export_custom_preset&nonce=' + mgAdmin.nonce + '&preset_id=' + presetId;
        window.location.href = exportUrl;
    });

    $('#mg-export-all-presets').on('click', function() {
        var exportUrl = mgAdmin.ajaxurl + '?action=mg_export_all_presets&nonce=' + mgAdmin.nonce;
        window.location.href = exportUrl;
    });

    $('#mg-import-preset-btn').on('click', function() {
        $('#mg-import-preset-file').click();
    });

    $('#mg-import-preset-file').on('change', function() {
        var file = this.files[0];
        if (!file) return;

        if (!file.name.endsWith('.json')) {
            alert(mgAdmin.i18n.select_json_file_alert);
            return;
        }

        var formData = new FormData();
        formData.append('action', 'mg_import_custom_preset');
        formData.append('nonce', mgAdmin.nonce);
        formData.append('preset_file', file);

        var $btn = $('#mg-import-preset-btn');
        $btn.prop('disabled', true).text(mgAdmin.i18n.importing);

        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    location.reload();
                } else {
                    alert(response.data.message || mgAdmin.i18n.import_error);
                }
            },
            error: function() {
                alert(mgAdmin.i18n.connection_error);
            },
            complete: function() {
                $btn.prop('disabled', false).text(mgAdmin.i18n.import_preset_btn);
                $('#mg-import-preset-file').val('');
            }
        });
    });

    
    $(document).on('change', '#mg-video-bg-enabled', function() {
        if ($(this).is(':checked')) {
            $('#mg-video-bg-options').slideDown();
        } else {
            $('#mg-video-bg-options').slideUp();
        }
    });

    $(document).on('input', '#mg-video-bg-opacity', function() {
        $('#mg-video-opacity-val').text($(this).val() + '%');
    });

    $(document).on('input', '#mg-video-bg-url', function() {
        var url = $(this).val().trim();
        var videoInfo = parseVideoUrl(url);
        
        if (videoInfo) {
            $('#mg-video-detected').show();
            if (videoInfo.type === 'youtube') {
                $('#mg-video-type-badge').text('YouTube').css('background', '#ff0000').css('color', '#fff');
            } else {
                $('#mg-video-type-badge').text('Vimeo').css('background', '#1ab7ea').css('color', '#fff');
            }
            $('#mg-video-id').text('ID: ' + videoInfo.id);
            
            loadVideoPreview(videoInfo);
        } else {
            $('#mg-video-detected').hide();
            $('#mg-video-preview-container').hide();
        }
    });

    function parseVideoUrl(url) {
        if (!url) return null;
        
        var ytRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
        var ytMatch = url.match(ytRegex);
        if (ytMatch) {
            return { type: 'youtube', id: ytMatch[1] };
        }
        
        var vimeoRegex = /(?:vimeo\.com\/)(\d+)/;
        var vimeoMatch = url.match(vimeoRegex);
        if (vimeoMatch) {
            return { type: 'vimeo', id: vimeoMatch[1] };
        }
        
        return null;
    }

    function loadVideoPreview(videoInfo) {
        var $container = $('#mg-video-preview-container');
        var $preview = $('#mg-video-preview');
        
        $container.show();
        
        if (videoInfo.type === 'youtube') {
            $preview.html('<iframe src="https://www.youtube.com/embed/' + videoInfo.id + '?autoplay=0&mute=1" style="width:100%;height:100%;border:none;" allowfullscreen></iframe>');
        } else if (videoInfo.type === 'vimeo') {
            $preview.html('<iframe src="https://player.vimeo.com/video/' + videoInfo.id + '?autoplay=0&muted=1" style="width:100%;height:100%;border:none;" allowfullscreen></iframe>');
        }
    }

    var initialVideoUrl = $('#mg-video-bg-url').val();
    if (initialVideoUrl) {
        var videoInfo = parseVideoUrl(initialVideoUrl);
        if (videoInfo) {
            $('#mg-video-detected').show();
            if (videoInfo.type === 'youtube') {
                $('#mg-video-type-badge').text('YouTube').css('background', '#ff0000').css('color', '#fff');
            } else {
                $('#mg-video-type-badge').text('Vimeo').css('background', '#1ab7ea').css('color', '#fff');
            }
            $('#mg-video-id').text('ID: ' + videoInfo.id);
            loadVideoPreview(videoInfo);
        }
    }

    
    $(document).on('change', '#mg-parallax-enabled', function() {
        if ($(this).is(':checked')) {
            $('#mg-parallax-options').slideDown();
        } else {
            $('#mg-parallax-options').slideUp();
        }
    });

    $(document).on('input', '#mg-parallax-intensity', function() {
        $('#mg-parallax-intensity-val').text($(this).val() + '%');
    });

    
    $(document).on('change', '#mg-stats-enabled', function() {
    });

    $(document).on('click', '#mg-reset-stats', function() {
        if (!confirm(mgAdmin.i18n.confirm_reset_stats)) {
            return;
        }
        
        var $btn = $(this);
        $btn.prop('disabled', true).text(mgAdmin.i18n.resetting_stats);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_reset_stats',
                nonce: mgAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#mg-stats-visits-count').text('0');
                    $('#mg-stats-unique-count').text('0');
                    showNotice(response.data.message, 'success');
                } else {
                    showNotice(response.data.message || mgAdmin.i18n.error_generic, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text(mgAdmin.i18n.reset_stats_btn);
            }
        });
    });

    
    $(document).on('change', '#mg-schedule-enabled', function() {
        if ($(this).is(':checked')) {
            $('#mg-schedule-options').slideDown();
        } else {
            $('#mg-schedule-options').slideUp();
        }
    });

    $(document).on('change', '#mg-schedule-start-date, #mg-schedule-start-time, #mg-schedule-end-date, #mg-schedule-end-time', function() {
        updateScheduleStatus();
    });

    function updateScheduleStatus() {
        var startDate = $('#mg-schedule-start-date').val();
        var startTime = $('#mg-schedule-start-time').val();
        var endDate = $('#mg-schedule-end-date').val();
        var endTime = $('#mg-schedule-end-time').val();
        
        if (startDate && endDate) {
            var $status = $('#mg-schedule-status');
            $status.html(
                '<p style="margin: 0; font-size: 13px; color: #2e7d32;">' +
                '<strong>📊 '+mgAdmin.i18n.schedule_configured+'</strong><br>' +
                '🟢 '+mgAdmin.i18n.start_label+' ' + formatDate(startDate) + ' '+mgAdmin.i18n.at+' ' + (startTime || '00:00') + '<br>' +
                '🔴 '+mgAdmin.i18n.end_label+' ' + formatDate(endDate) + ' '+mgAdmin.i18n.at+' ' + (endTime || '00:00') + '<br>' +
                '<em>💾 Sauvegardez pour activer</em></p>'
            );
        }
    }

    function formatDate(dateStr) {
        if (!dateStr) return '';
        var parts = dateStr.split('-');
        return parts[2] + '/' + parts[1] + '/' + parts[0];
    }

    
    $(document).on('click', '#mg-export-all-settings', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).html(mgAdmin.i18n.exporting);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'mg_export_all_settings',
                nonce: mgAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    var dataStr = JSON.stringify(response.data.data, null, 2);
                    var blob = new Blob([dataStr], {type: 'application/json'});
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = response.data.filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    showNotice(mgAdmin.i18n.config_exported, 'success');
                } else {
                    showNotice(response.data.message || mgAdmin.i18n.export_error, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).html(mgAdmin.i18n.download_backup_btn);
            }
        });
    });
    
    $(document).on('click', '#mg-import-all-settings', function() {
        $('#mg-import-settings-file').click();
    });
    
    $(document).on('change', '#mg-import-settings-file', function() {
        var file = this.files[0];
        if (!file) return;
        
        if (!file.name.endsWith('.json')) {
            showNotice(mgAdmin.i18n.select_json_file, 'error');
            return;
        }
        
        if (!confirm(mgAdmin.i18n.confirm_import_settings)) {
            $(this).val('');
            return;
        }
        
        var $btn = $('#mg-import-all-settings');
        $btn.prop('disabled', true).html('⏳ Import en cours...');
        
        var formData = new FormData();
        formData.append('action', 'mg_import_all_settings');
        formData.append('nonce', mgAdmin.nonce);
        formData.append('config_file', file);
        
        $.ajax({
            url: mgAdmin.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    showNotice(response.data.message || mgAdmin.i18n.import_error, 'error');
                }
            },
            error: function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).html(mgAdmin.i18n.upload_backup_btn);
                $('#mg-import-settings-file').val('');
            }
        });
    });

});

jQuery(document).ready(function($) {
    'use strict';
    
    $(document).ready(function() {
        function mgScrollToSection($el) {
            if (!$el || !$el.length) { return; }
            // Attendre la fin de l'animation slideDown avant de mesurer la position
            setTimeout(function() {
                var adminBar = $('#wpadminbar').length ? $('#wpadminbar').outerHeight() : 0;
                var offset   = adminBar + 16;
                var top      = $el.offset().top - offset;
                $('html, body').animate({ scrollTop: top }, 300);
            }, 260);
        }
        window.mgScrollToSection = mgScrollToSection;

        $(document).on('click', '.mg-bg-toggle', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $u    = $('#mg-bg-unified');
            var $host = $('#mg-bg-host');
            var $btn  = $(this);

            if ($host.is(':animated')) { return; }

            var willOpen = !$u.hasClass('is-open');

            if (willOpen) {
                // accordéon exclusif : fermer les autres sections du même card
                var $card = $u.closest('.mg-card');
                $card.find('.mg-accordion.is-open').each(function() {
                    $(this).removeClass('is-open');
                    $(this).children('.mg-accordion-body').slideUp(250);
                });
                $u.addClass('is-open');
                $host.stop(true, true).slideDown(250);
                $btn.attr('aria-expanded', 'true');
                mgScrollToSection($u);
            } else {
                $u.removeClass('is-open');
                $host.stop(true, true).slideUp(250);
                $btn.attr('aria-expanded', 'false');
            }
        });

        $(document).on('click', '.mg-accordion-header', function(e) {
            e.preventDefault();
            var $accordion = $(this).closest('.mg-accordion');
            var $body = $accordion.find('.mg-accordion-body');
            var $card = $accordion.closest('.mg-card');

            if ($body.is(':animated')) { return; }

            if ($accordion.hasClass('is-open')) {
                $accordion.removeClass('is-open');
                $body.stop(true, true).slideUp(250);
            } else {
                $card.find('.mg-accordion.is-open').not($accordion).each(function() {
                    $(this).removeClass('is-open');
                    $(this).children('.mg-accordion-body').stop(true, true).slideUp(250);
                });
                var $bgU = $card.find('#mg-bg-unified');
                if ($bgU.length && $bgU.hasClass('is-open')) {
                    $bgU.removeClass('is-open');
                    $bgU.find('#mg-bg-host').stop(true, true).slideUp(250);
                    $bgU.find('.mg-bg-toggle').attr('aria-expanded', 'false');
                }
                $accordion.addClass('is-open');
                $body.stop(true, true).slideDown(250);
                mgScrollToSection($accordion);
            }
        });

        $(document).on('change', '.mg-mode-option input[type="radio"]', function() {
            $('.mg-mode-option').removeClass('is-active');
            $(this).closest('.mg-mode-option').addClass('is-active');
            var isCS   = $(this).val() === 'coming_soon';
            var isOn   = $('#mg-toggle').is(':checked');
            var $badge = $('#mg-status-badge');
            if (isOn) {
                $badge.text(isCS ? (mgAdmin.i18n.coming_soon_label || 'COMING SOON') : 'ON')
                      .removeClass('coming-soon');
                if (isCS) { $badge.addClass('coming-soon'); }
            }
            $('#mg-mode-label').text(isCS ? (mgAdmin.i18n.coming_soon_mode || 'COMING SOON MODE') : (mgAdmin.i18n.maintenance_mode || 'MAINTENANCE MODE'));
            mgAutoSave();
        });

        $(document).on('click', '.mg-btn-expand-all', function(e) {
            e.preventDefault();
            var $card = $(this).closest('.mg-card');
            $card.find('.mg-accordion').each(function() {
                if (!$(this).hasClass('is-open')) {
                    $(this).addClass('is-open');
                    $(this).find('.mg-accordion-body').slideDown(250);
                }
            });
            var $bgU = $card.find('#mg-bg-unified');
            if ($bgU.length && !$bgU.hasClass('is-open')) { $bgU.addClass('is-open'); $bgU.find('#mg-bg-host').slideDown(250); }
        });
        
        $(document).on('click', '.mg-btn-collapse-all', function(e) {
            e.preventDefault();
            var $card = $(this).closest('.mg-card');
            $card.find('.mg-accordion').each(function() {
                if ($(this).hasClass('is-open')) {
                    $(this).removeClass('is-open');
                    $(this).find('.mg-accordion-body').slideUp(250);
                }
            });
            var $bgU = $card.find('#mg-bg-unified');
            if ($bgU.length && $bgU.hasClass('is-open')) { $bgU.removeClass('is-open'); $bgU.find('#mg-bg-host').slideUp(250); }
        });
        

        var badgeMapping = {
            'mg-notification-enabled': 'notification_enabled',
            'mg-turnstile-enabled': 'turnstile_enabled',
            'mg-countdown-enabled': 'countdown_enabled',
            'mg-rgpd-mode': 'rgpd_mode',
            'mg-animation-enabled': 'animation_enabled',
            'mg-lottie-enabled': 'lottie_enabled',
            'mg-video-bg-enabled': 'video_bg_enabled',
            'mg-parallax-enabled': 'parallax_enabled',
            'mg-stats-enabled': 'stats_enabled',
            'mg-sidebar-enabled': 'sidebar_enabled',
            'mg-schedule-enabled': 'schedule_enabled',
            'mg-seo-503': 'seo_503_enabled',
            'mg-show-powered-by': 'show_powered_by'
        };

        function updateAccordionBadge($checkbox) {
            var $accordion = $checkbox.closest('.mg-accordion');
            var $badge = $accordion.find('.mg-accordion-badge');
            var isChecked = $checkbox.is(':checked');
            var isPro = $accordion.hasClass('mg-pro-feature') || $badge.hasClass('mg-badge-pro');
            
            if (isChecked) {
                $badge.removeClass('mg-badge-default mg-badge-pro').addClass('mg-badge-ok').html('✓');
            } else {
                if (isPro || $badge.data('pro')) {
                    $badge.removeClass('mg-badge-ok mg-badge-default').addClass('mg-badge-pro').html('PRO');
                } else {
                    $badge.removeClass('mg-badge-ok mg-badge-pro').addClass('mg-badge-default').html('○');
                }
            }
        }

        $(document).on('change', '.mg-accordion input[type="checkbox"]', function() {
            updateAccordionBadge($(this));
        });

        $(document).on('click', '#mg-upload-logo, #mg-remove-logo', function() {
            setTimeout(function() {
                var $logoAccordion = $('#mg-logo-url').closest('.mg-accordion');
                var $badge = $logoAccordion.find('.mg-accordion-badge');
                var hasLogo = $('#mg-logo-url').val() !== '';
                
                if (hasLogo) {
                    $badge.removeClass('mg-badge-default').addClass('mg-badge-ok').html('✓');
                } else {
                    $badge.removeClass('mg-badge-ok').addClass('mg-badge-default').html('○');
                }
            }, 500);
        });


        $('#mg-remote-enabled').on('change', function() {
            $('#mg-remote-options').toggle(this.checked);
        });

        $('#mg-remote-pin-enabled').on('change', function() {
            $('#mg-remote-pin-section').toggle(this.checked);
        });

        $('#mg-remote-ip-enabled').on('change', function() {
            $('#mg-remote-ip-section').toggle(this.checked);
        });

        // Mise à jour visuelle des pastilles d'étape
        function updateStepBadge(stepId, done) {
            var $badge = $('#' + stepId);
            var $bar = $('#' + stepId + '-bar');
            if (!$badge.length) return;
            if (done) {
                $badge.css('background', '#4CAF50').text('✓');
                if ($bar.length) $bar.css('border-left-color', '#4CAF50');
            }
        }

        // Fonction réutilisable pour sauvegarder la config remote
        function saveRemoteConfig(callback) {
            return $.post(mgAdmin.ajaxurl, {
                action: 'mg_remote_save_config',
                nonce: mgAdmin.nonce,
                remote_enabled: $('#mg-remote-enabled').is(':checked') ? 'true' : 'false',
                pin_enabled: $('#mg-remote-pin-enabled').is(':checked') ? 'true' : 'false',
                remote_pin: $('#mg-remote-pin').val(),
                ip_whitelist_enabled: $('#mg-remote-ip-enabled').is(':checked') ? 'true' : 'false',
                ip_whitelist: $('#mg-remote-ip-whitelist').val()
            }, function(resp) {
                if (resp.success) {
                    $('#mg-remote-pin').val('');
                    if (callback) callback(true, resp.data);
                } else {
                    showNotice(resp.data.message || mgAdmin.i18n.error_generic, 'error');
                    if (callback) callback(false);
                }
            }).fail(function() {
                showNotice(mgAdmin.i18n.connection_error, 'error');
                if (callback) callback(false);
            });
        }

        $('#mg-remote-save-config').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true).text(mgAdmin.i18n.saving);

            saveRemoteConfig(function(ok, data) {
                $btn.prop('disabled', false).text(mgAdmin.i18n.save);
                if (ok) {
                    showNotice(mgAdmin.i18n.saved || 'Paramètres sauvegardés', 'success');
                    // Étape 1 : vert si PIN en DB, orange si IP seul, bleu si rien
                    var $badge = $('#mg-remote-step1');
                    var $bar = $('#mg-remote-step1-bar');
                    if (data && data.has_pin) {
                        $badge.css('background', '#4CAF50').text('✓');
                        if ($bar.length) $bar.css('border-left-color', '#4CAF50');
                    } else if (data && data.ip_enabled) {
                        $badge.css('background', '#e67e22').text('!');
                        if ($bar.length) $bar.css('border-left-color', '#e67e22');
                    } else {
                        $badge.css('background', '#667eea').text('1');
                        if ($bar.length) $bar.css('border-left-color', '#667eea');
                    }
                }
            });
        });

        var remoteGeneratedToken = '';
        var remoteGeneratedUrl = '';

        $('#mg-remote-generate-token').on('click', function() {
            if (!confirm(mgAdmin.i18n.confirm_regenerate_token || 'Generating a new token will invalidate the old one. Continue?')) return;

            var $btn = $(this);
            $btn.prop('disabled', true).text('⏳ Sauvegarde...');

            // Auto-save config AVANT de générer le token
            saveRemoteConfig(function(ok) {
                if (!ok) {
                    $btn.prop('disabled', false).text(mgAdmin.i18n.regenerate_token || '🔑 Régénérer le jeton');
                    return;
                }
                $btn.text('⏳ Génération...');

                $.post(mgAdmin.ajaxurl, {
                    action: 'mg_remote_generate_token',
                    nonce: mgAdmin.nonce,
                    expires_in: $('#mg-remote-token-expires').val()
                }, function(resp) {
                    $btn.prop('disabled', false).text(mgAdmin.i18n.regenerate_token || '🔑 Régénérer le jeton');
                    if (resp.success) {
                        remoteGeneratedToken = resp.data.token;
                        remoteGeneratedUrl = resp.data.url;
                        $('#mg-remote-created-url').val(resp.data.url);
                        
                        $('#mg-remote-token-modal').fadeIn(200);
                    } else {
                        showNotice(resp.data.message || 'Erreur', 'error');
                    }
                }).fail(function() {
                    $btn.prop('disabled', false).text(mgAdmin.i18n.regenerate_token || '🔑 Régénérer le jeton');
                    showNotice('Erreur de connexion', 'error');
                });
            });
        });

        $('#mg-remote-copy-url').on('click', function() {
            var $input = $('#mg-remote-created-url');
            $input.select();
            document.execCommand('copy');
            showNotice(mgAdmin.i18n.copied || 'Copié !', 'success');
        });

        $('#mg-remote-modal-close, #mg-remote-token-modal .mg-modal-overlay').on('click', function() {
            $('#mg-remote-token-modal').fadeOut(200);
        });
        $('#mg-remote-modal-done').on('click', function() {
            // Reload en restant sur l'onglet Accès
            localStorage.setItem('mg_active_tab', 'access');
            window.location.reload();
        });

        var tokenModal = document.getElementById('mg-remote-token-modal');
        if (tokenModal) {
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(m) {
                    if (m.attributeName === 'style' && tokenModal.style.display !== 'none') {
                        var src = document.getElementById('mg-remote-pin-enabled');
                        var dst = document.getElementById('mg-remote-include-pin');
                        if (src && dst) {
                            dst.checked = src.checked;
                        }
                    }
                });
            });
            observer.observe(tokenModal, { attributes: true, attributeFilter: ['style'] });
        }

        // Envoi direct email (bouton sur la page, pas dans la modale)
        $('#mg-remote-send-email-direct-btn').on('click', function() {
            var email = $('#mg-remote-email-direct').val();
            var includePin = $('#mg-remote-include-pin-direct').is(':checked');
            var $btn = $(this);
            var $status = $('#mg-remote-email-direct-status');

            if (!email || email.indexOf('@') < 0) {
                $status.text('❌ Adresse email invalide').css('color', '#e74c3c').show();
                return;
            }

            $btn.prop('disabled', true).text(mgAdmin.i18n.verifying || 'Envoi...');

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_remote_send_email',
                nonce: mgAdmin.nonce,
                email: email,
                include_pin: includePin ? 'true' : 'false'
            }, function(resp) {
                $btn.prop('disabled', false).text(mgAdmin.i18n.send || 'Envoyer');
                if (resp.success) {
                    $status.text('✅ ' + resp.data.message).css('color', '#4CAF50').show();
                    updateStepBadge('mg-remote-step3', true);
                } else {
                    $status.text('❌ ' + (resp.data.message || 'Erreur')).css('color', '#e74c3c').show();
                }
            }).fail(function() {
                $btn.prop('disabled', false).text(mgAdmin.i18n.send || 'Envoyer');
                $status.text('❌ ' + mgAdmin.i18n.connection_error).css('color', '#e74c3c').show();
            });
        });

        $('#mg-remote-load-logs').on('click', function() {
            var $container = $('#mg-remote-logs');
            $container.html('<em style="color:#999;">⏳ ...</em>');

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_remote_get_logs',
                nonce: mgAdmin.nonce
            }, function(resp) {
                if (resp.success && resp.data.logs.length > 0) {
                    var html = '';
                    resp.data.logs.forEach(function(log) {
                        var color = '#666';
                        if (log.action.indexOf('toggle_enabled') > -1) color = '#e67e22';
                        if (log.action.indexOf('toggle_disabled') > -1) color = '#4CAF50';
                        if (log.action.indexOf('invalid') > -1 || log.action.indexOf('blocked') > -1) color = '#e74c3c';
                        if (log.action.indexOf('verified') > -1) color = '#3498db';
                        html += '<div style="padding:4px 0;border-bottom:1px solid #eee;color:' + color + ';">';
                        html += '<strong>' + log.time + '</strong> — ' + log.action;
                        if (log.details) html += ' — ' + log.details;
                        html += ' <span style="color:#aaa;">(' + log.ip + ')</span>';
                        html += '</div>';
                    });
                    $container.html(html);
                } else {
                    $container.html('<em style="color:#999;">Aucun log</em>');
                }
            });
        });

        $('#mg-remote-clear-logs').on('click', function() {
            if (!confirm('Vider les logs remote ?')) return;
            $.post(mgAdmin.ajaxurl, {
                action: 'mg_remote_clear_logs',
                nonce: mgAdmin.nonce
            }, function(resp) {
                if (resp.success) {
                    $('#mg-remote-logs').html('<em style="color:#999;">' + (mgAdmin.i18n.logs_cleared || 'Logs cleared') + '</em>');
                    showNotice(resp.data.message, 'success');
                }
            });
        });

        $('#mg-remote-reset-ratelimit').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            $btn.prop('disabled', true).html('⏳ ...');
            $.post(mgAdmin.ajaxurl, {
                action: 'mg_remote_reset_ratelimit',
                nonce: mgAdmin.nonce
            }, function(resp) {
                $btn.prop('disabled', false).html(originalText);
                if (resp.success) {
                    showNotice('✅ ' + resp.data.message, 'success');
                    $btn.html(mgAdmin.i18n.unblocked || '✅ Unblocked!').addClass('mg-btn-success');
                    setTimeout(function() {
                        $btn.html(originalText).removeClass('mg-btn-success');
                    }, 3000);
                } else {
                    showNotice('❌ ' + (resp.data.message || 'Erreur'), 'error');
                }
            }).fail(function(xhr, status, error) {
                $btn.prop('disabled', false).html(originalText);
                showNotice('❌ Erreur réseau: ' + error, 'error');
            });
        });


        $(document).on('click', '.mg-monitoring-save-btn', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            $btn.prop('disabled', true).html('⏳ ...');

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_monitoring_save',
                nonce: mgAdmin.nonce,
                monitoring_enabled: $('#mg-monitoring-enabled').is(':checked') ? 'true' : 'false',
                monitoring_independent: $('#mg-monitoring-independent').is(':checked') ? 'true' : 'false',
                monitoring_interval: $('#mg-monitoring-interval').val(),
                monitoring_emails: $('#mg-monitoring-emails').val(),
                monitoring_email_cooldown: $('#mg-monitoring-cooldown').val(),
                monitoring_subject_down: $('#mg-monitoring-subject-down').val(),
                monitoring_body_down: $('#mg-monitoring-body-down').val(),
                monitoring_subject_up: $('#mg-monitoring-subject-up').val(),
                monitoring_body_up: $('#mg-monitoring-body-up').val()
            }, function(resp) {
                $btn.prop('disabled', false).html(originalText);
                if (resp.success) {
                    showNotice('✅ ' + resp.data.message, 'success');
                    $('.mg-monitoring-save-result').html('<span style="color:green;">✅</span>').fadeIn().delay(3000).fadeOut();
                } else {
                    showNotice('❌ ' + (resp.data.message || 'Error'), 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false).html(originalText);
                showNotice('❌ Network error', 'error');
            });
        });

        $('#mg-monitoring-test-check').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            $btn.prop('disabled', true).html('⏳ Checking...');

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_monitoring_test_check',
                nonce: mgAdmin.nonce
            }, function(resp) {
                $btn.prop('disabled', false).html(originalText);
                if (resp.success) {
                    var d = resp.data;
                    var icon = d.status === 'up' ? '✅' : '⚠️';
                    var msg = icon + ' Status: ' + d.status.toUpperCase() + ' (HTTP ' + d.code + ') — ' + d.time;
                    showNotice(msg, d.status === 'up' ? 'success' : 'error');
                    $('.mg-monitoring-save-result').html(msg).fadeIn().delay(5000).fadeOut();
                } else {
                    showNotice('❌ Check failed', 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false).html(originalText);
                showNotice('❌ Network error', 'error');
            });
        });

        $('#mg-monitoring-test-email').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            $btn.prop('disabled', true).html('⏳ Sending...');

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_monitoring_test_email',
                nonce: mgAdmin.nonce,
                monitoring_emails: $('#mg-monitoring-emails').val()
            }, function(resp) {
                $btn.prop('disabled', false).html(originalText);
                var msg = resp.success ? '✅ ' + resp.data.message : '❌ ' + (resp.data.message || 'Error');
                showNotice(msg, resp.success ? 'success' : 'error');
                $('#mg-monitoring-test-email-result').html(msg).fadeIn().delay(5000).fadeOut();
            }).fail(function() {
                $btn.prop('disabled', false).html(originalText);
                showNotice('❌ Network error', 'error');
            });
        });

        $('#mg-monitoring-clear-events').on('click', function() {
            if (!confirm(mgAdmin.i18n.confirm_clear_monitoring || 'Do you really want to clear the monitoring history?')) return;

            var $btn = $(this);
            $btn.prop('disabled', true);

            $.post(mgAdmin.ajaxurl, {
                action: 'mg_monitoring_clear_events',
                nonce: mgAdmin.nonce
            }, function(resp) {
                $btn.prop('disabled', false);
                if (resp.success) {
                    showNotice('✅ ' + resp.data.message, 'success');
                    $('#mg-monitoring-events-table tbody').html('<tr><td colspan="4" style="text-align:center;padding:20px;">📊 ' + (mgAdmin.i18n.no_monitoring_events || 'No events recorded yet.') + '</td></tr>');
                } else {
                    showNotice('❌ ' + (resp.data.message || 'Error'), 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false);
                showNotice('❌ Network error', 'error');
            });
        });

    });
    
});

jQuery(document).ready(function($) {
    var $dur = $('#mg-visitor-duration');
    if (!$dur.length) { return; }
    function mgToggleVadCustom() {
        $('.mg-vad-custom').toggle($dur.val() === 'custom');
    }
    $dur.on('change', mgToggleVadCustom);
    mgToggleVadCustom();
});

/* =========================================================
 * v2.9.80 — Arrière-plan unifié + Recherche réglages
 * ========================================================= */
jQuery(document).ready(function($) {
    'use strict';

    /* ---- Arrière-plan unifié (sélecteur de type) ---- */
    var $host = $('#mg-bg-host');
    if ($host.length) {
        var bgOrder = ['preset', 'gradient', 'image', 'video', 'animation'];
        // Regrouper les panneaux background sous le sélecteur, dans l'ordre.
        $.each(bgOrder, function(i, type) {
            $('.mg-bg-panel[data-bg-type="' + type + '"]').appendTo($host);
        });

        function mgBgShow(type) {
            if (!$('.mg-bg-seg[data-bg-type="' + type + '"]').length) { type = 'gradient'; }
            $('.mg-bg-seg').removeClass('is-active');
            $('.mg-bg-seg[data-bg-type="' + type + '"]').addClass('is-active');
            $host.find('.mg-bg-panel').hide();
            var $sel = $host.find('.mg-bg-panel[data-bg-type="' + type + '"]').show();
            $sel.addClass('is-open').find('.mg-accordion-body').show();
            localStorage.setItem('mg_bg_type', type);
        }
        window.mgBgRestore = function() {
            mgBgShow(localStorage.getItem('mg_bg_type') || 'gradient');
        };

        $(document).on('click', '.mg-bg-seg', function() {
            mgBgShow($(this).attr('data-bg-type'));
        });

        window.mgBgRestore();
    }

    /* ---- Recherche réglages (filtre transversal) ---- */
    var $search = $('#mg-settings-search');
    if ($search.length) {
        var $clear = $('#mg-settings-search-clear');
        var $count = $('#mg-search-count');
        var $items = $('.mg-content .mg-form-group, .mg-content .mg-accordion');

        function mgNorm(s) {
            return (s || '').toString().toLowerCase()
                .normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        }

        function mgSearchReset() {
            $items.removeClass('mg-search-hit').css('display', '');
            $('.mg-tab-content').css('display', '');
            $clear.prop('hidden', true);
            $count.text('');
            $('body').removeClass('mg-searching');
            // resync de l'état déplié/replié des accordéons
            $('.mg-accordion').each(function() {
                var $a = $(this);
                $a.children('.mg-accordion-body').toggle($a.hasClass('is-open'));
            });
            var saved = localStorage.getItem('mg_active_tab');
            var $btn = saved ? $('.mg-tab[data-tab="' + saved + '"]') : $();
            if (!$btn.length) { $btn = $('.mg-tab').first(); }
            if (window.mgShowTab) { window.mgShowTab($btn); }
            if (window.mgBgRestore) { window.mgBgRestore(); }
        }

        function mgSearch(raw) {
            var q = mgNorm(raw.trim());
            if (!q) { mgSearchReset(); return; }
            $('body').addClass('mg-searching');
            $('.mg-tab').removeClass('active');
            $('.mg-tab-content').show();
            $items.each(function() {
                var $it = $(this);
                var match = mgNorm($it.text()).indexOf(q) !== -1;
                $it.toggleClass('mg-search-hit', match);
                $it.toggle(match);
                if (match) {
                    $it.closest('.mg-accordion').addClass('is-open')
                       .find('.mg-accordion-body').show();
                }
            });
            $('.mg-tab-content').each(function() {
                $(this).toggle($(this).find('.mg-search-hit').length > 0);
            });
            // visibles (évite de compter un accordéon + ses champs internes en double,
            // et les panneaux d'arrière-plan masqués).
            var hits = $items.filter('.mg-search-hit:visible').filter(function() {
                return $(this).parents('.mg-search-hit').length === 0;
            }).length;
            $clear.prop('hidden', false);
            $count.text(hits ? String(hits) : ($count.attr('data-empty') || '0'));
        }

        var mgT;
        $search.on('input', function() {
            var v = this.value;
            clearTimeout(mgT);
            mgT = setTimeout(function() { mgSearch(v); }, 120);
        });
        $clear.on('click', function() {
            $search.val(''); mgSearchReset(); $search.focus();
        });
        $search.on('keydown', function(e) {
            if (e.key === 'Escape') { $search.val(''); mgSearchReset(); }
        });
    }
});

/* ============================================================
   DIAGNOSTIC (v2.9.116) — scan, rendu, test courriel, bandeau
   ============================================================ */
jQuery(document).ready(function($) {
    'use strict';

    var $runBtn = $('#mg-diag-run');
    if (!$runBtn.length) { return; } // Pas sur la page MG

    var mgDiagI18n = {
        running: $runBtn.attr('data-running-label') || '⏳ ...',
        runLabel: $runBtn.html()
    };

    // ---- Rendu d'un item (mêmes classes que le rendu serveur) ----
    function mgDiagRenderItem(id, check) {
        var $item = $('<div/>', { 'class': 'mg-diag-item mg-diag-' + check.status, 'data-check': id });
        $item.append($('<span/>', { 'class': 'mg-diag-status', 'aria-hidden': 'true' }));
        var $body = $('<div/>', { 'class': 'mg-diag-body' });
        var $label = $('<strong/>', { 'class': 'mg-diag-label', text: check.label });
        if (check.tooltip) {
            $label.append(' ').append($('<span/>', { 'class': 'mg-info-tooltip', 'data-tooltip': check.tooltip, text: '?' }));
        }
        $body.append($label);
        $body.append($('<p/>', { 'class': 'mg-diag-detail', text: check.detail }));
        if (check.fix) {
            $body.append($('<p/>', { 'class': 'mg-diag-fix', text: '💡 ' + check.fix }));
        }
        $item.append($body);
        return $item;
    }

    // ---- Lancer l'analyse ----
    $runBtn.on('click', function() {
        $runBtn.prop('disabled', true).text(mgDiagI18n.running);

        $.post(mgAdmin.ajaxurl, {
            action: 'mg_run_diagnostic',
            nonce: mgAdmin.nonce
        }, function(response) {
            $runBtn.prop('disabled', false).html(mgDiagI18n.runLabel);
            if (!response || !response.success) {
                var msg = (response && response.data && response.data.message) ? response.data.message : 'Error';
                $('#mg-diag-last').text(msg);
                return;
            }
            var results = response.data.results;
            var $container = $('#mg-diag-results').empty();
            $.each(results.checks, function(id, check) {
                $container.append(mgDiagRenderItem(id, check));
            });
            $('#mg-diag-last').text(response.data.date_human ? response.data.date_human : '');
            // Recharge pour rafraîchir pastille onglet + badges sections + bandeau (rendu PHP).
            setTimeout(function() { location.reload(); }, 1500);
        }).fail(function() {
            $runBtn.prop('disabled', false).html(mgDiagI18n.runLabel);
        });
    });

    // ---- Test courriel ----
    $('#mg-diag-email-send').on('click', function() {
        var $btn = $(this);
        var $result = $('#mg-diag-email-result');
        $btn.prop('disabled', true);
        $result.removeClass('mg-diag-email-ok mg-diag-email-err').text('...');

        $.post(mgAdmin.ajaxurl, {
            action: 'mg_diag_send_test_email',
            nonce: mgAdmin.nonce,
            email: $('#mg-diag-email-to').val()
        }, function(response) {
            $btn.prop('disabled', false);
            if (response && response.success) {
                $result.addClass('mg-diag-email-ok').text(response.data.message);
            } else {
                var msg = (response && response.data && response.data.message) ? response.data.message : 'Error';
                $result.addClass('mg-diag-email-err').text(msg);
            }
        }).fail(function() {
            $btn.prop('disabled', false);
            $result.addClass('mg-diag-email-err').text('Error');
        });
    });

    // ---- Badge section / bandeau → naviguer vers l'onglet Diagnostic ----
    function mgDiagGoto(checkId) {
        $('.mg-tab[data-tab="diagnostic"]').trigger('click');
        if (checkId) {
            var $target = $('.mg-diag-item[data-check="' + checkId + '"]');
            if ($target.length) {
                $target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
                $target.addClass('mg-diag-highlight');
                setTimeout(function() { $target.removeClass('mg-diag-highlight'); }, 2500);
            }
        }
    }

    $(document).on('click', '.mg-diag-badge', function(e) {
        e.preventDefault();
        e.stopPropagation(); // Ne pas ouvrir/fermer l'accordéon parent.
        mgDiagGoto($(this).attr('data-diag-goto'));
    });

    $('#mg-diag-banner-view').on('click', function() {
        mgDiagGoto($('#mg-diag-banner').attr('data-check'));
    });

    // ---- Fermer le bandeau (persisté 24 h côté serveur) ----
    $('#mg-diag-banner-close').on('click', function() {
        var checkId = $('#mg-diag-banner').attr('data-check');
        $('#mg-diag-banner').slideUp(200);
        $.post(mgAdmin.ajaxurl, {
            action: 'mg_diag_dismiss_banner',
            nonce: mgAdmin.nonce,
            check_id: checkId
        });
    });
});

jQuery(function($) {
    var $badge = $('#mg-update-badge'), $panel = $('#mg-update-panel');
    if (!$badge.length) { return; }
    function togglePanel(show) {
        $panel.toggle(show);
        $badge.attr('aria-expanded', show ? 'true' : 'false');
    }
    $badge.on('click keydown', function(e) {
        if (e.type === 'keydown' && e.key !== 'Enter' && e.key !== ' ') { return; }
        e.preventDefault();
        togglePanel($panel.is(':hidden'));
    });
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#mg-update-panel, #mg-update-badge').length) { togglePanel(false); }
    });
    $(document).on('keydown', function(e) { if (e.key === 'Escape') { togglePanel(false); } });
    $('#mg-update-later').on('click', function() {
        $.post(ajaxurl, {
            action: 'mg_dismiss_update',
            nonce: mgAdmin.nonce,
            version: $panel.data('version')
        }, function() {
            togglePanel(false);
            $badge.removeClass('mg-version-update').text('v' + (mgAdmin.version || ''));
            location.reload();
        });
    });
});
