        function bmToggleBreakpointMode(val) {
            var row = document.getElementById('bm-bp-manual-row');
            if (row) row.style.display = val === 'manual' ? '' : 'none';
            // Update radio card styles
            document.querySelectorAll('[name="menux_style[mobile_breakpoint_mode]"]').forEach(function(r) {
                var lbl = r.closest('label');
                if (!lbl) return;
                lbl.style.borderColor = r.checked ? '#667eea' : '#e5e7eb';
                lbl.style.background  = r.checked ? '#f0f4ff' : '#fff';
            });
        }
        function bmToggleOpenStyle(val) {
            document.getElementById('bm-mob-overlay-opts').style.display   = val !== 'dropdown' ? '' : 'none';
            document.getElementById('bm-mob-fullscreen-opts').style.display = val === 'fullscreen' ? '' : 'none';
            document.getElementById('bm-mob-drawer-opts').style.display     = (val === 'drawer-left' || val === 'drawer-right') ? '' : 'none';
            document.getElementById('bm-mob-dropdown-opts').style.display   = val === 'dropdown' ? '' : 'none';
            // Update radio card styles
            document.querySelectorAll('[name="menux_style[mobile_open_style]"]').forEach(function(r) {
                var lbl = r.closest('label');
                if (!lbl) return;
                lbl.style.borderColor = r.checked ? '#667eea' : '#e5e7eb';
                lbl.style.background  = r.checked ? '#f0f4ff' : '#fff';
            });
        }
    function menux_switchTab(activeId) {
        document.querySelectorAll('.bm-tab-pane').forEach(function(p){ p.style.display='none'; });
        document.querySelectorAll('.bm-tab-btn').forEach(function(b){
            var isActive = b.getAttribute('data-tab') === activeId;
            // Pulisce eventuali stili inline residui e usa la classe .active (vedi CSS)
            b.style.color         = '';
            b.style.borderColor   = '';
            b.style.background    = '';
            if (isActive) b.classList.add('active');
            else b.classList.remove('active');
        });
        var pane = document.getElementById(activeId);
        if (pane) pane.style.display = 'block';
    }
    // Initialize the style-panel tab. If a section is being restored after
    // a save (menuxGoSection already ran and set _menuxActiveSection), skip
    // the switchTab so the restored tab is not overwritten by 'themes'.
    document.addEventListener('DOMContentLoaded', function() {
        var styleSections = ['themes', 'colors', 'typo', 'layout', 'mobile'];
        var restored = window._menuxActiveSection || '';
        if (!restored || styleSections.indexOf(restored) === -1) {
            menux_switchTab('bm-tab-themes');
        }
        buildInlineThemeGrid();
        buildMobilePresetGrid();
        buildMobilePhonePreview();
    });

    /* ════════════════════════════════════════════════════════════════
       WCAG CONTRAST ENFORCEMENT (Accessibility → enforce_contrast)
       Validates the main text/background color pairs when the form is
       saved. Modes: false (off) | warn (confirm) | block (prevent save).
    ════════════════════════════════════════════════════════════════ */

    function menux_hexToRgb(hex) {
        hex = (hex || '').replace('#', '').trim();
        if (hex.length === 3) hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        if (!/^[0-9a-fA-F]{6}$/.test(hex)) return null;
        return [parseInt(hex.substr(0, 2), 16), parseInt(hex.substr(2, 2), 16), parseInt(hex.substr(4, 2), 16)];
    }
    function menux_relLuminance(rgb) {
        var c = rgb.map(function(v) {
            v /= 255;
            return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
        });
        return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
    }
    function menux_contrastRatio(fg, bg) {
        var a = menux_hexToRgb(fg), b = menux_hexToRgb(bg);
        if (!a || !b) return null;
        var l1 = menux_relLuminance(a), l2 = menux_relLuminance(b);
        return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
    }
    // Active color value: '' when the enable checkbox is unticked or the field is absent.
    function menux_ctStyleColor(key) {
        var use = document.querySelector('[name="menux_style_use[' + key + ']"]');
        if (use && !use.checked) return '';
        var inp = document.querySelector('[name="menux_style[' + key + ']"]');
        return inp && inp.value ? inp.value : '';
    }
    function menux_ctStyleField(key) {
        var inp = document.querySelector('[name="menux_style[' + key + ']"]');
        return inp && inp.value ? inp.value : '';
    }

    // Returns a list of human-readable failures, empty when everything passes.
    // Pairs whose background is unknown (theme default) or a gradient are
    // skipped: a reliable ratio can't be computed for them.
    function menux_contrastIssues() {
        var MIN = 4.5; // WCAG 1.4.3 AA, normal text
        var containerGrad = menux_ctStyleField('container_bg_gradient');
        var containerBg   = containerGrad ? '' : menux_ctStyleColor('container_bg');

        // [label, fg key, explicit bg key, gradient key that voids the bg, fallback bg]
        var pairs = [
            ['Menu links',      'link_color',         '',               '',                        containerBg],
            ['Link hover',      'link_hover_color',   'link_hover_bg',  'link_hover_bg_gradient',  containerBg],
            ['Active link',     'link_active_color',  'link_active_bg', 'link_active_bg_gradient', containerBg],
            ['Submenu links',   'submenu_link_color', 'submenu_bg',     '',                        '#ffffff'],
            ['Last item',       'last_item_color',    'last_item_bg',   '',                        containerBg],
            ['Mobile links',    'mobile_link_color',  '',               '',                        containerBg]
        ];

        var issues = [];
        pairs.forEach(function(p) {
            var fg = menux_ctStyleColor(p[1]);
            if (!fg) return;
            if (p[3] && menux_ctStyleField(p[3])) return;
            var bg = p[2] ? menux_ctStyleColor(p[2]) : '';
            if (!bg) bg = p[4];
            if (!bg) return;
            var ratio = menux_contrastRatio(fg, bg);
            if (ratio !== null && ratio < MIN) {
                issues.push('• ' + p[0] + ': ' + fg + ' on ' + bg + ' → ' + (Math.round(ratio * 100) / 100) + ':1 (min ' + MIN + ':1)');
            }
        });
        return issues;
    }

    document.addEventListener('DOMContentLoaded', function() {
        var form = document.getElementById('menux-form');
        if (!form) return;
        form.addEventListener('submit', function(e) {
            var modeSel = document.querySelector('[name="menux_accessibility[enforce_contrast]"]');
            var mode = modeSel ? modeSel.value : 'false';
            if (mode !== 'warn' && mode !== 'block') return;
            var issues = menux_contrastIssues();
            if (!issues.length) return;
            var msg = 'Contrast check (WCAG 1.4.3 — minimum 4.5:1 for text):\n\n' + issues.join('\n');
            if (mode === 'block') {
                e.preventDefault();
                alert('✋ Save blocked — fix these color combinations, or set "Contrast enforcement" to Warn or Disabled in the Accessibility panel.\n\n' + msg);
            } else if (!confirm('⚠ ' + msg + '\n\nSave anyway?')) {
                e.preventDefault();
            }
        });
    });

    function menux_openLogoUploader() {
        if (typeof wp === 'undefined' || !wp.media) { alert('Media uploader non disponibile.'); return; }
        var frame = wp.media({ title:'Choose a Logo', button:{text:'Use this image'}, multiple:false });
        frame.on('select', function() {
            var att = frame.state().get('selection').first().toJSON();
            var inp = document.getElementById('bm-logo-url-input');
            if (inp) { inp.value = att.url; menux_liveStylePreview(); }
        });
        frame.open();
    }

    // ================================================================
    // ICON PICKER
    // ================================================================
    var mxIconPicker = (function() {
        var currentInput = null;
        var searchTimeout = null;

        // Lista icone Font Awesome 6 Free — raggruppate per categoria
        var iconGroups = {
            '🏠 Navigazione': ['fa-solid fa-house','fa-solid fa-house-chimney','fa-solid fa-bars','fa-solid fa-xmark','fa-solid fa-arrow-left','fa-solid fa-arrow-right','fa-solid fa-arrow-up','fa-solid fa-arrow-down','fa-solid fa-chevron-left','fa-solid fa-chevron-right','fa-solid fa-chevron-up','fa-solid fa-chevron-down','fa-solid fa-angles-left','fa-solid fa-angles-right','fa-solid fa-circle-arrow-left','fa-solid fa-circle-arrow-right','fa-solid fa-link','fa-solid fa-external-link','fa-solid fa-up-right-from-square','fa-solid fa-sitemap','fa-solid fa-map'],
            '👤 Utente': ['fa-solid fa-user','fa-solid fa-user-tie','fa-regular fa-user','fa-solid fa-users','fa-solid fa-user-group','fa-solid fa-user-check','fa-solid fa-user-plus','fa-solid fa-user-minus','fa-solid fa-user-xmark','fa-solid fa-address-card','fa-regular fa-address-card','fa-solid fa-id-card','fa-solid fa-person','fa-solid fa-right-to-bracket','fa-solid fa-right-from-bracket','fa-solid fa-lock','fa-solid fa-unlock','fa-solid fa-key','fa-solid fa-shield-halved','fa-solid fa-circle-user'],
            '📞 Comunicazione': ['fa-solid fa-phone','fa-solid fa-envelope','fa-regular fa-envelope','fa-solid fa-comments','fa-regular fa-comments','fa-solid fa-comment','fa-regular fa-comment','fa-solid fa-bell','fa-regular fa-bell','fa-solid fa-at','fa-solid fa-paper-plane','fa-regular fa-paper-plane','fa-solid fa-inbox','fa-solid fa-share-nodes','fa-solid fa-rss','fa-solid fa-headset','fa-solid fa-mobile-screen','fa-solid fa-mobile'],
            '💼 Business': ['fa-solid fa-briefcase','fa-solid fa-building','fa-regular fa-building','fa-solid fa-chart-bar','fa-regular fa-chart-bar','fa-solid fa-chart-line','fa-solid fa-chart-pie','fa-solid fa-handshake','fa-regular fa-handshake','fa-solid fa-suitcase','fa-solid fa-file-contract','fa-solid fa-clipboard-list','fa-solid fa-calendar-days','fa-regular fa-calendar-days','fa-solid fa-clock','fa-regular fa-clock','fa-solid fa-dollar-sign','fa-solid fa-euro-sign','fa-solid fa-receipt','fa-solid fa-cash-register'],
            '🛒 E-commerce': ['fa-solid fa-cart-shopping','fa-solid fa-cart-plus','fa-solid fa-bag-shopping','fa-solid fa-store','fa-solid fa-shop','fa-solid fa-tag','fa-solid fa-tags','fa-solid fa-gift','fa-solid fa-percent','fa-solid fa-ticket','fa-solid fa-credit-card','fa-regular fa-credit-card','fa-solid fa-wallet','fa-solid fa-basket-shopping','fa-solid fa-box','fa-solid fa-boxes-stacked','fa-solid fa-truck','fa-solid fa-truck-fast','fa-solid fa-heart','fa-regular fa-heart'],
            '⚙️ Settings': ['fa-solid fa-gear','fa-solid fa-gears','fa-solid fa-wrench','fa-solid fa-screwdriver-wrench','fa-solid fa-sliders','fa-solid fa-toggle-on','fa-solid fa-toggle-off','fa-solid fa-power-off','fa-solid fa-circle-info','fa-solid fa-question','fa-solid fa-circle-question','fa-regular fa-circle-question','fa-solid fa-triangle-exclamation','fa-solid fa-circle-exclamation','fa-solid fa-ban','fa-solid fa-trash','fa-regular fa-trash-can','fa-solid fa-pen','fa-regular fa-pen-to-square','fa-solid fa-magnifying-glass'],
            '📄 Contenuto': ['fa-solid fa-file','fa-regular fa-file','fa-solid fa-file-lines','fa-regular fa-file-lines','fa-solid fa-book','fa-solid fa-book-open','fa-solid fa-newspaper','fa-regular fa-newspaper','fa-solid fa-image','fa-regular fa-image','fa-solid fa-images','fa-solid fa-camera','fa-solid fa-video','fa-solid fa-film','fa-solid fa-music','fa-solid fa-podcast','fa-solid fa-microphone','fa-solid fa-star','fa-regular fa-star','fa-solid fa-bookmark'],
            '🌐 Social': ['fa-brands fa-facebook','fa-brands fa-facebook-f','fa-brands fa-twitter','fa-brands fa-x-twitter','fa-brands fa-instagram','fa-brands fa-linkedin','fa-brands fa-linkedin-in','fa-brands fa-youtube','fa-brands fa-tiktok','fa-brands fa-whatsapp','fa-brands fa-telegram','fa-brands fa-github','fa-brands fa-gitlab','fa-brands fa-google','fa-brands fa-apple','fa-brands fa-android','fa-brands fa-wordpress','fa-brands fa-slack','fa-brands fa-discord','fa-brands fa-spotify'],
            '🎓 Informazione': ['fa-solid fa-graduation-cap','fa-solid fa-school','fa-solid fa-chalkboard-user','fa-solid fa-lightbulb','fa-regular fa-lightbulb','fa-solid fa-brain','fa-solid fa-flask','fa-solid fa-microscope','fa-solid fa-atom','fa-solid fa-globe','fa-solid fa-earth-europe','fa-solid fa-language','fa-solid fa-list','fa-solid fa-list-check','fa-solid fa-table-list','fa-solid fa-table','fa-solid fa-database','fa-solid fa-server','fa-solid fa-code','fa-solid fa-terminal'],
        };

        function buildModal() {
            var existing = document.getElementById('bm-icon-picker-modal');
            if (existing) return;

            var overlay = document.createElement('div');
            overlay.id = 'bm-icon-picker-modal';
            overlay.style.cssText = 'display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:1000010;align-items:center;justify-content:center;padding:16px;';

            var html = '<div style="background:#fff;border-radius:14px;box-shadow:0 24px 60px rgba(0,0,0,.3);width:min(760px,96vw);max-height:85vh;display:flex;flex-direction:column;overflow:hidden;font-family:-apple-system,sans-serif;">'
                // Header
                + '<div style="background:linear-gradient(135deg,#0f172a,#1e293b);padding:16px 20px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">'
                + '<div><div style="color:rgba(255,255,255,.6);font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:2px;">Font Awesome 6 Free</div>'
                + '<div style="color:#fff;font-size:16px;font-weight:700;">🎨 Select Icon</div></div>'
                + '<button onclick="mxIconPicker.close()" style="background:rgba(255,255,255,.15);border:none;color:#fff;width:30px;height:30px;border-radius:50%;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;">&times;</button>'
                + '</div>'
                // Search bar
                + '<div style="padding:12px 16px;background:#f8fafc;border-bottom:1px solid #e5e7eb;flex-shrink:0;display:flex;gap:8px;align-items:center;">'
                + '<div style="flex:1;position:relative;"><span style="position:absolute;left:10px;top:50%;transform:translateY(-50%);color:#9ca3af;">🔍</span>'
                + '<input type="text" id="bm-icon-search" placeholder="Search icon… (e.g. home, user, cart)" oninput="mxIconPicker.search(this.value)" style="width:100%;padding:8px 10px 8px 32px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;box-sizing:border-box;">'
                + '</div>'
                + '<button type="button" onclick="mxIconPicker.clear()" style="background:#fff;border:1px solid #d1d5db;color:#555;padding:7px 14px;border-radius:6px;font-size:12px;cursor:pointer;white-space:nowrap;">Remove icon</button>'
                + '</div>'
                // Body
                + '<div id="bm-icon-body" style="overflow-y:auto;flex:1;padding:16px;"></div>'
                // Footer
                + '<div style="padding:10px 16px;border-top:1px solid #f0f0f0;background:#fafafa;display:flex;align-items:center;gap:12px;flex-shrink:0;border-radius:0 0 14px 14px;">'
                + '<div id="bm-icon-preview" style="display:flex;align-items:center;gap:8px;font-size:13px;color:#6b7280;">None icona selezionata</div>'
                + '<div style="margin-left:auto;display:flex;gap:8px;">'
                + '<button onclick="mxIconPicker.close()" style="background:#fff;border:1px solid #d1d5db;color:#374151;padding:7px 18px;border-radius:7px;font-size:13px;cursor:pointer;">Cancel</button>'
                + '<button id="bm-icon-apply-btn" onclick="mxIconPicker.apply()" disabled style="background:linear-gradient(135deg,#0f172a,#334155);border:none;color:#fff;padding:7px 20px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;opacity:.4;">✅ Use this icon</button>'
                + '</div></div>'
                + '</div>';

            overlay.innerHTML = html;
            document.body.appendChild(overlay);
            overlay.addEventListener('click', function(e){ if(e.target===overlay) mxIconPicker.close(); });

            mxIconPicker.renderAll();
        }

        function renderGroup(title, icons, container) {
            var div = document.createElement('div');
            div.style.cssText = 'margin-bottom:18px;';
            div.innerHTML = '<div style="font-size:11px;font-weight:700;color:#374151;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;padding-bottom:4px;border-bottom:1px solid #e5e7eb;">'+title+'</div>';
            var grid = document.createElement('div');
            grid.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(52px,1fr));gap:4px;';
            icons.forEach(function(ic) {
                var parts = ic.split(' ');
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.title = ic;
                btn.setAttribute('data-icon', ic);
                btn.style.cssText = 'background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;padding:8px 4px;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:3px;transition:all .1s;min-height:52px;';
                btn.innerHTML = '<i class="'+ic+'" style="font-size:18px;color:#374151;"></i><span style="font-size:8px;color:#9ca3af;text-align:center;word-break:break-all;line-height:1.2;">'+parts[parts.length-1].replace('fa-','')+'</span>';
                btn.onmouseenter = function(){ this.style.background='#e0e7ff'; this.style.borderColor='#667eea'; };
                btn.onmouseleave = function(){ if(mxIconPicker._selected!==ic){ this.style.background='#f9fafb'; this.style.borderColor='#e5e7eb'; } };
                btn.onclick = function(){ mxIconPicker.select(ic); };
                grid.appendChild(btn);
            });
            div.appendChild(grid);
            container.appendChild(div);
        }

        return {
            _selected: null,
            _target: null,

            open: function(inputEl) {
                buildModal();
                this._target = inputEl;
                this._selected = inputEl ? inputEl.value.trim() : null;
                var overlay = document.getElementById('bm-icon-picker-modal');
                overlay.style.display = 'flex';
                // Pre-seleziona se c'è già un'icona
                if (this._selected) {
                    this.updatePreview(this._selected);
                    var btn = document.getElementById('bm-icon-apply-btn');
                    if (btn) { btn.disabled=false; btn.style.opacity='1'; }
                    // Evidenzia icona corrente
                    setTimeout(function(){
                        var cur = document.querySelector('[data-icon="'+mxIconPicker._selected+'"]');
                        if (cur) { cur.style.background='#e0e7ff'; cur.style.borderColor='#667eea'; cur.scrollIntoView({block:'center'}); }
                    }, 100);
                }
                var searchEl = document.getElementById('bm-icon-search');
                if (searchEl) { searchEl.value=''; searchEl.focus(); }
            },

            close: function() {
                var o = document.getElementById('bm-icon-picker-modal');
                if (o) o.style.display='none';
                this._selected = null;
            },

            apply: function() {
                if (!this._selected || !this._target) { this.close(); return; }
                this._target.value = this._selected;
                // Preview <i> lives BEFORE the input (previousElementSibling).
                // Inserting it after the input would shift previousElementSibling
                // of the pick button away from the input on the second click.
                var previewEl = this._target.previousElementSibling;
                if (previewEl && previewEl.classList.contains('bm-icon-preview-el')) {
                    previewEl.className = 'bm-icon-preview-el ' + this._selected;
                } else {
                    var ic = document.createElement('i');
                    ic.className = 'bm-icon-preview-el ' + this._selected;
                    ic.style.cssText = 'font-size:16px;color:#374151;flex-shrink:0;';
                    this._target.parentNode.insertBefore(ic, this._target);
                }
                var ev = new Event('input', {bubbles:true});
                this._target.dispatchEvent(ev);
                this.close();
                menux_updatePreview();
            },

            clear: function() {
                if (this._target) {
                    this._target.value = '';
                    var previewEl = this._target.previousElementSibling;
                    if (previewEl && previewEl.classList.contains('bm-icon-preview-el')) previewEl.remove();
                    var ev = new Event('input', {bubbles:true});
                    this._target.dispatchEvent(ev);
                }
                this.close();
                menux_updatePreview();
            },

            select: function(ic) {
                // Deseleziona precedente
                if (this._selected) {
                    var prev = document.querySelector('[data-icon="'+this._selected+'"]');
                    if (prev) { prev.style.background='#f9fafb'; prev.style.borderColor='#e5e7eb'; }
                }
                this._selected = ic;
                var cur = document.querySelector('[data-icon="'+ic+'"]');
                if (cur) { cur.style.background='#e0e7ff'; cur.style.borderColor='#667eea'; }
                this.updatePreview(ic);
                var btn = document.getElementById('bm-icon-apply-btn');
                if (btn) { btn.disabled=false; btn.style.opacity='1'; }
            },

            updatePreview: function(ic) {
                var pv = document.getElementById('bm-icon-preview');
                if (pv) pv.innerHTML = '<i class="'+ic+'" style="font-size:22px;color:#334155;"></i> <span style="font-size:12px;color:#374151;font-weight:600;">'+ic+'</span>';
            },

            renderAll: function() {
                var body = document.getElementById('bm-icon-body');
                if (!body) return;
                body.innerHTML = '';
                Object.keys(iconGroups).forEach(function(g){ renderGroup(g, iconGroups[g], body); });
            },

            search: function(q) {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function(){
                    var body = document.getElementById('bm-icon-body');
                    if (!body) return;
                    if (!q.trim()) { mxIconPicker.renderAll(); return; }
                    body.innerHTML = '';
                    var all = [];
                    Object.values(iconGroups).forEach(function(arr){ all = all.concat(arr); });
                    var filtered = all.filter(function(ic){ return ic.indexOf(q.toLowerCase()) !== -1; });
                    if (!filtered.length) { var safeQ = q.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); body.innerHTML = '<p style="color:#9ca3af;text-align:center;padding:40px;font-size:13px;">None icona trovata per "'+safeQ+'"</p>'; return; }
                    renderGroup('Results ('+filtered.length+')', filtered, body);
                }, 200);
            }
        };
    })();

    // Inizializza icone preview esistenti al caricamento
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('input.bm-icon-input').forEach(function(inp) {
            if (!inp.value.trim()) return;
            // PHP already inserts <i> before the input for server-rendered rows — skip those.
            var prev = inp.previousElementSibling;
            if (prev && prev.classList.contains('bm-icon-preview-el')) return;
            var ic = document.createElement('i');
            ic.className = 'bm-icon-preview-el ' + inp.value.trim();
            ic.style.cssText = 'font-size:16px;color:#374151;flex-shrink:0;';
            inp.parentNode.insertBefore(ic, inp); // Always insert BEFORE the input
        });
    });
    // ---- FINE ICON PICKER ----

    // ---- ENTRANCE ANIMATION CARD HIGHLIGHT ----
    function menux_updateEntranceCard(radio) {
        document.querySelectorAll('.bm-entrance-card').forEach(function(card) {
            var inp = card.querySelector('input[type="radio"]');
            var active = inp && inp.checked;
            card.style.border = active ? '2px solid #667eea' : '2px solid #e5e7eb';
            card.style.background = active ? '#eef2ff' : '#fff';
        });
    }

    function menux_previewEntrance() {
        var nav = document.getElementById('menux-preview-nav');
        if (!nav) return;
        var anim = (document.querySelector('[name="menux_style[entrance_animation]"]:checked') || {}).value || 'none';
        var dur  = (document.querySelector('[name="menux_style[entrance_duration]"]') || {}).value || '0.5';
        var delay= (document.querySelector('[name="menux_style[entrance_delay]"]') || {}).value || '0';
        if (anim === 'none') return;
        nav.style.animation = 'none';
        nav.offsetHeight; // reflow
        nav.style.animation = 'bm-entrance-' + anim + ' ' + dur + 's ease both ' + delay + 's';
        // Stagger items
        var stagger = parseFloat((document.querySelector('[name="menux_style[entrance_stagger]"]') || {}).value || '0');
        if (stagger > 0) {
            nav.querySelectorAll('.menux-list > li').forEach(function(li, i) {
                li.style.animation = 'none';
                li.offsetHeight;
                li.style.animation = 'bm-entrance-' + anim + ' ' + dur + 's ease both ' + (parseFloat(delay) + i * stagger) + 's';
            });
        }
    }
    // ---- END ENTRANCE ANIMATION ----

    /* ══ ENTRANCE CONTROLS TOGGLE ══ */
    window.menuxToggleEntranceControls = function(val) {
        var el = document.getElementById('menux-entrance-controls');
        if (el) el.style.display = val === 'none' ? 'none' : 'flex';
    };

    /* ══ STICKY MIRROR TOGGLE ══ */
    window.menuxToggleStickyMirror = function(mirrored) {
        var ids = ['menux-sticky-row-bg','menux-sticky-row-shadow','menux-sticky-row-justify','menux-sticky-row-align','menux-sticky-row-padx','menux-sticky-row-pady'];
        ids.forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.style.display = mirrored ? 'none' : '';
        });
    };

    /* ══ ACCORDION ITEM TOGGLE ══ */
    window.menuxToggleItem = function(header) {
        header.closest('.menux-item').classList.toggle('menux-item-open');
    };

    /* ══ ADD-SECTION TAB SWITCHER ══ */
    window.menuxAddTab = function(tab) {
        document.querySelectorAll('.bm-add-tab-btn').forEach(function(btn) {
            btn.classList.toggle('active', btn.dataset.tab === tab);
        });
        var pp = document.getElementById('bm-add-pane-page');
        var pl = document.getElementById('bm-add-pane-link');
        if (pp) pp.style.display = tab === 'page' ? 'block' : 'none';
        if (pl) pl.style.display = tab === 'link' ? 'block' : 'none';
    };

    jQuery(document).ready(function($) {
        try {
            var $ul = $('#menux-sortable');
            if ($ul.length && typeof $.fn.sortable === 'function') {
                $ul.sortable({
                    handle: '.menux-drag-handle',
                    axis: 'y',
                    placeholder: 'menux-sortable-placeholder',
                    forcePlaceholderSize: true,
                    helper: 'clone',
                    opacity: 0.9,
                    start: function(e, ui) { ui.placeholder.height(ui.item.outerHeight()); },
                    update: function() { menux_reindex(); menux_updatePreview(); }
                });
            }
        } catch(e) {}

        $(document).on('input change', '.menux-panel input, .menux-panel select', function() { menux_updatePreview(); });
        $(document).on('input change', '.menux-style-panel input, .menux-style-panel select, .menux-style-panel textarea', function() { menux_liveStylePreview(); });
        // Announcement / Search / WooCommerce panels affect preview HTML structure (position, enabled state)
        $(document).on('input change', '#panel-announcement input, #panel-announcement select, #panel-search input, #panel-search select, #panel-woocommerce input, #panel-woocommerce select', function() { menux_updatePreview(); });

        // Inizializzazione al caricamento
        menux_liveStylePreview();
        menux_updatePreview();
    });
    function menux_build_vis_options(selectedVal) {
        var html = '';
        for (var val in menux_wp_roles) {
            html += '<option value="' + val + '"' + (val === selectedVal ? ' selected' : '') + '>' + menux_wp_roles[val] + '</option>';
        }
        return html;
    }
    function menux_buildPageOptions() {
        var html = '<option value="">📄 WP Page...</option>';
        menux_all_pages.forEach(function(p) {
            html += '<option value="' + p.id + '" data-title="' + menux_esc(p.title) + '">' + menux_esc(p.title) + '</option>';
        });
        return html;
    }

    var menuxStyleSections = ['themes','colors','typo','layout','mobile'];

    function menuxGoSection(section) {
        var tracker = document.getElementById('menux-active-section');
        if (tracker) tracker.value = section;
        window._menuxActiveSection = section;
        // Hide all panels
        document.querySelectorAll('.bm-panel').forEach(function(p) { p.style.display = 'none'; });
        // Update sidebar active state
        document.querySelectorAll('.bm-sidebar-item').forEach(function(b) { b.classList.remove('active'); });
        var activeBtn = document.querySelector('.bm-sidebar-item[data-section="' + section + '"]');
        if (activeBtn) activeBtn.classList.add('active');
        // Show the correct panel
        if (menuxStyleSections.indexOf(section) !== -1) {
            var stylePanel = document.getElementById('panel-style');
            if (stylePanel) stylePanel.style.display = '';
            if (typeof menux_switchTab === 'function') menux_switchTab('bm-tab-' + section);
            if (section === 'themes' && typeof buildInlineThemeGrid === 'function') buildInlineThemeGrid();
        } else {
            var panel = document.getElementById('panel-' + section);
            if (panel) panel.style.display = '';
        }
    }

    /* ================================================================
       PRESET THEMES
       ================================================================ */
    var bmThemes = {

    'ghost': {
        title: 'Ghost',
        badge: 'Minimal',
        cat: 'minimal',
        colors: ['#ffffff', '#6b7280', '#6366f1'],
        data: {
            container_bg: '#ffffff', container_bg_gradient: '', container_border: '',
            link_color: '#6b7280', link_hover_color: '#111827', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#6b7280', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'underline',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#ffffff', submenu_border: '#e5e7eb', submenu_link_color: '#374151',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'void_dark': {
        title: 'Void Dark',
        badge: 'Premium',
        cat: 'dark',
        colors: ['#09090b', '#52525b', '#fafafa'],
        data: {
            container_bg: '#09090b', container_bg_gradient: '', container_border: '',
            link_color: '#a1a1aa', link_hover_color: '#f4f4f5', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#71717a', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '400', gap: '4', padding_x: '20', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '-0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#18181b', submenu_border: '#27272a', submenu_link_color: '#a1a1aa',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'indigo_pulse': {
        title: 'Indigo Pulse',
        badge: 'SaaS',
        cat: 'corporate',
        colors: ['#ffffff', '#4f46e5', '#eef2ff'],
        data: {
            container_bg: '#ffffff', container_bg_gradient: '', container_border: '',
            link_color: '#4b5563', link_hover_color: '#1e1b4b', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#4f46e5', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '4', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'slideDown', entrance_duration: '0.35',
            submenu_bg: '#ffffff', submenu_border: '#e5e7eb', submenu_link_color: '#4b5563',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'aurora_night': {
        title: 'Aurora Night',
        badge: 'Vibrant',
        cat: 'creative',
        colors: ['linear-gradient(135deg,#0f0c29,#302b63)', '#a78bfa', '#4ade80'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#0f0c29,#302b63,#24243e)', container_border: '',
            link_color: '#a78bfa', link_hover_color: '#e9d5ff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#a78bfa', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '600', gap: '6', padding_x: '16', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '0.8', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.5',
            submenu_bg: '#1a1030', submenu_border: '#302b63', submenu_link_color: '#c4b5fd',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'navy_command': {
        title: 'Navy Command',
        badge: 'Corporate',
        cat: 'corporate',
        colors: ['linear-gradient(135deg,#1e3a8a,#2563eb)', '#93c5fd', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#1e3a8a,#2563eb)', container_border: '',
            link_color: '#93c5fd', link_hover_color: '#dbeafe', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '4', padding_x: '20', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#1e3a8a', submenu_border: '#2563eb', submenu_link_color: '#bfdbfe',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'tropical_bloom': {
        title: 'Tropical Bloom',
        badge: 'Energetic',
        cat: 'vibrant',
        colors: ['linear-gradient(135deg,#f97316,#db2777)', '#ffffff', '#fef3c7'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#f97316,#db2777)', container_border: '',
            link_color: '#ffffff', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#c2185b', submenu_border: '#ec4899', submenu_link_color: '#fce7f3',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'evergreen': {
        title: 'Evergreen',
        badge: 'Nature',
        cat: 'nature',
        colors: ['linear-gradient(135deg,#064e3b,#059669)', '#6ee7b7', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#064e3b,#059669)', container_border: '',
            link_color: '#6ee7b7', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '14', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#065f46', submenu_border: '#059669', submenu_link_color: '#d1fae5',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'cyber_matrix': {
        title: 'Cyber Matrix',
        badge: 'Cyberpunk',
        cat: 'creative',
        colors: ['#0a0a0a', '#888888', '#00ff88'],
        data: {
            container_bg: '#0a0a0a', container_bg_gradient: '', container_border: '',
            link_color: '#888888', link_hover_color: '#00ff88', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#00ff88', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '12', font_weight: '400', gap: '4', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '12', mobile_menu_shadow: '1',
            font_family: 'Space Mono, monospace', google_font: 'Space Mono',
            push_last_item: '0', link_transition: '0.15', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '1.5', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#111111', submenu_border: '#00ff88', submenu_link_color: '#00ff88',
            submenu_animation: 'none', submenu_shadow: '0',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'rose_silk': {
        title: 'Rose Silk',
        badge: 'Elegant',
        cat: 'elegant',
        colors: ['#fff1f2', '#be185d', '#fce7f3'],
        data: {
            container_bg: '#fff1f2', container_bg_gradient: '', container_border: '',
            link_color: '#be185d', link_hover_color: '#9d174d', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#be185d', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '500', gap: '8', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Lora, serif', google_font: 'Lora',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fff1f2', submenu_border: '#fecdd3', submenu_link_color: '#9d174d',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'sky_fresh': {
        title: 'Sky Fresh',
        badge: 'Fresh',
        cat: 'minimal',
        colors: ['linear-gradient(180deg,#e0f2fe,#f0f9ff)', '#0369a1', '#0ea5e9'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(180deg,#e0f2fe,#f0f9ff)', container_border: '',
            link_color: '#0369a1', link_hover_color: '#0c4a6e', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#0369a1', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '8', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#f0f9ff', submenu_border: '#bae6fd', submenu_link_color: '#0369a1',
            submenu_animation: 'slide', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'newspaper_ink': {
        title: 'Newspaper Ink',
        badge: 'Editorial',
        cat: 'elegant',
        colors: ['#fafaf9', '#44403c', '#1c1917'],
        data: {
            container_bg: '#fafaf9', container_bg_gradient: '', container_border: '',
            link_color: '#44403c', link_hover_color: '#0c0a09', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#1c1917', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '500', gap: '0', padding_x: '22', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Playfair Display, serif', google_font: 'Playfair Display',
            push_last_item: '0', link_transition: '0.15', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '2', link_border_radius: '0',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fafaf9', submenu_border: '#1c1917', submenu_link_color: '#44403c',
            submenu_animation: 'none', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'dev_dark': {
        title: 'Dev Dark',
        badge: 'Developer',
        cat: 'dark',
        colors: ['#0d1117', '#8b949e', '#388bfd'],
        data: {
            container_bg: '#0d1117', container_bg_gradient: '', container_border: '',
            link_color: '#8b949e', link_hover_color: '#e6edf3', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#8b949e', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '400', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '12', mobile_menu_shadow: '1',
            font_family: 'JetBrains Mono, monospace', google_font: 'JetBrains Mono',
            push_last_item: '0', link_transition: '0.15', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#161b22', submenu_border: '#30363d', submenu_link_color: '#8b949e',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'ocean_electric': {
        title: 'Ocean Electric',
        badge: 'Modern',
        cat: 'vibrant',
        colors: ['linear-gradient(135deg,#0052D4,#4364F7,#6FB1FC)', '#dbeafe', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#0052D4,#4364F7,#6FB1FC)', container_border: '',
            link_color: '#dbeafe', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '4', padding_x: '16', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '12', mobile_menu_shadow: '1',
            font_family: 'Raleway, sans-serif', google_font: 'Raleway',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#1e40af', submenu_border: '#3b82f6', submenu_link_color: '#bfdbfe',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'violet_cloud': {
        title: 'Violet Cloud',
        badge: 'Startup',
        cat: 'vibrant',
        colors: ['linear-gradient(135deg,#667eea,#764ba2)', '#ffffff', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#667eea,#764ba2)', container_border: '',
            link_color: '#ffffff', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.25', link_animation: 'underline',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'slideDown', entrance_duration: '0.4',
            submenu_bg: '#5b21b6', submenu_border: '#7c3aed', submenu_link_color: '#e0d7ff',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'swiss_pro': {
        title: 'Swiss Pro',
        badge: 'Corporate',
        cat: 'corporate',
        colors: ['#ffffff', '#374151', '#dc2626'],
        data: {
            container_bg: '#ffffff', container_bg_gradient: '', container_border: '',
            link_color: '#374151', link_hover_color: '#111827', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#374151', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '600', gap: '0', padding_x: '24', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'system-ui, -apple-system, sans-serif', google_font: '',
            push_last_item: '0', link_transition: '0.15', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '0.5', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#ffffff', submenu_border: '#e5e7eb', submenu_link_color: '#374151',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'cosmic_dusk': {
        title: 'Cosmic Dusk',
        badge: 'Space',
        cat: 'creative',
        colors: ['linear-gradient(135deg,#13001e,#2d0035)', '#c084fc', '#a855f7'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#13001e,#2d0035,#0a001a)', container_border: '',
            link_color: '#c084fc', link_hover_color: '#e9d5ff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#c084fc', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '500', gap: '4', padding_x: '16', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '0.8', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.6',
            submenu_bg: '#1a0029', submenu_border: '#3b0764', submenu_link_color: '#c084fc',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'warm_honey': {
        title: 'Warm Honey',
        badge: 'Warm',
        cat: 'nature',
        colors: ['#fffbeb', '#92400e', '#fde68a'],
        data: {
            container_bg: '#fffbeb', container_bg_gradient: '', container_border: '',
            link_color: '#92400e', link_hover_color: '#78350f', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#92400e', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '8', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fffbeb', submenu_border: '#fde68a', submenu_link_color: '#92400e',
            submenu_animation: 'slide', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'cloud_glass': {
        title: 'Cloud Glass',
        badge: 'Modern',
        cat: 'glass',
        colors: ['#f8fafc', '#475569', '#6366f1'],
        data: {
            container_bg: '#f8fafc', container_bg_gradient: '', container_border: '',
            link_color: '#475569', link_hover_color: '#0f172a', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#6366f1', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#ffffff', submenu_border: '#e2e8f0', submenu_link_color: '#475569',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'carbon_pro': {
        title: 'Carbon Pro',
        badge: 'Dark',
        cat: 'dark',
        colors: ['#1c1c1e', '#8d8d93', '#f2f2f7'],
        data: {
            container_bg: '#1c1c1e', container_bg_gradient: '', container_border: '',
            link_color: '#8d8d93', link_hover_color: '#f2f2f7', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#8d8d93', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '400', gap: '4', padding_x: '20', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#2c2c2e', submenu_border: '#3a3a3c', submenu_link_color: '#ebebf5',
            submenu_animation: 'fade', submenu_shadow: '0',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'aegean_teal': {
        title: 'Aegean Teal',
        badge: 'Fresh',
        cat: 'nature',
        colors: ['linear-gradient(135deg,#f0fdfa,#ffffff)', '#0f766e', '#14b8a6'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#f0fdfa,#ffffff)', container_border: '',
            link_color: '#0f766e', link_hover_color: '#134e4a', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#0f766e', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '8', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'underline',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#f0fdfa', submenu_border: '#99f6e4', submenu_link_color: '#0f766e',
            submenu_animation: 'slide', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ───────────────────────── DARK ───────────────────────── */
    'obsidian_gold': {
        title: 'Obsidian Gold',
        badge: 'Luxe Dark',
        cat: 'dark',
        colors: ['#0b0b0f', '#d4af37', '#f5e7b8'],
        data: {
            container_bg: '#0b0b0f', container_bg_gradient: '', container_border: '',
            link_color: '#d4af37', link_hover_color: '#f5e7b8', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#d4af37', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '20', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.4', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#15151c', submenu_border: '#2a2a35', submenu_link_color: '#d4af37',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'graphite_ice': {
        title: 'Graphite Ice',
        badge: 'Slate Mono',
        cat: 'dark',
        colors: ['#1e293b', '#94a3b8', '#38bdf8'],
        data: {
            container_bg: '#1e293b', container_bg_gradient: '', container_border: '',
            link_color: '#94a3b8', link_hover_color: '#f1f5f9', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#38bdf8', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '400', gap: '4', padding_x: '20', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'IBM Plex Mono, monospace', google_font: 'IBM Plex Mono',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#0f172a', submenu_border: '#334155', submenu_link_color: '#cbd5e1',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── MINIMAL ──────────────────────── */
    'paper_white': {
        title: 'Paper White',
        badge: 'Clean',
        cat: 'minimal',
        colors: ['#ffffff', '#525252', '#0a0a0a'],
        data: {
            container_bg: '#ffffff', container_bg_gradient: '', container_border: '#e5e5e5',
            link_color: '#525252', link_hover_color: '#0a0a0a', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#525252', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'underline',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#ffffff', submenu_border: '#e5e5e5', submenu_link_color: '#525252',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'nordic_calm': {
        title: 'Nordic Calm',
        badge: 'Nordic',
        cat: 'minimal',
        colors: ['#eceff4', '#4c566a', '#5e81ac'],
        data: {
            container_bg: '#eceff4', container_bg_gradient: '', container_border: '',
            link_color: '#4c566a', link_hover_color: '#2e3440', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#5e81ac', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#e5e9f0', submenu_border: '#d8dee9', submenu_link_color: '#4c566a',
            submenu_animation: 'slide', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'mono_line': {
        title: 'Mono Line',
        badge: 'Typographic',
        cat: 'minimal',
        colors: ['#fafafa', '#18181b', '#71717a'],
        data: {
            container_bg: '#fafafa', container_bg_gradient: '', container_border: '#18181b',
            link_color: '#18181b', link_hover_color: '#18181b', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#18181b', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '600', gap: '2', padding_x: '20', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Space Grotesk, sans-serif', google_font: 'Space Grotesk',
            push_last_item: '0', link_transition: '0.15', link_animation: 'underline',
            text_transform: 'uppercase', letter_spacing: '1', link_border_radius: '0',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fafafa', submenu_border: '#18181b', submenu_link_color: '#18181b',
            submenu_animation: 'none', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── VIBRANT ──────────────────────── */
    'sunset_blaze': {
        title: 'Sunset Blaze',
        badge: 'Sunset',
        cat: 'vibrant',
        colors: ['linear-gradient(135deg,#ff512f,#dd2476)', '#ffffff', '#ffe4f0'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#ff512f,#dd2476)', container_border: '',
            link_color: '#ffffff', link_hover_color: '#ffe4f0', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffffff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#c81d6b', submenu_border: '#ff6ec7', submenu_link_color: '#ffe4f0',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'citrus_pop': {
        title: 'Citrus Pop',
        badge: 'Citrus',
        cat: 'vibrant',
        colors: ['linear-gradient(135deg,#f7971e,#ffd200)', '#422006', '#9a3412'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#f7971e,#ffd200)', container_border: '',
            link_color: '#422006', link_hover_color: '#7c2d12', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#422006', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '700', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fff7ed', submenu_border: '#fdba74', submenu_link_color: '#9a3412',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── CREATIVE ─────────────────────── */
    'neon_synth': {
        title: 'Neon Synthwave',
        badge: 'Synthwave',
        cat: 'creative',
        colors: ['#1a0b2e', '#ff2e97', '#00e5ff'],
        data: {
            container_bg: '#1a0b2e', container_bg_gradient: '', container_border: '',
            link_color: '#ff2e97', link_hover_color: '#00e5ff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#00e5ff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '12', font_weight: '500', gap: '4', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Orbitron, sans-serif', google_font: 'Orbitron',
            push_last_item: '0', link_transition: '0.2', link_animation: 'glow',
            text_transform: 'uppercase', letter_spacing: '1.5', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.5',
            submenu_bg: '#0f0620', submenu_border: '#ff2e97', submenu_link_color: '#00e5ff',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'holographic': {
        title: 'Holographic',
        badge: 'Iridescent',
        cat: 'creative',
        colors: ['linear-gradient(135deg,#a18cd1,#fbc2eb)', '#2d1b4e', '#6b21a8'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#a18cd1,#fbc2eb)', container_border: '',
            link_color: '#2d1b4e', link_hover_color: '#6b21a8', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#2d1b4e', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Quicksand, sans-serif', google_font: 'Quicksand',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'fadeIn', entrance_duration: '0.5',
            submenu_bg: '#f3e8ff', submenu_border: '#d8b4fe', submenu_link_color: '#6b21a8',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ─────────────────────── CORPORATE ─────────────────────── */
    'executive_navy': {
        title: 'Executive Navy',
        badge: 'Executive',
        cat: 'corporate',
        colors: ['#0f172a', '#cbd5e1', '#38bdf8'],
        data: {
            container_bg: '#0f172a', container_bg_gradient: '', container_border: '',
            link_color: '#cbd5e1', link_hover_color: '#f8fafc', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#38bdf8', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '4', padding_x: '20', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#1e293b', submenu_border: '#334155', submenu_link_color: '#cbd5e1',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'crimson_trust': {
        title: 'Crimson Trust',
        badge: 'Trust',
        cat: 'corporate',
        colors: ['#ffffff', '#1f2937', '#b91c1c'],
        data: {
            container_bg: '#ffffff', container_bg_gradient: '', container_border: '#e5e7eb',
            link_color: '#1f2937', link_hover_color: '#b91c1c', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#b91c1c', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '600', gap: '2', padding_x: '20', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.18', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '0.5', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#ffffff', submenu_border: '#fecaca', submenu_link_color: '#1f2937',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── NATURE ───────────────────────── */
    'forest_moss': {
        title: 'Forest Moss',
        badge: 'Forest',
        cat: 'nature',
        colors: ['linear-gradient(135deg,#2d5016,#3a6b35)', '#d4e09b', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#2d5016,#3a6b35)', container_border: '',
            link_color: '#d4e09b', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#d4e09b', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '14', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#1a3409', submenu_border: '#3a6b35', submenu_link_color: '#d4e09b',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'terracotta_earth': {
        title: 'Terracotta Earth',
        badge: 'Terracotta',
        cat: 'nature',
        colors: ['#faf3e0', '#9c4221', '#c2410c'],
        data: {
            container_bg: '#faf3e0', container_bg_gradient: '', container_border: '',
            link_color: '#9c4221', link_hover_color: '#7c2d12', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#c2410c', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '8', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fef6e9', submenu_border: '#fed7aa', submenu_link_color: '#9c4221',
            submenu_animation: 'slide', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── ELEGANT ──────────────────────── */
    'noir_serif': {
        title: 'Noir Élégance',
        badge: 'Noir',
        cat: 'elegant',
        colors: ['#0c0c0c', '#e0c097', '#f7e9d0'],
        data: {
            container_bg: '#0c0c0c', container_bg_gradient: '', container_border: '',
            link_color: '#e0c097', link_hover_color: '#f7e9d0', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#e0c097', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '16', font_weight: '500', gap: '8', padding_x: '20', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'Cormorant Garamond, serif', google_font: 'Cormorant Garamond',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.6',
            submenu_bg: '#161616', submenu_border: '#3a3326', submenu_link_color: '#e0c097',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'pearl_luxe': {
        title: 'Pearl Luxe',
        badge: 'Pearl',
        cat: 'elegant',
        colors: ['#f5f5f0', '#1a1a1a', '#b8860b'],
        data: {
            container_bg: '#f5f5f0', container_bg_gradient: '', container_border: '',
            link_color: '#1a1a1a', link_hover_color: '#6b5b4f', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#1a1a1a', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '16', font_weight: '500', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Playfair Display, serif', google_font: 'Playfair Display',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#faf9f5', submenu_border: '#d6d3cb', submenu_link_color: '#1a1a1a',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'burgundy_velvet': {
        title: 'Burgundy Velvet',
        badge: 'Velvet',
        cat: 'elegant',
        colors: ['#2b0a14', '#e8b4bc', '#fce7eb'],
        data: {
            container_bg: '#2b0a14', container_bg_gradient: '', container_border: '',
            link_color: '#e8b4bc', link_hover_color: '#fce7eb', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#e8b4bc', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '500', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Lora, serif', google_font: 'Lora',
            push_last_item: '0', link_transition: '0.3', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#3d1320', submenu_border: '#5c1a2e', submenu_link_color: '#e8b4bc',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },

    /* ───────────────────────── RETRO ───────────────────────── */
    'miami_80s': {
        title: 'Miami 80s',
        badge: 'Miami',
        cat: 'retro',
        colors: ['linear-gradient(135deg,#2e1a47,#ff6ec7)', '#00f0ff', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#2e1a47,#ff6ec7)', container_border: '',
            link_color: '#00f0ff', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#00f0ff', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Space Mono, monospace', google_font: 'Space Mono',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '1.5', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.5',
            submenu_bg: '#1a0f2e', submenu_border: '#ff6ec7', submenu_link_color: '#00f0ff',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'vaporwave': {
        title: 'Vaporwave',
        badge: 'Aesthetic',
        cat: 'retro',
        colors: ['linear-gradient(135deg,#ff71ce,#01cdfe)', '#2d1b4e', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#ff71ce,#01cdfe)', container_border: '',
            link_color: '#2d1b4e', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#2d1b4e', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '13', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Space Mono, monospace', google_font: 'Space Mono',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '1', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.5',
            submenu_bg: '#b5179e', submenu_border: '#f72585', submenu_link_color: '#fff0fb',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'vintage_sepia': {
        title: 'Vintage Sepia',
        badge: 'Vintage',
        cat: 'retro',
        colors: ['#f4ecd8', '#5c4033', '#8b5a2b'],
        data: {
            container_bg: '#f4ecd8', container_bg_gradient: '', container_border: '',
            link_color: '#5c4033', link_hover_color: '#3a2817', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#8b5a2b', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '500', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'classic', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '0',
            font_family: 'Lora, serif', google_font: 'Lora',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#faf4e6', submenu_border: '#d2b48c', submenu_link_color: '#5c4033',
            submenu_animation: 'fade', submenu_shadow: '0',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'retro_arcade': {
        title: 'Retro Arcade',
        badge: 'Arcade',
        cat: 'retro',
        colors: ['#0f0f23', '#ffd700', '#ff4081'],
        data: {
            container_bg: '#0f0f23', container_bg_gradient: '', container_border: '',
            link_color: '#ffd700', link_hover_color: '#ff4081', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ffd700', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '18', font_weight: '400', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'minimal', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'VT323, monospace', google_font: 'VT323',
            push_last_item: '0', link_transition: '0.15', link_animation: 'none',
            text_transform: 'uppercase', letter_spacing: '1', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#1a1a3a', submenu_border: '#ffd700', submenu_link_color: '#ffd700',
            submenu_animation: 'none', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'seventies_funk': {
        title: 'Seventies Funk',
        badge: '70s Funk',
        cat: 'retro',
        colors: ['#3d2817', '#e9c46a', '#f4a261'],
        data: {
            container_bg: '#3d2817', container_bg_gradient: '', container_border: '',
            link_color: '#e9c46a', link_hover_color: '#f4a261', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#e9c46a', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '600', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            font_family: 'Poppins, sans-serif', google_font: 'Poppins',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.3', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#2a1c10', submenu_border: '#6b4423', submenu_link_color: '#e9c46a',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },

    /* ───────────────────────── GLASS ───────────────────────── */
    'frosted_aqua': {
        title: 'Frosted Aqua',
        badge: 'Frosted',
        cat: 'glass',
        colors: ['linear-gradient(135deg,#d4f1f4,#e8f5f9)', '#0e7490', '#06b6d4'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#d4f1f4,#e8f5f9)', container_border: '',
            link_color: '#0e7490', link_hover_color: '#155e75', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#06b6d4', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#e8f5f9', submenu_border: '#a5e8f0', submenu_link_color: '#0e7490',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'smoked_glass': {
        title: 'Smoked Glass',
        badge: 'Smoked',
        cat: 'glass',
        colors: ['linear-gradient(135deg,#2c3036,#3a3f47)', '#d1d5db', '#ffffff'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#2c3036,#3a3f47)', container_border: '',
            link_color: '#d1d5db', link_hover_color: '#ffffff', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#d1d5db', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '400', gap: '6', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '0', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '0.2', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#33373e', submenu_border: '#4b5159', submenu_link_color: '#d1d5db',
            submenu_animation: 'fade', submenu_shadow: '1',
            dark_mode: 'dark', nav_justify: 'flex-end'
        }
    },
    'rose_quartz_glass': {
        title: 'Rose Quartz',
        badge: 'Translucent',
        cat: 'glass',
        colors: ['linear-gradient(135deg,#fce4ec,#f8e1ee)', '#9d174d', '#db2777'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#fce4ec,#f8e1ee)', container_border: '',
            link_color: '#9d174d', link_hover_color: '#831843', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#db2777', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Quicksand, sans-serif', google_font: 'Quicksand',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#fdf2f8', submenu_border: '#fbcfe8', submenu_link_color: '#9d174d',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'arctic_glass': {
        title: 'Arctic Glass',
        badge: 'Crystal',
        cat: 'glass',
        colors: ['linear-gradient(135deg,#eef2f7,#f7fafc)', '#475569', '#6366f1'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#eef2f7,#f7fafc)', container_border: '',
            link_color: '#475569', link_hover_color: '#1e293b', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#6366f1', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '14', font_weight: '500', gap: '6', padding_x: '16', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Inter, sans-serif', google_font: 'Inter',
            push_last_item: '0', link_transition: '0.2', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '20',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            entrance_animation: 'fadeIn', entrance_duration: '0.4',
            submenu_bg: '#f7fafc', submenu_border: '#e2e8f0', submenu_link_color: '#475569',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },

    /* ──────────────────────── PLAYFUL ──────────────────────── */
    'bubblegum': {
        title: 'Bubblegum',
        badge: 'Bubblegum',
        cat: 'playful',
        colors: ['#ffe0f0', '#ff5ca2', '#d6246e'],
        data: {
            container_bg: '#ffe0f0', container_bg_gradient: '', container_border: '',
            link_color: '#ff5ca2', link_hover_color: '#d6246e', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#ff5ca2', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '700', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Quicksand, sans-serif', google_font: 'Quicksand',
            push_last_item: '0', link_transition: '0.25', link_animation: 'bounce',
            text_transform: '', letter_spacing: '', link_border_radius: '24',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fff0f7', submenu_border: '#ffb8d9', submenu_link_color: '#ff5ca2',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'candy_pop': {
        title: 'Candy Pop',
        badge: 'Candy',
        cat: 'playful',
        colors: ['linear-gradient(135deg,#fbc2eb,#a6c1ee)', '#6d28d9', '#4c1d95'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#fbc2eb,#a6c1ee)', container_border: '',
            link_color: '#6d28d9', link_hover_color: '#4c1d95', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#6d28d9', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '700', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '24',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#f5f3ff', submenu_border: '#ddd6fe', submenu_link_color: '#6d28d9',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'mint_bubble': {
        title: 'Mint Bubble',
        badge: 'Mint',
        cat: 'playful',
        colors: ['#e0fff4', '#06b6a4', '#047a6e'],
        data: {
            container_bg: '#e0fff4', container_bg_gradient: '', container_border: '',
            link_color: '#06b6a4', link_hover_color: '#047a6e', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#06b6a4', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '600', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Quicksand, sans-serif', google_font: 'Quicksand',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '24',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#f0fffa', submenu_border: '#99f6e4', submenu_link_color: '#06b6a4',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'sunny_comic': {
        title: 'Sunny Comic',
        badge: 'Comic',
        cat: 'playful',
        colors: ['#fffbe6', '#2563eb', '#f59e0b'],
        data: {
            container_bg: '#fffbe6', container_bg_gradient: '', container_border: '',
            link_color: '#2563eb', link_hover_color: '#f59e0b', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#2563eb', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '600', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Baloo 2, cursive', google_font: 'Baloo 2',
            push_last_item: '0', link_transition: '0.25', link_animation: 'bounce',
            text_transform: '', letter_spacing: '', link_border_radius: '24',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fffdf2', submenu_border: '#fde68a', submenu_link_color: '#2563eb',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    },
    'lemonade': {
        title: 'Lemonade',
        badge: 'Lemonade',
        cat: 'playful',
        colors: ['linear-gradient(135deg,#fffde7,#fff9c4)', '#f57f17', '#e65100'],
        data: {
            container_bg: '', container_bg_gradient: 'linear-gradient(135deg,#fffde7,#fff9c4)', container_border: '',
            link_color: '#f57f17', link_hover_color: '#e65100', link_hover_bg: '', link_hover_bg_gradient: '',
            link_active_color: '', link_active_border: '', link_active_bg: '', link_active_bg_gradient: '', link_active_font_weight: '',
            hamburger_color: '#f57f17', hamburger_bg: '',
            last_item_color: '', last_item_hover_color: '', last_item_bg: '', close_btn_color: '#ffffff',
            font_size: '15', font_weight: '700', gap: '8', padding_x: '18', padding_y: '15',
            hamburger_style: 'modern', hamburger_align: 'flex-end', mobile_menu_pad: '20', mobile_menu_shadow: '1',
            font_family: 'Nunito, sans-serif', google_font: 'Nunito',
            push_last_item: '0', link_transition: '0.25', link_animation: 'none',
            text_transform: '', letter_spacing: '', link_border_radius: '24',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'scale',
            entrance_animation: 'none', entrance_duration: '0.5',
            submenu_bg: '#fffef5', submenu_border: '#fff59d', submenu_link_color: '#f57f17',
            submenu_animation: 'slide', submenu_shadow: '1',
            dark_mode: 'light', nav_justify: 'flex-end'
        }
    }

};

// ── Mobile Presets ────────────────────────────────────────────────────────────
// Each preset sets ONLY mobile-specific fields; desktop theme settings are untouched.
// preview: used to render the mini phone mockup card (bg, text, type, align).
var bmMobilePresets = {

    'midnight': {
        title: 'Midnight', icon: '🌑',
        preview: { bg: '#000000', text: '#ffffff', type: 'fullscreen', align: 'center' },
        colors: ['#000000', '#1a1a1a', '#818cf8'],
        data: {
            hamburger_style: 'minimal', hamburger_align: 'flex-end',
            hamburger_color: '#222222', hamburger_bg: '',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'slide',
            mobile_overlay_bg: '#000000', mobile_overlay_opacity: '0.97', mobile_overlay_blur: '0',
            mobile_link_color: '#ffffff', mobile_link_hover_color: '#a5b4fc', mobile_link_active_color: '#818cf8',
            mobile_fullscreen_align: 'center',
            mobile_drawer_width: '280', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            close_btn_color: '#ffffff', close_btn_bg: ''
        }
    },

    'slate_drawer': {
        title: 'Slate Drawer', icon: '◀',
        preview: { bg: '#1e293b', text: '#e2e8f0', type: 'drawer-left', align: 'flex-start' },
        colors: ['#1e293b', '#334155', '#7dd3fc'],
        data: {
            hamburger_style: 'modern', hamburger_align: 'flex-start',
            hamburger_color: '#1e293b', hamburger_bg: '',
            mobile_open_style: 'drawer-left', mobile_open_animation: 'slide',
            mobile_overlay_bg: '#1e293b', mobile_overlay_opacity: '1', mobile_overlay_blur: '0',
            mobile_link_color: '#e2e8f0', mobile_link_hover_color: '#ffffff', mobile_link_active_color: '#7dd3fc',
            mobile_fullscreen_align: 'center',
            mobile_drawer_width: '280', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            close_btn_color: '#e2e8f0', close_btn_bg: ''
        }
    },

    'clean_drop': {
        title: 'Clean Drop', icon: '⬇',
        preview: { bg: '#ffffff', text: '#111827', type: 'dropdown', align: 'flex-start' },
        colors: ['#ffffff', '#f1f5f9', '#4f46e5'],
        data: {
            hamburger_style: 'classic', hamburger_align: 'flex-end',
            hamburger_color: '#374151', hamburger_bg: '',
            mobile_open_style: 'dropdown', mobile_open_animation: 'slide',
            mobile_overlay_bg: '#000000', mobile_overlay_opacity: '0.5', mobile_overlay_blur: '0',
            mobile_link_color: '#111827', mobile_link_hover_color: '#4f46e5', mobile_link_active_color: '#4f46e5',
            mobile_fullscreen_align: 'flex-start',
            mobile_drawer_width: '280', mobile_menu_pad: '12', mobile_menu_shadow: '1',
            close_btn_color: '#374151', close_btn_bg: ''
        }
    },

    'ember': {
        title: 'Ember Night', icon: '🔥',
        preview: { bg: '#1c0f0a', text: '#fef3c7', type: 'fullscreen', align: 'center' },
        colors: ['#1c0f0a', '#2d1810', '#fbbf24'],
        data: {
            hamburger_style: 'modern', hamburger_align: 'flex-end',
            hamburger_color: '#b45309', hamburger_bg: '',
            mobile_open_style: 'fullscreen', mobile_open_animation: 'fade',
            mobile_overlay_bg: '#1c0f0a', mobile_overlay_opacity: '0.98', mobile_overlay_blur: '0',
            mobile_link_color: '#fef3c7', mobile_link_hover_color: '#fbbf24', mobile_link_active_color: '#f59e0b',
            mobile_fullscreen_align: 'center',
            mobile_drawer_width: '280', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            close_btn_color: '#fbbf24', close_btn_bg: ''
        }
    },

    'navy_side': {
        title: 'Navy Side', icon: '▶',
        preview: { bg: '#0f172a', text: '#e0f2fe', type: 'drawer-right', align: 'flex-start' },
        colors: ['#0f172a', '#1e3a5f', '#38bdf8'],
        data: {
            hamburger_style: 'modern', hamburger_align: 'flex-end',
            hamburger_color: '#0f172a', hamburger_bg: '',
            mobile_open_style: 'drawer-right', mobile_open_animation: 'slide',
            mobile_overlay_bg: '#0f172a', mobile_overlay_opacity: '1', mobile_overlay_blur: '0',
            mobile_link_color: '#e0f2fe', mobile_link_hover_color: '#ffffff', mobile_link_active_color: '#38bdf8',
            mobile_fullscreen_align: 'center',
            mobile_drawer_width: '300', mobile_menu_pad: '0', mobile_menu_shadow: '0',
            close_btn_color: '#e0f2fe', close_btn_bg: ''
        }
    },

    'frosted': {
        title: 'Frosted', icon: '🧊',
        preview: { bg: '#f0f4ff', text: '#1e1b4b', type: 'dropdown', align: 'flex-start' },
        colors: ['#f0f4ff', '#e0e7ff', '#4f46e5'],
        data: {
            hamburger_style: 'minimal', hamburger_align: 'flex-end',
            hamburger_color: '#4f46e5', hamburger_bg: '',
            mobile_open_style: 'dropdown', mobile_open_animation: 'fade',
            mobile_overlay_bg: '#000000', mobile_overlay_opacity: '0.3', mobile_overlay_blur: '4',
            mobile_link_color: '#1e1b4b', mobile_link_hover_color: '#4f46e5', mobile_link_active_color: '#4338ca',
            mobile_fullscreen_align: 'flex-start',
            mobile_drawer_width: '280', mobile_menu_pad: '16', mobile_menu_shadow: '1',
            close_btn_color: '#4f46e5', close_btn_bg: ''
        }
    }

};

// Renders a CSS-only mini phone mockup showing how the mobile menu looks.
function buildMiniPhone(pv) {
    var isFullscreen = pv.type === 'fullscreen';
    var isDrawer     = pv.type === 'drawer-left' || pv.type === 'drawer-right';

    var html = '<div style="width:62px;height:90px;border-radius:8px;overflow:hidden;position:relative;'
             + 'background:#e5e7eb;border:2px solid #9ca3af;box-sizing:border-box;flex-shrink:0;">';

    // Top nav bar
    html += '<div style="height:13px;background:#f9fafb;display:flex;align-items:center;'
          + 'padding:0 5px;border-bottom:1px solid #e5e7eb;flex-shrink:0;">';
    html += '<div style="width:14px;height:2px;background:#d1d5db;border-radius:1px;"></div>';
    html += '<div style="margin-left:auto;display:flex;flex-direction:column;gap:2px;">';
    html += '<div style="width:9px;height:1.5px;background:#6b7280;border-radius:1px;"></div>';
    html += '<div style="width:7px;height:1.5px;background:#6b7280;border-radius:1px;"></div>';
    html += '<div style="width:9px;height:1.5px;background:#6b7280;border-radius:1px;"></div>';
    html += '</div></div>';

    // Faint page content (always in background)
    html += '<div style="padding:4px 5px;display:flex;flex-direction:column;gap:3px;">';
    html += '<div style="height:2px;background:#d1d5db;border-radius:1px;width:85%;"></div>';
    html += '<div style="height:2px;background:#d1d5db;border-radius:1px;width:70%;"></div>';
    html += '<div style="height:2px;background:#d1d5db;border-radius:1px;width:78%;"></div>';
    html += '</div>';

    if (isFullscreen) {
        var ai = pv.align === 'center' ? 'center' : (pv.align === 'flex-end' ? 'flex-end' : 'flex-start');
        html += '<div style="position:absolute;inset:0;background:' + pv.bg + ';'
              + 'display:flex;flex-direction:column;justify-content:center;align-items:' + ai + ';'
              + 'gap:8px;padding:10px;">';
        [52, 72, 62, 46].forEach(function(w) {
            html += '<div style="height:3px;background:' + pv.text + ';border-radius:2px;width:' + w + '%;"></div>';
        });
        html += '</div>';
    } else if (isDrawer) {
        var side = pv.type === 'drawer-right' ? 'right:0' : 'left:0';
        html += '<div style="position:absolute;top:13px;left:0;right:0;bottom:0;background:rgba(0,0,0,.35);"></div>';
        html += '<div style="position:absolute;top:13px;' + side + ';bottom:0;width:68%;background:' + pv.bg + ';'
              + 'display:flex;flex-direction:column;gap:7px;padding:9px 7px;">';
        [82, 67, 76, 58].forEach(function(w) {
            html += '<div style="height:2.5px;background:' + pv.text + ';border-radius:2px;width:' + w + '%;"></div>';
        });
        html += '</div>';
    } else {
        // Dropdown
        html += '<div style="position:absolute;top:13px;left:0;right:0;background:' + pv.bg + ';'
              + 'box-shadow:0 2px 6px rgba(0,0,0,.15);'
              + 'display:flex;flex-direction:column;gap:7px;padding:8px 7px;">';
        [82, 67, 76, 58].forEach(function(w) {
            html += '<div style="height:2.5px;background:' + pv.text + ';border-radius:2px;width:' + w + '%;"></div>';
        });
        html += '</div>';
    }

    html += '</div>';
    return html;
}

function buildMobilePresetGrid() {
    var grid = document.getElementById('bm-mobile-preset-grid');
    if (!grid) return;
    grid.style.cssText = 'display:grid;grid-template-columns:repeat(3,1fr);gap:12px;';

    var typeLabels = {
        'fullscreen':   'Fullscreen',
        'drawer-left':  '◀ Drawer',
        'drawer-right': 'Drawer ▶',
        'dropdown':     'Dropdown'
    };
    var typeBadgeBg = {
        'fullscreen':   '#312e81',
        'drawer-left':  '#0c4a6e',
        'drawer-right': '#0c4a6e',
        'dropdown':     '#14532d'
    };

    grid.innerHTML = Object.keys(bmMobilePresets).map(function(k) {
        var p  = bmMobilePresets[k];
        var pv = p.preview;
        var typeLabel = typeLabels[pv.type] || pv.type;
        var badgeBg   = typeBadgeBg[pv.type] || '#374151';

        return '<div id="bm-mpc-' + k + '" onclick="menux_applyMobilePreset(\'' + k + '\')"'
            + ' style="border:2px solid #e5e7eb;border-radius:12px;overflow:hidden;cursor:pointer;'
            + 'transition:border-color .15s,box-shadow .15s;position:relative;display:flex;flex-direction:column;"'
            + ' onmouseenter="this.style.borderColor=\'#a5b4fc\';this.style.boxShadow=\'0 4px 14px rgba(99,102,241,.12)\'"'
            + ' onmouseleave="var sel=this.dataset.sel;this.style.borderColor=sel?\'#667eea\':\'#e5e7eb\';this.style.boxShadow=sel?\'0 0 0 3px rgba(102,126,234,.18)\':\'\';">'
            + '<div style="background:#f1f5f9;padding:14px 0 10px;display:flex;justify-content:center;">'
            + buildMiniPhone(pv)
            + '</div>'
            + '<div style="padding:8px 10px 12px;flex:1;display:flex;flex-direction:column;gap:5px;">'
            + '<div style="font-size:12px;font-weight:700;color:#1a1a2e;">' + p.icon + ' ' + p.title + '</div>'
            + '<div style="font-size:10px;font-weight:600;color:#fff;background:' + badgeBg + ';'
            + 'padding:2px 7px;border-radius:10px;display:inline-block;align-self:flex-start;">' + typeLabel + '</div>'
            + '</div>'
            + '<div id="bm-mpc-chk-' + k + '" style="display:none;position:absolute;top:8px;right:8px;'
            + 'background:#667eea;color:#fff;width:20px;height:20px;border-radius:50%;font-size:11px;'
            + 'align-items:center;justify-content:center;">✓</div>'
            + '</div>';
    }).join('');
}

function menux_applyMobilePreset(key) {
    if (!bmMobilePresets[key]) return;
    var p = bmMobilePresets[key].data;
    function setC(n,v){var cb=document.querySelector('input[name="menux_style_use['+n+']"]');var cp=document.querySelector('input[name="menux_style['+n+']"]');if(cb){cb.checked=(v!=='');menux_toggleColor(cb);}if(cp&&v!=='')cp.value=v;}
    function setV(n,v){var el=document.querySelector('[name="menux_style['+n+']"]');if(!el)return;if(el.type==='checkbox'){el.checked=(v==='1');}else if(el.type==='radio'){document.querySelectorAll('[name="menux_style['+n+']"]').forEach(function(r){r.checked=(r.value===v);});}else{el.value=v;}}

    setC('hamburger_color', p.hamburger_color || '');
    setC('hamburger_bg',    p.hamburger_bg    || '');
    setV('hamburger_style', p.hamburger_style);
    setV('hamburger_align', p.hamburger_align);

    setV('mobile_open_style',     p.mobile_open_style);
    setV('mobile_open_animation', p.mobile_open_animation);
    if (typeof bmToggleOpenStyle === 'function') bmToggleOpenStyle(p.mobile_open_style);

    setV('mobile_overlay_bg',      p.mobile_overlay_bg      || '#000000');
    setV('mobile_overlay_opacity', p.mobile_overlay_opacity || '0.9');
    setV('mobile_overlay_blur',    p.mobile_overlay_blur    || '0');

    setC('mobile_link_color',        p.mobile_link_color        || '');
    setC('mobile_link_hover_color',  p.mobile_link_hover_color  || '');
    setC('mobile_link_active_color', p.mobile_link_active_color || '');

    setC('close_btn_color', p.close_btn_color || '');
    setC('close_btn_bg',    p.close_btn_bg    || '');

    setV('mobile_fullscreen_align', p.mobile_fullscreen_align || 'center');
    setV('mobile_drawer_width',     p.mobile_drawer_width     || '280');
    setV('mobile_menu_pad',         p.mobile_menu_pad         || '0');
    setV('mobile_menu_shadow',      p.mobile_menu_shadow      || '0');

    menux_liveStylePreview();

    document.querySelectorAll('#bm-mobile-preset-grid > div').forEach(function(c) {
        c.dataset.sel = '';
        c.style.borderColor = '#e5e7eb';
        c.style.boxShadow   = '';
    });
    document.querySelectorAll('#bm-mobile-preset-grid [id^="bm-mpc-chk-"]').forEach(function(c) {
        c.style.display = 'none';
    });
    var card = document.getElementById('bm-mpc-' + key);
    if (card) { card.dataset.sel = '1'; card.style.borderColor = '#667eea'; card.style.boxShadow = '0 0 0 3px rgba(102,126,234,.18)'; }
    var chk = document.getElementById('bm-mpc-chk-' + key);
    if (chk) { chk.style.display = 'flex'; }
}

    function buildMobilePhonePreview() {
        var screen = document.getElementById('bm-mob-phone-screen');
        if (!screen) return;
        function gv(name) {
            var sel = document.querySelector('select[name="menux_style[' + name + ']"]');
            if (sel) return sel.value;
            var chk = document.querySelector('[name="menux_style[' + name + ']"]:checked');
            if (chk) return chk.value;
            var inp = document.querySelector('input[name="menux_style[' + name + ']"]');
            return inp ? inp.value : '';
        }
        function gc(name) {
            var cb = document.querySelector('input[name="menux_style_use[' + name + ']"]');
            var cp = document.querySelector('input[name="menux_style[' + name + ']"]');
            if (cb && !cb.checked) return '';
            return cp ? cp.value : '';
        }
        function gp(name) {
            var el = document.querySelector('input[name="menux_style[' + name + ']"]');
            return el ? el.value.trim() : '';
        }
        var openStyle = gv('mobile_open_style') || 'dropdown';
        var overlayBg = gp('mobile_overlay_bg') || '#000000';
        var overlayOp = parseFloat(gp('mobile_overlay_opacity') || '0.9');
        var hbColor   = gc('hamburger_color') || '#333333';
        var hbAlign   = gv('hamburger_align') || 'flex-end';
        var linkColor = gc('mobile_link_color') || '';
        var drawerW   = parseInt(gp('mobile_drawer_width') || '280', 10);
        var fsAlign   = gv('mobile_fullscreen_align') || 'center';
        if (!linkColor) {
            if (openStyle === 'dropdown') {
                linkColor = '#111827';
            } else {
                var rgb = typeof menux_hexToRgb === 'function' ? menux_hexToRgb(overlayBg) : null;
                var lum = rgb && typeof menux_relLuminance === 'function' ? menux_relLuminance(rgb) : 0;
                linkColor = lum > 0.45 ? '#111827' : '#ffffff';
            }
        }
        var items = ['Home', 'About', 'Services', 'Contact'];
        var html = '';
        html += '<div style="height:38px;background:#ffffff;display:flex;align-items:center;justify-content:' + hbAlign + ';padding:0 10px;flex-shrink:0;box-shadow:0 1px 0 rgba(0,0,0,.09);">';
        html += '<div style="display:flex;flex-direction:column;gap:3px;">';
        html += '<span style="display:block;width:18px;height:2px;background:' + hbColor + ';border-radius:1px;"></span>';
        html += '<span style="display:block;width:18px;height:2px;background:' + hbColor + ';border-radius:1px;"></span>';
        html += '<span style="display:block;width:13px;height:2px;background:' + hbColor + ';border-radius:1px;"></span>';
        html += '</div></div>';
        html += '<div style="flex:1;position:relative;overflow:hidden;">';
        if (openStyle === 'fullscreen') {
            html += '<div style="position:absolute;inset:0;background:' + hexToRgba(overlayBg, overlayOp) + ';display:flex;flex-direction:column;align-items:' + fsAlign + ';justify-content:center;gap:8px;padding:10px;">';
            items.forEach(function(item) { html += '<div style="font-size:11px;font-weight:600;color:' + linkColor + ';letter-spacing:.4px;">' + item + '</div>'; });
            html += '</div>';
        } else if (openStyle === 'drawer-left' || openStyle === 'drawer-right') {
            var drawerPx = Math.round(164 * Math.min(drawerW / 375, 0.82));
            var side = openStyle === 'drawer-right' ? 'right:0' : 'left:0';
            html += '<div style="position:absolute;inset:0;background:' + hexToRgba(overlayBg, Math.min(overlayOp * 0.55, 0.5)) + ';"></div>';
            html += '<div style="position:absolute;top:0;bottom:0;' + side + ';width:' + drawerPx + 'px;background:' + overlayBg + ';display:flex;flex-direction:column;padding:10px 0;">';
            items.forEach(function(item) { html += '<div style="font-size:10px;color:' + linkColor + ';padding:5px 10px;">' + item + '</div>'; });
            html += '</div>';
        } else {
            html += '<div style="background:#ffffff;box-shadow:0 3px 12px rgba(0,0,0,.13);border-radius:0 0 6px 6px;">';
            items.forEach(function(item) { html += '<div style="font-size:10px;color:' + linkColor + ';padding:6px 10px;border-bottom:1px solid #f3f4f6;">' + item + '</div>'; });
            html += '</div>';
        }
        html += '</div>';
        screen.innerHTML = html;
    }

    // ── Theme application (used by inline Themes tab and setup wizard) ──
    function menux_applyTheme(key) {
        if (!bmThemes[key]) return;
        var p = bmThemes[key].data;
        function setC(n,v){var cb=document.querySelector('input[name="menux_style_use['+n+']"]');var cp=document.querySelector('input[name="menux_style['+n+']"]');if(cb){cb.checked=(v!=='');menux_toggleColor(cb);}if(cp&&v!=='')cp.value=v;}
        function setV(n,v){var el=document.querySelector('[name="menux_style['+n+']"]');if(!el)return;if(el.type==='checkbox'){el.checked=(v==='1');}else if(el.type==='radio'){document.querySelectorAll('[name="menux_style['+n+']"]').forEach(function(r){r.checked=(r.value===v);});}else{el.value=v;}}
        setC('container_bg',p.container_bg);setC('container_border',p.container_border);
        setC('link_color',p.link_color);setC('link_hover_color',p.link_hover_color);setC('link_hover_bg',p.link_hover_bg);
        setC('link_active_color',p.link_active_color);setC('link_active_border',p.link_active_border);setC('link_active_bg',p.link_active_bg);
        setC('hamburger_color',p.hamburger_color);setC('hamburger_bg',p.hamburger_bg);
        setC('last_item_color',p.last_item_color);setC('last_item_hover_color',p.last_item_hover_color);setC('last_item_bg',p.last_item_bg);
        setC('close_btn_color',p.close_btn_color||'');setC('close_btn_bg',p.close_btn_bg||'');
        setV('font_size',p.font_size);setV('font_weight',p.font_weight);setV('gap',p.gap);
        setV('padding_x',p.padding_x);setV('padding_y',p.padding_y);
        setV('hamburger_style',p.hamburger_style);setV('hamburger_align',p.hamburger_align);
        setV('mobile_menu_pad',p.mobile_menu_pad);setV('mobile_menu_shadow',p.mobile_menu_shadow);
        setV('font_family',p.font_family);setV('google_font',p.google_font);
        setV('push_last_item',p.push_last_item);
        setV('link_animation',p.link_animation);setV('link_transition',p.link_transition);
        setV('text_transform',p.text_transform);setV('letter_spacing',p.letter_spacing);
        setV('link_active_font_weight',p.link_active_font_weight);
        setV('link_border_radius',p.link_border_radius);
        if (typeof bmGP !== 'undefined') { bmGP.setFromTheme(p.container_bg_gradient||''); }
        else { setV('container_bg_gradient',p.container_bg_gradient||''); }
        setV('link_hover_bg_gradient',p.link_hover_bg_gradient||'');setV('link_active_bg_gradient',p.link_active_bg_gradient||'');
        setV('mobile_open_style',p.mobile_open_style||'dropdown');setV('mobile_open_animation',p.mobile_open_animation||'fade');
        setV('entrance_animation',p.entrance_animation||'none');setV('entrance_duration',p.entrance_duration||'0.5');
        setV('submenu_animation',p.submenu_animation||'fade');setV('submenu_shadow',p.submenu_shadow||'0');
        setV('dark_mode',p.dark_mode||'light');setV('nav_justify',p.nav_justify||'flex-start');
        setC('submenu_bg',p.submenu_bg||'');setC('submenu_border',p.submenu_border||'');setC('submenu_link_color',p.submenu_link_color||'');
        if (typeof menuxFontPicker !== 'undefined') { menuxFontPicker.syncFromInput(true); }
        menux_liveStylePreview();
    }

    // ── Theme categories + filter chips ───────────────────────────────
    var bmThemeCats = [
        { key: 'all',       label: '✨ All' },
        { key: 'dark',      label: '🌙 Dark' },
        { key: 'minimal',   label: '⚪ Minimal' },
        { key: 'vibrant',   label: '🌈 Vibrant' },
        { key: 'creative',  label: '🎨 Creative' },
        { key: 'corporate', label: '💼 Corporate' },
        { key: 'nature',    label: '🌿 Nature' },
        { key: 'elegant',   label: '💎 Elegant' },
        { key: 'retro',     label: '📼 Retro' },
        { key: 'glass',     label: '🧊 Glass' },
        { key: 'playful',   label: '🎈 Playful' }
    ];
    var bmActiveThemeCat = 'all';

    function buildThemeFilters() {
        var bar = document.getElementById('bm-theme-filters');
        if (!bar) return;
        var counts = {};
        Object.keys(bmThemes).forEach(function(k) {
            var c = bmThemes[k].cat || 'other';
            counts[c] = (counts[c] || 0) + 1;
        });
        bar.innerHTML = bmThemeCats.filter(function(cat) {
            return cat.key === 'all' || counts[cat.key];
        }).map(function(cat) {
            var active = cat.key === bmActiveThemeCat;
            var n = cat.key === 'all' ? Object.keys(bmThemes).length : (counts[cat.key] || 0);
            return '<button type="button" data-cat="' + cat.key + '" onclick="menux_filterThemes(\'' + cat.key + '\')"'
                + ' style="border:1px solid ' + (active ? '#667eea' : '#e5e7eb') + ';'
                + 'background:' + (active ? '#667eea' : '#fff') + ';color:' + (active ? '#fff' : '#475569') + ';'
                + 'padding:6px 13px;border-radius:18px;font-size:12px;font-weight:600;cursor:pointer;'
                + 'transition:all .15s;white-space:nowrap;display:inline-flex;align-items:center;gap:5px;">'
                + cat.label + '<span style="opacity:.65;font-weight:700;">' + n + '</span></button>';
        }).join('');
    }

    function menux_filterThemes(cat) {
        bmActiveThemeCat = cat;
        buildInlineThemeGrid();
    }

    // ── Inline theme grid (Themes tab in style panel) ─────────────────
    function buildInlineThemeGrid() {
        buildThemeFilters();
        var grid = document.getElementById('bm-inline-theme-grid');
        if (!grid) return;
        var keys = Object.keys(bmThemes).filter(function(k) {
            return bmActiveThemeCat === 'all' || (bmThemes[k].cat || '') === bmActiveThemeCat;
        });
        grid.innerHTML = keys.map(function(k) {
            var t = bmThemes[k];
            var strip = t.colors.map(function(c) {
                return '<div style="flex:1;background:' + c + ';height:100%;"></div>';
            }).join('');
            return '<div id="bm-itc-' + k + '" onclick="menux_applyInlineTheme(\'' + k + '\')"'
                + ' style="border:2px solid #e5e7eb;border-radius:10px;overflow:hidden;cursor:pointer;transition:border-color .15s,box-shadow .15s;position:relative;display:flex;flex-direction:column;"'
                + ' onmouseenter="this.style.borderColor=\'#a5b4fc\';this.style.boxShadow=\'0 4px 14px rgba(99,102,241,.12)\'"'
                + ' onmouseleave="var sel=this.dataset.sel;this.style.borderColor=sel?\'#667eea\':\'#e5e7eb\';this.style.boxShadow=sel?\'0 0 0 3px rgba(102,126,234,.18)\':\'\';">'
                + '<div style="height:10px;display:flex;overflow:hidden;flex-shrink:0;">' + strip + '</div>'
                + '<div style="padding:10px 12px 12px;flex:1;display:flex;flex-direction:column;">'
                + '<div style="font-size:13px;font-weight:700;color:#1a1a2e;margin-bottom:8px;flex:1;">' + t.title + '</div>'
                + '<div style="font-size:10px;background:#f1f5f9;color:#64748b;padding:2px 7px;border-radius:10px;display:inline-block;align-self:flex-start;">' + t.badge + '</div>'
                + '</div>'
                + '<div id="bm-itc-chk-' + k + '" style="display:none;position:absolute;top:8px;right:8px;background:#667eea;color:#fff;width:20px;height:20px;border-radius:50%;font-size:12px;align-items:center;justify-content:center;">✓</div>'
                + '</div>';
        }).join('');
    }

    function menux_applyInlineTheme(key) {
        menux_applyTheme(key);
        // Clear all selections
        document.querySelectorAll('#bm-inline-theme-grid > div').forEach(function(c) {
            c.dataset.sel = '';
            c.style.borderColor = '#e5e7eb';
            c.style.boxShadow = '';
        });
        document.querySelectorAll('#bm-inline-theme-grid [id^="bm-itc-chk-"]').forEach(function(c) {
            c.style.display = 'none';
        });
        // Mark selected
        var card = document.getElementById('bm-itc-' + key);
        if (card) {
            card.dataset.sel = '1';
            card.style.borderColor = '#667eea';
            card.style.boxShadow = '0 0 0 3px rgba(102,126,234,.18)';
        }
        var chk = document.getElementById('bm-itc-chk-' + key);
        if (chk) { chk.style.display = 'flex'; }
        // Sync top-bar badge
        var badge = document.getElementById('bm-active-theme-badge');
        if (badge) { badge.textContent = '🎨 ' + bmThemes[key].title; badge.style.display = 'inline-block'; }
        // Scroll to live preview
        var preview = document.getElementById('menux-preview-wrap');
        if (preview) preview.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function menux_applyPreset(presetKey) { menux_applyTheme(presetKey); }

    /* ================================================================
       GRADIENT PICKER  (container_bg_gradient)
       Visual two-stop gradient builder — no CSS typing needed.
    ================================================================ */
    window.bmGP = (function() {
        var _type  = 'linear';
        var _angle = 135;
        var _c1    = '#667eea';
        var _c2    = '#764ba2';

        var DIRS = [
            { label:'↖', angle:315 }, { label:'↑', angle:0   }, { label:'↗', angle:45  },
            { label:'←', angle:270 }, { label:null, angle:null }, { label:'→', angle:90  },
            { label:'↙', angle:225 }, { label:'↓', angle:180  }, { label:'↘', angle:135 }
        ];

        function _css() {
            if (_type === 'radial') return 'radial-gradient(circle, ' + _c1 + ', ' + _c2 + ')';
            return 'linear-gradient(' + _angle + 'deg, ' + _c1 + ', ' + _c2 + ')';
        }

        function _apply() {
            var css = _css();
            var inp = document.getElementById('bm-container-bg-gradient');
            if (inp) inp.value = css;
            _refresh(css);
            menux_liveStylePreview();
        }

        function _refresh(css) {
            var strip = document.getElementById('bm-gp-strip');
            if (strip) strip.style.background = css || '';
            _updateDirBtns();
            var lbl = document.getElementById('bm-gp-angle-lbl');
            if (lbl) lbl.textContent = _angle + '°';
            var slider = document.getElementById('bm-gp-angle-range');
            if (slider) slider.value = _angle;
        }

        function _updateDirBtns() {
            document.querySelectorAll('.bm-gp-dir-btn').forEach(function(b) {
                b.classList.toggle('active', parseInt(b.dataset.angle) === _angle);
            });
        }

        function _checkerboard() {
            return 'repeating-linear-gradient(45deg,#f3f4f6 0,#f3f4f6 4px,#fff 4px,#fff 8px)';
        }

        function render() {
            var wrap = document.getElementById('bm-gp-widget');
            if (!wrap) return;

            // Parse saved value if any
            var saved = (wrap.dataset.value || '').trim();
            if (saved) _parse(saved);

            var dirHtml = DIRS.map(function(d) {
                if (!d.label) return '<div class="bm-gp-dir-center"><div class="bm-gp-dir-dot"></div></div>';
                return '<button type="button" class="bm-gp-dir-btn" data-angle="' + d.angle + '" title="' + d.angle + '°">' + d.label + '</button>';
            }).join('');

            var css = saved || _css();
            wrap.innerHTML =
                '<div id="bm-gp-strip" style="background:' + (saved || _checkerboard()) + '"></div>'
                + '<div class="bm-gp-controls">'
                +   '<div class="bm-gp-type-row">'
                +     '<button type="button" class="bm-gp-type-btn' + (_type==='linear'?' active':'') + '" data-t="linear">Linear</button>'
                +     '<button type="button" class="bm-gp-type-btn' + (_type==='radial'?' active':'') + '" data-t="radial">Radial</button>'
                +     '<button type="button" class="bm-gp-clear-btn" title="Remove gradient">&times; Clear</button>'
                +   '</div>'
                +   '<div class="bm-gp-main">'
                +     '<div class="bm-gp-colors">'
                +       '<div class="bm-gp-stop"><label>Start</label><input type="color" id="bm-gp-c1" value="' + _c1 + '"></div>'
                +       '<div class="bm-gp-stop"><label>End</label><input type="color" id="bm-gp-c2" value="' + _c2 + '"></div>'
                +     '</div>'
                +     '<div class="bm-gp-dir-col" id="bm-gp-dir-col">'
                +       '<div class="bm-gp-dir-label">Direction</div>'
                +       '<div class="bm-gp-compass">' + dirHtml + '</div>'
                +       '<div class="bm-gp-angle-row">'
                +         '<input type="range" id="bm-gp-angle-range" min="0" max="360" value="' + _angle + '">'
                +         '<span id="bm-gp-angle-lbl">' + _angle + '°</span>'
                +       '</div>'
                +     '</div>'
                +   '</div>'
                + '</div>';

            // Events
            document.getElementById('bm-gp-c1').addEventListener('input', function() { _c1 = this.value; _apply(); });
            document.getElementById('bm-gp-c2').addEventListener('input', function() { _c2 = this.value; _apply(); });

            document.getElementById('bm-gp-angle-range').addEventListener('input', function() {
                _angle = parseInt(this.value);
                _apply();
            });

            wrap.querySelectorAll('.bm-gp-type-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    _type = this.dataset.t;
                    wrap.querySelectorAll('.bm-gp-type-btn').forEach(function(b){ b.classList.remove('active'); });
                    this.classList.add('active');
                    var dirCol = document.getElementById('bm-gp-dir-col');
                    if (dirCol) dirCol.style.display = _type === 'radial' ? 'none' : '';
                    _apply();
                });
            });

            wrap.querySelector('.bm-gp-clear-btn').addEventListener('click', function() {
                var inp = document.getElementById('bm-container-bg-gradient');
                if (inp) inp.value = '';
                var strip = document.getElementById('bm-gp-strip');
                if (strip) strip.style.background = _checkerboard();
                menux_liveStylePreview();
            });

            wrap.querySelectorAll('.bm-gp-dir-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    _angle = parseInt(this.dataset.angle);
                    _apply();
                });
            });

            _updateDirBtns();
            if (_type === 'radial') {
                var dc = document.getElementById('bm-gp-dir-col');
                if (dc) dc.style.display = 'none';
            }
        }

        function _parse(css) {
            var lm = css.match(/linear-gradient\(\s*(\d+)deg\s*,\s*(#[0-9a-fA-F]{3,6}|[a-z]+)\s*,\s*(#[0-9a-fA-F]{3,6}|[a-z]+)/);
            if (lm) { _type='linear'; _angle=parseInt(lm[1]); _c1=lm[2]; _c2=lm[3]; return; }
            var rm = css.match(/radial-gradient\([^,]+,\s*(#[0-9a-fA-F]{3,6}|[a-z]+)\s*,\s*(#[0-9a-fA-F]{3,6}|[a-z]+)/);
            if (rm) { _type='radial'; _c1=rm[1]; _c2=rm[2]; }
        }

        // Called by applyTheme() when a preset sets the gradient
        function setFromTheme(css) {
            var inp = document.getElementById('bm-container-bg-gradient');
            if (inp) inp.value = css || '';
            if (css) { _parse(css); }
            var strip = document.getElementById('bm-gp-strip');
            if (strip) strip.style.background = css || _checkerboard();
            if (css) {
                var c1inp = document.getElementById('bm-gp-c1');
                var c2inp = document.getElementById('bm-gp-c2');
                var slider = document.getElementById('bm-gp-angle-range');
                if (c1inp) c1inp.value = _c1;
                if (c2inp) c2inp.value = _c2;
                if (slider) slider.value = _angle;
                _updateDirBtns();
            }
        }

        document.addEventListener('DOMContentLoaded', render);
        return { setFromTheme: setFromTheme };
    })();

    // ================================================================
    // FUNZIONI SOTTOMENU nel drag'n drop
    // ================================================================
    function menux_toggleSubmenuZone(idx) {
        var body = document.getElementById('bm-sm-body-' + idx);
        var btn  = document.getElementById('bm-sm-toggle-' + idx);
        if (!body) return;
        var open = body.style.display !== 'none';
        body.style.display = open ? 'none' : 'block';
        if (!btn) return;
        if (!open) btn.style.background = '#e0f2fe';
        else       btn.style.background = '#f0f6fc';
    }

    function menux_updateSubCount(idx) {
        var list = document.getElementById('bm-sm-list-' + idx);
        var btn  = document.getElementById('bm-sm-toggle-' + idx);
        if (!list || !btn) return;
        var count = list.querySelectorAll('li.bm-sm-item').length;
        btn.textContent = count > 0 ? count + ' sub-items ▾' : '+ Add submenu';
    }

    function menux_getSubIndex(idx) {
        var list = document.getElementById('bm-sm-list-' + idx);
        if (!list) return 0;
        return list.querySelectorAll('li.bm-sm-item').length;
    }

    function menux_buildSubItem(parentIdx, ci, type, idOrUrl, label) {
        var list = document.getElementById('bm-sm-list-' + parentIdx);
        if (!list) return;
        var li = document.createElement('li');
        li.className = 'bm-sm-item';
        li.style.cssText = 'background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:5px 8px;margin-bottom:4px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;';

        var base = 'menu_items['+parentIdx+'][children]['+ci+']';

        var inner = '<span style="font-size:16px;color:#9ca3af;cursor:move;" title="Trascina">⠿</span>';

        // Type selector
        var selPageSel = type === 'page' ? ' selected' : '';
        var selCustSel = type !== 'page' ? ' selected' : '';
        inner += '<select name="'+base+'[type]" class="bm-child-type-sel" onchange="menux_toggleChildType(this)" style="font-size:10px;height:24px;padding:1px 4px;border-radius:4px;border:1px solid #c3d4e8;color:#1d4ed8;background:#dbeafe;font-weight:600;max-width:90px;">'
            + '<option value="page"'+selPageSel+'>📄 Page</option>'
            + '<option value="custom"'+selCustSel+'>🔗 Link</option>'
            + '</select>';

        // Page select wrapper
        var pageDisplay = type === 'page' ? 'flex' : 'none';
        var pageOpts = '<option value="">-- Page --</option>';
        menux_all_pages.forEach(function(p) {
            var sel2 = (type === 'page' && String(p.id) === String(idOrUrl)) ? ' selected' : '';
            pageOpts += '<option value="'+p.id+'"'+sel2+'>'+menux_esc(p.title)+'</option>';
        });
        inner += '<div class="bm-child-page-wrap" style="display:'+pageDisplay+';align-items:center;gap:4px;">'
            + '<select name="'+base+'[id]" style="font-size:11px;height:24px;padding:1px 4px;max-width:160px;">'+pageOpts+'</select>'
            + '</div>';

        // URL wrapper
        var urlDisplay = type !== 'page' ? 'flex' : 'none';
        var urlVal = type !== 'page' ? menux_esc(idOrUrl) : '';
        inner += '<div class="bm-child-url-wrap" style="display:'+urlDisplay+';align-items:center;gap:4px;">'
            + '<input type="text" name="'+base+'[url]" value="'+urlVal+'" placeholder="https://..." style="font-size:11px;width:130px;height:24px;padding:2px 5px;">'
            + '</div>';

        // Campi lingua
        if (menux_supported_langs.length > 0) {
            menux_supported_langs.forEach(function(lang) {
                var key = 'lang_' + lang.code.replace(/-/g,'_');
                inner += '<input type="text" name="'+base+'['+key+']" value="'+menux_esc(label)+'" placeholder="'+lang.code+'" title="'+lang.label+'" style="font-size:11px;width:80px;height:24px;padding:2px 5px;">';
            });
        } else {
            inner += '<input type="text" name="'+base+'[lang_it_IT]" value="'+menux_esc(label)+'" placeholder="Label" style="font-size:11px;width:110px;height:24px;padding:2px 5px;">';
        }

        inner += '<div style="display:inline-flex;align-items:center;gap:2px;">';
        inner += '<input type="hidden" name="'+base+'[icon]" value="" class="bm-icon-input">';
        inner += '<button type="button" class="bm-icon-btn" onclick="mxIconPicker.open(this.previousElementSibling)" tabindex="-1">🎨</button>';
        inner += '</div>';
        inner += '<select name="'+base+'[target]" style="font-size:11px;height:24px;padding:1px 3px;"><option value="">= tab</option><option value="_blank">↗ nuova</option></select>';
        inner += '<button type="button" onclick="this.closest(\'li\').remove();menux_updateSubCount('+parentIdx+');" style="background:#fee2e2;border:1px solid #fca5a5;color:#dc2626;border-radius:3px;padding:1px 7px;font-size:12px;cursor:pointer;margin-left:auto;">&times;</button>';

        li.innerHTML = inner;
        list.appendChild(li);
        menux_updateSubCount(parentIdx);
    }

    function menux_esc(s) {
        return String(s||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }

    // Toggle campo pagina/URL nei sottomenu
    function menux_toggleChildType(sel) {
        var li = sel.closest('li.bm-sm-item');
        if (!li) return;
        var pageWrap = li.querySelector('.bm-child-page-wrap');
        var urlWrap  = li.querySelector('.bm-child-url-wrap');
        if (sel.value === 'page') {
            if (pageWrap) pageWrap.style.display = 'flex';
            if (urlWrap)  urlWrap.style.display  = 'none';
        } else {
            if (pageWrap) pageWrap.style.display = 'none';
            if (urlWrap)  urlWrap.style.display  = 'flex';
        }
    }

    function menux_addSubBlank(parentIdx) {
        var ci = menux_getSubIndex(parentIdx);
        menux_buildSubItem(parentIdx, ci, 'custom', '', '');
        var body = document.getElementById('bm-sm-body-'+parentIdx);
        if (body) body.style.display = 'block';
    }

    function menux_addSubPage(parentIdx) {
        var ci = menux_getSubIndex(parentIdx);
        menux_buildSubItem(parentIdx, ci, 'page', '', '');
        var body = document.getElementById('bm-sm-body-'+parentIdx);
        if (body) body.style.display = 'block';
    }

    function menux_addSubCustom(parentIdx) {
        var urlInp   = document.getElementById('bm-sm-url-'   + parentIdx);
        var labelInp = document.getElementById('bm-sm-label-' + parentIdx);
        var url   = urlInp   ? urlInp.value.trim()   : '';
        var label = labelInp ? labelInp.value.trim() : '';
        if (!url) { alert('Please enter a URL'); return; }
        var ci = menux_getSubIndex(parentIdx);
        menux_buildSubItem(parentIdx, ci, 'custom', url, label || url);
        if (urlInp)   urlInp.value   = '';
        if (labelInp) labelInp.value = '';
        var body = document.getElementById('bm-sm-body-'+parentIdx);
        if (body) body.style.display = 'block';
    }
    // ---- FINE SOTTOMENU ----

    function menux_exportConfig() {
        jQuery.post(ajaxurl, {
            action: 'menux_export_config',
            nonce: menux_export_config_nonce
        }, function(response) {
            if (!response.success) { alert('Export error.'); return; }
            var json = JSON.stringify(response.data, null, 2);
            var blob = new Blob([json], {type: 'application/json'});
            var url  = URL.createObjectURL(blob);
            var a    = document.createElement('a');
            a.href     = url;
            a.download = 'menux-config-' + new Date().toISOString().slice(0,10) + '.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }).fail(function() { alert('Communication error.'); });
    }

    function menux_importConfig(input) {
        var file = input.files[0];
        if (!file) return;
        var msg = document.getElementById('menux-import-msg');
        var reader = new FileReader();
        reader.onload = function(e) {
            var raw = e.target.result;
            // Verifica validità JSON prima di inviare
            try { JSON.parse(raw); } catch(err) {
                if (msg) { msg.style.display='inline'; msg.style.color='#d63638'; msg.textContent='❌ Invalid JSON file.'; }
                input.value = '';
                return;
            }
            if (msg) { msg.style.display='inline'; msg.style.color='#666'; msg.textContent='⏳ Importing...'; }
            // Base64-encode per evitare problemi di escaping con wp_magic_quotes
            var encoded = btoa(unescape(encodeURIComponent(raw)));
            jQuery.post(ajaxurl, {
                action: 'menux_import_config',
                nonce:  menux_import_config_nonce,
                config: encoded
            }, function(response) {
                if (response.success) {
                    var d = response.data;
                    var info = ' (' + d.items_count + ' items, URL: ' + (d.api_url || 'not set') + ')';
                    if (msg) { msg.style.display='inline'; msg.style.color='#2e7d32'; msg.textContent='✅ Imported' + info + ' — reloading...'; }
                    setTimeout(function() {
                        // Usa ajaxurl per ricavare la base dell'admin, aggiunge cache-buster
                        var adminBase = ajaxurl.replace('admin-ajax.php', 'admin.php');
                        window.location.href = adminBase + '?page=menux&_nc=' + Date.now();
                    }, 1500);
                } else {
                    if (msg) { msg.style.display='inline'; msg.style.color='#d63638'; msg.textContent='❌ ' + response.data; }
                }
            }).fail(function() {
                if (msg) { msg.style.display='inline'; msg.style.color='#d63638'; msg.textContent='❌ Communication error.'; }
            });
            input.value = '';
        };
        reader.readAsText(file);
    }

    function menux_reloadLanguages() {
        var btn = document.getElementById('menux-reload-langs-btn');
        var msg = document.getElementById('menux-reload-langs-msg');
        if (btn) { btn.disabled = true; btn.textContent = '⏳ Loading...'; }
        if (msg) { msg.style.display = 'none'; }

        jQuery.post(ajaxurl, {
            action: 'menux_reload_languages',
            nonce: menux_reload_langs_nonce
        }, function(response) {
            if (btn) { btn.disabled = false; btn.textContent = '🔄 Refresh'; }
            if (response.success && response.data) {
                menux_supported_langs = response.data;
                if (msg) {
                    msg.style.display = 'inline';
                    msg.style.color = '#2e7d32';
                    msg.textContent = '✅ Languages updated (' + response.data.length + '). Save to apply.';
                }
                // Aggiorna la visualizzazione delle lingue nella card
                var langsWrap = btn ? btn.closest('td') : null;
                if (langsWrap && response.data.length > 0) {
                    var newHtml = '<div style="display:flex; gap:8px; flex-wrap:wrap; align-items:center;">';
                    response.data.forEach(function(lang) {
                        newHtml += '<span style="background:#e8f4f8; border:1px solid #bee3f8; border-radius:3px; padding:3px 8px; font-size:12px; font-family:monospace;"><strong>' + menux_esc(lang.code) + '</strong> — ' + menux_esc(lang.label) + '</span>';
                    });
                    newHtml += '<button type="button" id="menux-reload-langs-btn" class="button button-small" onclick="menux_reloadLanguages()">🔄 Refresh</button>';
                    newHtml += '</div><span id="menux-reload-langs-msg" style="margin-left:10px; font-size:13px; color:#2e7d32;">✅ Languages updated (' + menux_esc(String(response.data.length)) + '). Save to apply.</span>';
                    langsWrap.innerHTML = newHtml;
                }
                // Aggiorna anche i campi lingua nei pannelli Aggiungi
                menux_rebuildAddPanelLangs();
            } else {
                if (msg) {
                    msg.style.display = 'inline';
                    msg.style.color = '#d63638';
                    msg.textContent = '❌ Could not retrieve languages. Check your multilingual plugin is active.';
                }
            }
        }).fail(function() {
            if (btn) { btn.disabled = false; btn.textContent = '🔄 Refresh'; }
            if (msg) {
                msg.style.display = 'inline';
                msg.style.color = '#d63638';
                msg.textContent = '❌ Server communication error.';
            }
        });
    }

    /* Ricostruisce i campi lingua nei pannelli Aggiungi dopo un reload AJAX */
    function menux_rebuildAddPanelLangs() {
        [['bm-page-lang-inputs','page-lang-'], ['bm-custom-lang-inputs','custom-lang-']].forEach(function(pair) {
            var el = document.getElementById(pair[0]);
            if (!el) return;
            el.innerHTML = '';
            menux_supported_langs.forEach(function(lang) {
                var key = 'lang_' + lang.code.replace(/-/g, '_');
                var inp = document.createElement('input');
                inp.type = 'text';
                inp.id = pair[1] + key;
                inp.placeholder = lang.code;
                inp.title = lang.label;
                inp.className = 'bm-add-lang-input';
                el.appendChild(inp);
            });
        });
    }

    function menux_reindex() {
        var list = document.getElementById('menux-sortable');
        if (!list) return;
        var rows = list.querySelectorAll('li.menux-item');
        rows.forEach(function(row, i) {
            row.querySelectorAll('input, select').forEach(function(el) {
                if (el.name) { el.name = el.name.replace(/menu_items\[\d+\]/, 'menu_items[' + i + ']'); }
            });
        });
        menux_index = rows.length;
        var emptyMsg = document.getElementById('menux-empty-msg');
        if (emptyMsg) emptyMsg.style.display = rows.length ? 'none' : 'block';
    }

    function menux_removeItem(btn) {
        var li = btn.closest('li');
        if (!li) return;
        li.remove();
        menux_reindex();
        menux_updatePreview();
    }

    // ── Import from WP native menu ──────────────────────────────────────────
    var _wpMenusLoaded = false;
    function menux_loadWpMenus() {
        var sel = document.getElementById('wp-menu-select');
        if (!sel || _wpMenusLoaded) return;
        _wpMenusLoaded = true;
        sel.innerHTML = '<option value="">-- Loading... --</option>';
        jQuery.post(ajaxurl, { action: 'menux_get_wp_menus', nonce: menux_import_wp_menu_nonce }, function(res) {
            if (!res.success || !res.data || !res.data.length) {
                sel.innerHTML = '<option value="">No WordPress menus found</option>';
                return;
            }
            sel.innerHTML = '<option value="">-- Select a WordPress menu --</option>';
            res.data.forEach(function(menu) {
                var opt = document.createElement('option');
                opt.value = menu.id;
                opt.textContent = menux_esc(menu.name) + ' (' + menu.count + ' items)';
                sel.appendChild(opt);
            });
        });
    }

    function menux_importWpMenu() {
        var sel = document.getElementById('wp-menu-select');
        if (!sel || !sel.value) { alert('Please select a WordPress menu to import.'); return; }
        var menuId   = sel.value;
        var menuName = sel.options[sel.selectedIndex].textContent;
        var existing = document.querySelectorAll('#menux-sortable > li.menux-item').length;
        if (existing > 0 && !confirm('This will replace the current ' + existing + ' item(s) with items from:\n\n"' + menuName + '"\n\nContinue?')) return;

        jQuery.post(ajaxurl, { action: 'menux_import_wp_menu', nonce: menux_import_wp_menu_nonce, menu_id: menuId }, function(res) {
            if (!res.success || !res.data || !res.data.items) { alert('Error importing menu. Please try again.'); return; }
            var items = res.data.items;
            if (!items.length) { alert('The selected menu has no items.'); return; }

            // Clear existing builder items and reset counter
            var ul = document.getElementById('menux-sortable');
            if (ul) ul.innerHTML = '';
            menux_index = 0;

            items.forEach(function(item) {
                var langValues = {};
                if (menux_supported_langs.length > 0) {
                    menux_supported_langs.forEach(function(lang) {
                        langValues['lang_' + lang.code.replace(/-/g, '_')] = item.label;
                    });
                } else {
                    langValues['lang_it_IT'] = item.label;
                }
                var rowVal = item.type === 'page' ? item.id : item.url;
                menux_buildRow(item.type, rowVal, langValues, '', item.label, { target: item.target });

                // Add sub-items
                var parentIdx = menux_index - 1;
                if (item.children && item.children.length) {
                    var smBody = document.getElementById('bm-sm-body-' + parentIdx);
                    if (smBody) smBody.style.display = 'block';
                    item.children.forEach(function(child) {
                        var ci      = menux_getSubIndex(parentIdx);
                        var childId = child.type === 'page' ? child.id : child.url;
                        menux_buildSubItem(parentIdx, ci, child.type, childId, child.label);
                    });
                }
            });

            menux_reindex();
            menux_updatePreview();
            var countEl = document.querySelector('.bm-items-count');
            if (countEl) countEl.textContent = items.length + ' items';
            alert('✅ Imported ' + items.length + ' items from "' + menuName + '".');
        });
    }
    // ────────────────────────────────────────────────────────────────────────

    function menux_addPage() {
        var sel = document.getElementById('page-select');
        if (!sel) return;
        var id = sel.value;
        if (!id) { alert('-- Select a page --'); return; }
        var title = sel.options[sel.selectedIndex].getAttribute('data-title') || '';
        sel.value = '';
        // Pre-fill all lang fields with the page title as default
        var langValues = {};
        if (menux_supported_langs.length > 0) {
            menux_supported_langs.forEach(function(lang) {
                langValues['lang_' + lang.code.replace(/-/g, '_')] = title;
            });
        } else {
            langValues['lang_it_IT'] = title;
        }
        menux_buildRow('page', id, langValues, '', title);
    }

    function menux_addCustom() {
        var urlInp  = document.getElementById('custom-url');
        var iconInp = document.getElementById('custom-icon');
        if (!urlInp) return;
        var url  = urlInp.value.trim();
        if (!url) { alert('Please enter a URL'); return; }
        var icon = iconInp ? iconInp.value.trim() : '';
        urlInp.value = '';
        if (iconInp) iconInp.value = '';
        menux_buildRow('custom', url, {}, icon, url);
    }

    function menux_buildRow(type, valOrId, langValues, icon, titleDisplay, extraData) {
        var idx = menux_index;
        var ul  = document.getElementById('menux-sortable');

        // ── helpers ──
        var mh = function(n, v) {
            var i = document.createElement('input'); i.type='hidden';
            i.name='menu_items['+idx+']['+n+']'; i.value=v; return i;
        };
        var sec = function(label) {
            var d = document.createElement('div'); d.className='bm-item-section';
            var t = document.createElement('div'); t.className='bm-item-section-title'; t.textContent=label;
            d.appendChild(t); return d;
        };

        // ── <li> ──
        var li = document.createElement('li');
        li.className = 'menux-item menux-item-open'; // new items start expanded

        // ── HEADER ──
        var hdr = document.createElement('div'); hdr.className = 'menux-item-header';
        hdr.onclick = function() { menuxToggleItem(this); };

        var drag = document.createElement('span'); drag.className='menux-drag-handle dashicons dashicons-menu'; drag.title='Drag to reorder';
        hdr.appendChild(drag);

        var titleEl = document.createElement('span'); titleEl.className='menux-item-title';
        titleEl.textContent = (type==='page' ? '📄 ' : '🔗 ') + titleDisplay;
        hdr.appendChild(titleEl);

        var metaEl = document.createElement('span'); metaEl.className='menux-item-meta';
        hdr.appendChild(metaEl);

        var chev = document.createElement('span'); chev.className='menux-item-chevron'; chev.textContent='▾';
        hdr.appendChild(chev);

        var delBtn = document.createElement('button'); delBtn.type='button'; delBtn.className='menux-item-delete'; delBtn.title='Remove'; delBtn.innerHTML='&times;';
        delBtn.onclick = function(e){ e.stopPropagation(); menux_removeItem(this); };
        hdr.appendChild(delBtn);
        li.appendChild(hdr);

        // ── BODY ──
        var body = document.createElement('div'); body.className='menux-item-body';

        // System hidden fields
        body.appendChild(mh('type', type));
        if (type==='page') body.appendChild(mh('id', valOrId)); else body.appendChild(mh('url', valOrId));
        var keyVal = (extraData&&extraData.item_key) ? extraData.item_key : (type==='page'?'page_'+valOrId:'c_'+Math.random().toString(36).substr(2,6));
        body.appendChild(mh('item_key', keyVal));

        // ── Section: Languages ──
        var secLbl = sec('🌐 Languages');
        var lblRow = document.createElement('div'); lblRow.className='bm-inputs-row'; lblRow.style.flexWrap='wrap'; lblRow.style.gap='6px';

        function makeLangField(key, val, code, labelName) {
            var lbl = document.createElement('label'); lbl.className='bm-lang-field'; lbl.title=labelName;
            var tag = document.createElement('span');  tag.className='bm-lang-code'; tag.textContent=code.toUpperCase().slice(0,2);
            var inp = document.createElement('input'); inp.type='text'; inp.name='menu_items['+idx+']['+key+']';
            inp.value=val||''; inp.placeholder=labelName; inp.className='bm-lang-input';
            lbl.appendChild(tag); lbl.appendChild(inp); return lbl;
        }

        if (menux_supported_langs.length > 0) {
            menux_supported_langs.forEach(function(lang) {
                var key='lang_'+lang.code.replace(/-/g,'_');
                var v=(langValues&&langValues[key])?langValues[key]:'';
                lblRow.appendChild(makeLangField(key, v, lang.code, lang.label));
            });
        } else {
            lblRow.appendChild(makeLangField('lang_it_IT', (langValues&&langValues.lang_it_IT)||titleDisplay||'', 'IT', 'Italiano'));
            lblRow.appendChild(makeLangField('lang_en_US', (langValues&&langValues.lang_en_US)||'', 'EN', 'English'));
        }
        secLbl.appendChild(lblRow); body.appendChild(secLbl);

        // ── Section: Icon & Badge ──
        var secIco = sec('🎨 Icon & Badge');
        var icoRow = document.createElement('div'); icoRow.className='bm-inputs-row'; icoRow.style.flexWrap='wrap';
        var icoWrap = document.createElement('div'); icoWrap.style.cssText='display:inline-flex;align-items:center;gap:5px;flex-shrink:0;';
        if (icon) { var iEl=document.createElement('i'); iEl.className='bm-icon-preview-el '+icon; iEl.style.cssText='font-size:16px;color:#374151;flex-shrink:0;'; icoWrap.appendChild(iEl); }
        var icoH=document.createElement('input'); icoH.type='hidden'; icoH.name='menu_items['+idx+'][icon]'; icoH.value=icon||''; icoH.className='bm-icon-input'; icoWrap.appendChild(icoH);
        var icoBtn=document.createElement('button'); icoBtn.type='button'; icoBtn.className='bm-icon-btn'; icoBtn.setAttribute('tabindex','-1'); icoBtn.textContent='🎨 Icon'; icoBtn.onclick=function(){mxIconPicker.open(this.previousElementSibling);}; icoWrap.appendChild(icoBtn);
        icoRow.appendChild(icoWrap);
        var bdgTxt=document.createElement('input'); bdgTxt.type='text'; bdgTxt.name='menu_items['+idx+'][badge]'; bdgTxt.value=(extraData&&extraData.badge)||''; bdgTxt.placeholder='Badge (e.g.: New, Hot)'; bdgTxt.className='bm-lang-input'; bdgTxt.style.maxWidth='110px'; bdgTxt.title='Badge text'; icoRow.appendChild(bdgTxt);
        var bdgBg=document.createElement('input'); bdgBg.type='color'; bdgBg.name='menu_items['+idx+'][badge_bg]'; bdgBg.value=(extraData&&extraData.badge_bg)||'#ef4444'; bdgBg.title='Badge color'; bdgBg.style.cssText='width:30px;height:28px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;flex-shrink:0;'; icoRow.appendChild(bdgBg);
        secIco.appendChild(icoRow); body.appendChild(secIco);

        // ── Section: Visibility & Behavior ──
        var secVis = sec('👁️ Visibility & Behavior');
        var visRow = document.createElement('div'); visRow.className='bm-inputs-row'; visRow.style.flexWrap='wrap';
        var visSel=document.createElement('select'); visSel.name='menu_items['+idx+'][visibility]'; visSel.className='menux-visibility'; visSel.innerHTML=menux_build_vis_options((extraData&&extraData.visibility)?extraData.visibility:'all'); visRow.appendChild(visSel);
        var tgtSel=document.createElement('select'); tgtSel.name='menu_items['+idx+'][target]'; tgtSel.className='bm-select bm-select-sm'; tgtSel.innerHTML='<option value="">Same tab</option><option value="_blank">↗ New tab</option>'; if(extraData&&extraData.target)tgtSel.value=extraData.target; visRow.appendChild(tgtSel);
        var locSel=document.createElement('select'); locSel.name='menu_items['+idx+'][menu_location]'; locSel.className='bm-select bm-select-sm'; locSel.title='Menu location'; locSel.innerHTML='<option value="primary">📍 Primary</option><option value="footer">📍 Footer</option><option value="sidebar">📍 Sidebar</option><option value="mobile">📍 Mobile</option>'; visRow.appendChild(locSel);
        var nLbl=document.createElement('label'); nLbl.style.cssText='display:flex;align-items:center;gap:4px;font-size:12px;color:#555;cursor:pointer;white-space:nowrap;';
        var nCb=document.createElement('input'); nCb.type='checkbox'; nCb.name='menu_items['+idx+'][notif_dot]'; nCb.value='1'; nLbl.appendChild(nCb); nLbl.appendChild(document.createTextNode('🔴 Dot')); visRow.appendChild(nLbl);
        secVis.appendChild(visRow); body.appendChild(secVis);

        // ── Section: CTA Button Style ──
        var secCta=document.createElement('div'); secCta.className='bm-item-section'; secCta.style.cssText='background:#fffbeb;border:1px dashed #fbbf24;border-radius:6px;padding:6px 10px;';
        var ctaTitle=document.createElement('div'); ctaTitle.className='bm-item-section-title'; ctaTitle.style.color='#92400e'; ctaTitle.textContent='🎯 CTA Button'; secCta.appendChild(ctaTitle);
        var ctaRow=document.createElement('div'); ctaRow.className='bm-inputs-row'; ctaRow.style.cssText='flex-wrap:wrap;gap:8px;align-items:center;';
        var ctaH=document.createElement('input'); ctaH.type='hidden'; ctaH.name='menu_items['+idx+'][cta_style]'; ctaH.value='0'; ctaH.className='bm-cta-style-h';
        var ctaOpts=document.createElement('div'); ctaOpts.className='bm-cta-opts'; ctaOpts.style.cssText='display:none;align-items:center;gap:8px;flex-wrap:wrap;';
        ctaOpts.innerHTML='<label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;">BG:<input type="color" name="menu_items['+idx+'][cta_bg]" value="#667eea" style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;"></label>'
            +'<label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;">Text:<input type="color" name="menu_items['+idx+'][cta_color]" value="#ffffff" style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;"></label>'
            +'<label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;">Hover:<input type="color" name="menu_items['+idx+'][cta_hover_bg]" value="#5a67d8" style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;"></label>'
            +'<label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;">Radius:<input type="number" name="menu_items['+idx+'][cta_border_radius]" value="6" min="0" max="50" style="width:48px;height:26px;padding:2px 4px;font-size:11px;"><span style="font-size:11px;color:#9ca3af;">px</span></label>';
        var ctaToggleLbl=document.createElement('label'); ctaToggleLbl.style.cssText='display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:#92400e;cursor:pointer;white-space:nowrap;';
        var ctaCb=document.createElement('input'); ctaCb.type='checkbox'; ctaCb.className='bm-cta-toggle'; ctaCb.value='1';
        ctaCb.addEventListener('change',function(){ ctaH.value=this.checked?'1':'0'; ctaOpts.style.display=this.checked?'flex':'none'; });
        ctaToggleLbl.appendChild(ctaCb); ctaToggleLbl.appendChild(document.createTextNode(' CTA button style'));
        ctaRow.appendChild(ctaH); ctaRow.appendChild(ctaToggleLbl); ctaRow.appendChild(ctaOpts);
        secCta.appendChild(ctaRow); body.appendChild(secCta);

        // ── Advanced (details/summary) ──
        var det=document.createElement('details'); det.className='bm-item-advanced';
        var summ=document.createElement('summary'); summ.className='bm-item-section-title'; summ.style.cssText='cursor:pointer;list-style:none;-webkit-appearance:none;'; summ.textContent='⚙️ Schedule & Conditions'; det.appendChild(summ);
        var advInner=document.createElement('div'); advInner.style.marginTop='8px';
        advInner.innerHTML='<div class="bm-inputs-row" style="flex-wrap:wrap;margin-bottom:6px;">'
            +'<label style="font-size:11px;color:#6b7280;white-space:nowrap;">📅 From:</label>'
            +'<input type="datetime-local" name="menu_items['+idx+'][schedule_start]" style="font-size:11px;height:28px;padding:2px 6px;max-width:180px;">'
            +'<label style="font-size:11px;color:#6b7280;white-space:nowrap;">to:</label>'
            +'<input type="datetime-local" name="menu_items['+idx+'][schedule_end]" style="font-size:11px;height:28px;padding:2px 6px;max-width:180px;">'
            +'</div>'
            +'<div class="bm-inputs-row" style="flex-wrap:wrap;">'
            +'<input type="text" name="menu_items['+idx+'][cond_roles]" placeholder="Roles (e.g.: editor,author)" style="font-size:11px;height:28px;padding:2px 6px;max-width:160px;">'
            +'<select name="menu_items['+idx+'][cond_devices]" style="font-size:11px;height:28px;padding:2px 4px;max-width:120px;"><option value="">📱 All devices</option><option value="mobile">📱 Mobile only</option><option value="desktop">🖥️ Desktop only</option></select>'
            +'<input type="text" name="menu_items['+idx+'][cond_time_from]" placeholder="⏰ From HH:MM" style="font-size:11px;height:28px;padding:2px 6px;max-width:80px;">'
            +'<input type="text" name="menu_items['+idx+'][cond_time_to]" placeholder="⏰ To HH:MM" style="font-size:11px;height:28px;padding:2px 6px;max-width:80px;">'
            +'<input type="text" name="menu_items['+idx+'][cond_utm]" placeholder="UTM source" style="font-size:11px;height:28px;padding:2px 6px;max-width:100px;">'
            +'<input type="text" name="menu_items['+idx+'][cond_pages]" placeholder="📄 Page IDs (e.g.: 2,15,42)" title="Show this item only on these page IDs (comma-separated). Empty = all pages." style="font-size:11px;height:28px;padding:2px 6px;max-width:160px;">'
            +'</div>';
        det.appendChild(advInner); body.appendChild(det);

        // ── Submenu zone ──
        var smZone=document.createElement('div'); smZone.className='bm-submenu-zone bm-item-section'; smZone.id='bm-sm-zone-'+idx;
        var smTitleEl=document.createElement('div'); smTitleEl.className='bm-item-section-title'; smTitleEl.textContent='📂 Submenu'; smZone.appendChild(smTitleEl);
        var smBtn=document.createElement('button'); smBtn.type='button'; smBtn.className='bm-btn bm-btn-secondary bm-btn-sm'; smBtn.id='bm-sm-toggle-'+idx; smBtn.textContent='+ Add submenu'; smBtn.setAttribute('onclick','menux_toggleSubmenuZone('+idx+')'); smZone.appendChild(smBtn);
        var smBody=document.createElement('div'); smBody.id='bm-sm-body-'+idx; smBody.style.cssText='display:none;margin-top:8px;';
        var smList=document.createElement('ul'); smList.className='bm-sm-list'; smList.id='bm-sm-list-'+idx; smList.style.cssText='list-style:none;padding:0;margin:0 0 8px;border-left:3px solid #c3d4e8;padding-left:12px;'; smBody.appendChild(smList);
        var smBar=document.createElement('div'); smBar.style.cssText='display:flex;gap:6px;align-items:center;';
        smBar.innerHTML='<button type="button" onclick="menux_addSubBlank('+idx+')" class="bm-btn bm-btn-secondary bm-btn-sm">+ Add sub-item</button><span style="font-size:11px;color:#9ca3af;">Use the type selector to choose Page or Link</span>';
        smBody.appendChild(smBar); smZone.appendChild(smBody); body.appendChild(smZone);

        li.appendChild(body);
        ul.appendChild(li);
        menux_index = idx + 1;
        menux_updatePreview();
        var emptyMsg = document.getElementById('menux-empty-msg');
        if (emptyMsg) emptyMsg.style.display = 'none';
    }

    function menux_updatePreview() {
        var items = [];
        var rows = document.querySelectorAll('#menux-sortable li.menux-item');
        rows.forEach(function(row) {
            var typeEl = row.querySelector('input[name*="[type]"]');
            var urlEl  = row.querySelector('input[name*="[url]"]');
            var iconEl = row.querySelector('input[name*="[icon]"]');
            var visEl  = row.querySelector('select[name*="[visibility]"]');
            var type = typeEl ? typeEl.value : 'custom';
            var url  = (type === 'custom' && urlEl) ? (urlEl.value || '#') : '#';
            var icon = iconEl ? iconEl.value.trim() : '';
            var vis  = visEl ? visEl.value : 'all';
            // Usa il primo campo lingua trovato come label di anteprima
            var firstLangEl = row.querySelector('input[name*="[lang_"]');
            var label = '';
            if (firstLangEl && firstLangEl.value.trim()) {
                label = firstLangEl.value.trim();
            } else if (type === 'custom' && url !== '#') {
                label = url;
            } else {
                label = 'Item';
            }
            var hasChildren = row.querySelectorAll('.bm-sm-item').length > 0;
            items.push({url: url, label: label, icon: icon, vis: vis, hasChildren: hasChildren});
        });

        var wrap = document.getElementById('menux-preview-wrap');
        if (!wrap) return;
        if (items.length === 0) {
            wrap.innerHTML = '<div style="padding:20px; text-align:center; color:#9ca3af; font-size:13px;">No menu items yet — add pages or links in <strong>Menu Structure</strong>.</div>';
            menux_liveStylePreview();
            return;
        }

        // Resolve logo URL: use PHP-injected URL (primary), fall back to thumbnail in logo panel
        var logoUrl = (typeof menux_preview_logo !== 'undefined') ? (menux_preview_logo.url || '') : '';
        if (!logoUrl) {
            var logoPreviewEl = document.getElementById('bm-logo-preview-desktop');
            if (logoPreviewEl) {
                var logoImg = logoPreviewEl.querySelector('img');
                if (logoImg) logoUrl = logoImg.getAttribute('src') || '';
            }
        }

        // Resolve logo position from checked radio, fall back to PHP-injected value
        var logoPosEl = document.querySelector('[name="menux_logo[position]"]:checked');
        var logoPos = logoPosEl ? logoPosEl.value
            : ((typeof menux_preview_logo !== 'undefined') ? (menux_preview_logo.pos || 'left') : 'left');

        var logoHtml = logoUrl
            ? '<a class="menux-logo menux-logo-desktop" href="#" onclick="return false;"><img src="' + menux_esc(logoUrl) + '" class="menux-logo-img" alt="Logo" style="max-height:48px;width:auto;display:block;"></a>'
            : '';

        var pvIndType = (document.querySelector('[name="menux_style[dropdown_indicator]"]:checked') || {}).value || 'triangle';
        var pvIndChar = pvIndType === 'chevron' ? '⌄' : pvIndType === 'dot' ? '•' : '▾';
        var ulHtml = '<ul class="menux-list" style="padding:10px;">';
        var pvSubShown = false;
        items.forEach(function(item) {
            var liClass = '';
            if (item.vis === 'auth')     liClass = 'bs-show-only-when-auth';
            if (item.vis === 'non-auth') liClass = 'bs-show-only-when-non-auth';
            var iconHtml = item.icon ? '<i class="'+menux_esc(item.icon)+'" style="margin-right:8px;"></i>' : '';
            var indHtml  = (pvIndType !== 'none' && item.hasChildren) ? '<span class="menux-indicator">'+pvIndChar+'</span>' : '';
            var subHtml  = '';
            if (pvIndType !== 'none' && item.hasChildren && !pvSubShown) {
                pvSubShown = true;
                subHtml = '<ul class="menux-sub-menu"><li><a href="#">Sub-item 1</a></li><li><a href="#">Sub-item 2</a></li><li><a href="#">Sub-item 3</a></li></ul>';
            }
            ulHtml += '<li class="' + liClass + '"><a href="' + menux_esc(item.url) + '" class="menux-link">' + iconHtml + '<span class="menux-label">' + menux_esc(item.label) + '</span>' + indHtml + '</a>' + subHtml + '</li>';
        });
        ulHtml += '</ul>';

        var hamHtml = '<div class="menux-hamburger" onclick="(function(btn){btn.classList.toggle(\'open\');var ul=btn.closest(\'.menux-container\').querySelector(\'.menux-list\');if(ul)ul.classList.toggle(\'show\');var ov=document.getElementById(\'menux-preview-overlay\');if(ov)ov.classList.toggle(\'visible\');})(this)"><span></span><span></span><span></span></div>';

        // ── Announcement bar ──
        var annEnabled = (function(){ var el = document.querySelector('[name="menux_style[announcement_enabled]"]'); return el && el.checked; })();
        var annText    = (function(){ var el = document.querySelector('[name="menux_style[announcement_text]"]'); return el ? el.value : ''; })();
        var annBg      = (function(){ var el = document.querySelector('[name="menux_style[announcement_bg]"]'); return el ? el.value : '#1d4ed8'; })();
        var annTc      = (function(){ var el = document.querySelector('[name="menux_style[announcement_text_color]"]'); return el ? el.value : '#ffffff'; })();
        var annPos     = (function(){ var el = document.querySelector('[name="menux_style[announcement_position]"]'); return el ? el.value : 'above'; })();
        var annFs      = (function(){ var el = document.querySelector('[name="menux_style[announcement_font_size]"]'); return el ? (parseInt(el.value, 10) || 13) : 13; })();
        var annPy      = (function(){ var el = document.querySelector('[name="menux_style[announcement_padding_y]"]'); return el ? (parseInt(el.value, 10) || 8) : 8; })();
        var annLink    = (function(){ var el = document.querySelector('[name="menux_style[announcement_link]"]'); var v = el ? el.value.trim() : ''; return /^javascript:/i.test(v) ? '' : v; })();
        var annCdOn    = (function(){ var el = document.querySelector('[name="menux_style[announcement_countdown_enabled]"]'); return el && el.checked; })();
        var annCdLabel = (function(){ var el = document.querySelector('[name="menux_style[announcement_countdown_label]"]'); return el ? (el.value.trim() || 'Ends in:') : 'Ends in:'; })();
        var annBarHtml = '';
        if (annEnabled && annText.trim()) {
            var annInner = annLink
                ? '<a href="' + menux_esc(annLink) + '" target="_blank" onclick="return false;" style="color:inherit;text-decoration:underline;">' + menux_esc(annText) + '</a>'
                : '<span>' + menux_esc(annText) + '</span>';
            if (annCdOn) {
                annInner += '<span style="margin-left:10px;font-weight:700;opacity:.9;white-space:nowrap;">' + menux_esc(annCdLabel) + ' <span style="font-variant-numeric:tabular-nums;letter-spacing:.04em;">12:05:30</span></span>';
            }
            annBarHtml = '<div class="menux-preview-ann" style="background:' + annBg + ';color:' + annTc + ';font-size:' + annFs + 'px;padding:' + annPy + 'px 16px;display:flex;align-items:center;justify-content:center;text-align:center;line-height:1.5;box-sizing:border-box;gap:6px;">'
                       + annInner
                       + '</div>';
        }

        // ── Search icon ──
        var srchEnabled = (function(){ var el = document.querySelector('[name="menux_style[search_enabled]"]'); return el && el.checked; })();
        var srchPos     = (function(){ var el = document.querySelector('[name="menux_style[search_position]"]:checked'); return el ? el.value : 'right'; })();
        var srchCb      = document.querySelector('input[name="menux_style_use[search_icon_color]"]');
        var srchCp      = document.querySelector('input[name="menux_style[search_icon_color]"]');
        var srchColor   = (srchCb && srchCb.checked && srchCp) ? srchCp.value : 'currentColor';
        var srchHtml    = '';
        if (srchEnabled) {
            srchHtml = '<div class="menux-search-wrap">'
                     + '<button type="button" class="menux-search-btn" onclick="return false;" style="color:' + srchColor + ';">'
                     + '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>'
                     + '</button>'
                     + '</div>';
        }

        // ── WooCommerce cart ──
        var cartEnabled   = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_enabled]"]'); return el && el.checked; })();
        var cartPos       = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_position]"]:checked'); return el ? el.value : 'right'; })();
        var cartIconVal   = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_icon]"]:checked'); return el ? el.value : 'cart'; })();
        var cartCb        = document.querySelector('input[name="menux_style_use[woo_cart_icon_color]"]');
        var cartCp        = document.querySelector('input[name="menux_style[woo_cart_icon_color]"]');
        var cartColor     = (cartCb && cartCb.checked && cartCp) ? cartCp.value : 'currentColor';
        var cartBadgeBg   = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_badge_bg]"]'); return el ? el.value : '#ef4444'; })();
        var cartShowCount = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_show_count]"]'); return el && el.checked; })();
        var cartShowTotal = (function(){ var el = document.querySelector('[name="menux_style[woo_cart_show_total]"]'); return el && el.checked; })();
        var cartIconMap   = { cart: 'fa-solid fa-cart-shopping', bag: 'fa-solid fa-bag-shopping', basket: 'fa-solid fa-basket-shopping' };
        var cartHtml      = '';
        if (cartEnabled) {
            var cartBadge = cartShowCount
                ? '<span class="menux-woo-count" style="position:absolute;top:-4px;left:18px;min-width:18px;height:18px;padding:0 5px;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;background:' + cartBadgeBg + ';color:#fff;border-radius:9px;font-size:11px;font-weight:700;line-height:1;">2</span>'
                : '';
            var cartTotal = cartShowTotal
                ? '<span class="menux-woo-total" style="font-size:13px;font-weight:600;color:' + cartColor + ';">$24.99</span>'
                : '';
            cartHtml = '<div class="menux-woo-cart-wrap">'
                     + '<div class="menux-woo-cart">'
                     + '<a class="menux-woo-cart-btn" href="#" onclick="return false;" style="color:' + cartColor + ';">'
                     + '<i class="' + menux_esc(cartIconMap[cartIconVal] || cartIconMap.cart) + '" aria-hidden="true"></i>'
                     + cartBadge
                     + cartTotal
                     + '</a>'
                     + '</div>'
                     + '</div>';
        }

        // ── Assemble nav inner HTML (mirrors frontend shortcode.php order) ──
        var leftInserts  = (srchEnabled && srchPos  === 'left'  ? srchHtml  : '')
                         + (cartEnabled && cartPos  === 'left'  ? cartHtml  : '');
        var rightInserts = (srchEnabled && srchPos  === 'right' ? srchHtml  : '')
                         + (cartEnabled && cartPos  === 'right' ? cartHtml  : '');

        var innerHtml;
        if (logoPos === 'right') {
            innerHtml = leftInserts + hamHtml + ulHtml + logoHtml + rightInserts;
        } else if (logoPos === 'center') {
            innerHtml = leftInserts + hamHtml + '<div class="menux-logo-center-wrap" style="flex:1;display:flex;justify-content:center;">' + logoHtml + '</div>' + ulHtml + rightInserts;
        } else {
            // left or center-split: logo first, then left extras, then hamburger
            innerHtml = logoHtml + leftInserts + hamHtml + ulHtml + rightInserts;
        }

        var html = (annEnabled && annText.trim() && annPos === 'above' ? annBarHtml : '')
                 + '<nav id="menux-preview-nav" class="menux-container menux-user-guest" style="width:100%; font-family:sans-serif;">' + innerHtml + '</nav>'
                 + (annEnabled && annText.trim() && annPos === 'below' ? annBarHtml : '')
                 + '<div id="menux-preview-overlay"></div>';
        wrap.innerHTML = html;
        menux_updatePreviewAuth();
        menux_liveStylePreview();
    }

    function menux_updatePreviewAuth() {
        var toggle = document.getElementById('preview-auth-toggle');
        var nav = document.getElementById('menux-preview-nav');
        if (!toggle || !nav) return;
        if (toggle.value === 'logged') { nav.classList.remove('menux-user-guest'); nav.classList.add('menux-user-logged-in'); } 
        else { nav.classList.remove('menux-user-logged-in'); nav.classList.add('menux-user-guest'); }
    }

    function menux_toggleColor(checkbox) {
        var row = checkbox.closest('.menux-color-row');
        if (!row) return;
        var picker = row.querySelector('input[type="color"]');
        if (!picker) return;
        picker.style.opacity = checkbox.checked ? '1' : '0.35';
        menux_liveStylePreview();
    }

    /* ================================================================
       GOOGLE FONT PICKER
       ================================================================ */
    window.menuxFontPicker = (function() {
        var _groups = [
            { cat: '⭐ Popular', fonts: ['Inter','Roboto','Open Sans','Lato','Montserrat','Nunito','Poppins','Raleway','Outfit','DM Sans','Plus Jakarta Sans','Figtree'] },
            { cat: 'Sans-serif', fonts: ['Barlow','Cabin','Exo 2','Fira Sans','Jost','Karla','Lexend','Manrope','Mulish','Noto Sans','PT Sans','Quicksand','Rubik','Source Sans 3','Titillium Web','Ubuntu','Work Sans'] },
            { cat: 'Serif', fonts: ['Arvo','Bitter','Cormorant Garamond','Crimson Pro','Domine','EB Garamond','Libre Baskerville','Lora','Merriweather','Noto Serif','Playfair Display','PT Serif','Spectral','Zilla Slab'] },
            { cat: 'Display', fonts: ['Abril Fatface','Anton','Bangers','Bebas Neue','Boogaloo','Fredoka','Lilita One','Lobster','Oswald','Pacifico','Righteous','Russo One','Teko'] },
            { cat: 'Handwriting', fonts: ['Architects Daughter','Caveat','Dancing Script','Gloria Hallelujah','Indie Flower','Kalam','Patrick Hand','Permanent Marker','Satisfy','Shadows Into Light'] },
            { cat: 'Monospace', fonts: ['Courier Prime','Fira Code','IBM Plex Mono','Inconsolata','JetBrains Mono','Roboto Mono','Source Code Pro','Space Mono'] },
        ];
        var _loaded = {}, _open = false, _query = '';

        function loadFont(name) {
            if (!name || _loaded[name]) return;
            _loaded[name] = true;
            var id = 'menux-gf-' + name.replace(/\s+/g, '-').toLowerCase();
            if (document.getElementById(id)) return;
            var lnk = document.createElement('link');
            lnk.id = id; lnk.rel = 'stylesheet';
            lnk.href = 'https://fonts.googleapis.com/css2?family=' + encodeURIComponent(name) + ':wght@400;700&display=swap';
            document.head.appendChild(lnk);
        }

        function getEl(id) { return document.getElementById(id); }

        function renderList() {
            var list = getEl('menux-fp-list');
            if (!list) return;
            var q = _query.toLowerCase();
            var currentVal = (getEl('menux-fp-input') || {}).value || '';
            var html = '';
            _groups.forEach(function(g) {
                var matching = g.fonts.filter(function(f) { return !q || f.toLowerCase().indexOf(q) !== -1; });
                if (!matching.length) return;
                html += '<div class="menux-fp-group-label">' + g.cat + '</div>';
                matching.forEach(function(f) {
                    var sel = (f === currentVal) ? ' selected' : '';
                    html += '<div class="menux-fp-item' + sel + '" data-font="' + f.replace(/"/g, '&quot;') + '">' + f + '</div>';
                });
            });
            list.innerHTML = html;

            if (window.IntersectionObserver) {
                var obs = new IntersectionObserver(function(entries) {
                    entries.forEach(function(e) {
                        if (e.isIntersecting) {
                            var f = e.target.dataset.font;
                            if (f) { loadFont(f); e.target.style.fontFamily = "'" + f + "',sans-serif"; }
                            obs.unobserve(e.target);
                        }
                    });
                }, { root: list, rootMargin: '80px' });
                list.querySelectorAll('.menux-fp-item').forEach(function(el) { obs.observe(el); });
            } else {
                list.querySelectorAll('.menux-fp-item').forEach(function(el) {
                    var f = el.dataset.font;
                    loadFont(f); el.style.fontFamily = "'" + f + "',sans-serif";
                });
            }

            list.onclick = function(e) {
                var item = e.target.closest('.menux-fp-item');
                if (item) select(item.dataset.font);
            };
        }

        function open() {
            var panel = getEl('menux-fp-panel'), trigger = getEl('menux-fp-trigger');
            if (!panel || !trigger) return;
            _open = true;
            panel.classList.add('open'); trigger.classList.add('open');
            renderList();
            var s = getEl('menux-fp-search');
            if (s) { s.value = ''; _query = ''; setTimeout(function() { s.focus(); }, 30); }
        }

        function close() {
            var panel = getEl('menux-fp-panel'), trigger = getEl('menux-fp-trigger');
            _open = false;
            if (panel) panel.classList.remove('open');
            if (trigger) trigger.classList.remove('open');
        }

        function toggle() { if (_open) close(); else open(); }

        function select(name) {
            var inp = getEl('menux-fp-input'), label = getEl('menux-fp-label');
            if (!inp || !label) return;
            inp.value = name;
            label.textContent = name || '— No font selected —';
            label.style.fontFamily = name ? "'" + name + "',sans-serif" : '';
            loadFont(name);
            close();
            if (typeof menux_liveStylePreview === 'function') menux_liveStylePreview();
        }

        function clear() { select(''); }

        function filter(q) { _query = q; renderList(); }

        function syncFromInput(silent) {
            var inp = getEl('menux-fp-input'), label = getEl('menux-fp-label');
            if (!inp || !label) return;
            var v = inp.value || '';
            label.textContent = v || '— No font selected —';
            label.style.fontFamily = v ? "'" + v + "',sans-serif" : '';
            if (v) loadFont(v);
            if (!silent && typeof menux_liveStylePreview === 'function') menux_liveStylePreview();
        }

        document.addEventListener('click', function(e) {
            if (!_open) return;
            var wrap = document.querySelector('.menux-fp-wrap');
            if (wrap && !wrap.contains(e.target)) close();
        });

        document.addEventListener('DOMContentLoaded', function() { syncFromInput(true); });

        return { toggle: toggle, open: open, close: close, select: select, clear: clear, filter: filter, syncFromInput: syncFromInput, loadFont: loadFont };
    })();

    function hexToRgba(hex, alpha) {
        hex = hex.replace('#','');
        if (hex.length === 3) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
        return 'rgba('+parseInt(hex.substring(0,2),16)+','+parseInt(hex.substring(2,4),16)+','+parseInt(hex.substring(4,6),16)+','+parseFloat(alpha)+')';
    }

    function menux_liveStylePreview() {
        function color(field) {
            var cb = document.querySelector('input[name="menux_style_use[' + field + ']"]');
            var cp = document.querySelector('input[name="menux_style[' + field + ']"]');
            return (cb && cb.checked && cp) ? cp.value : '';
        }
        function val(field) {
            var el = document.querySelector('[name="menux_style[' + field + ']"]');
            return el ? el.value.trim() : '';
        }
        function isChecked(field) {
            var el = document.querySelector('[name="menux_style[' + field + ']"]');
            return el ? el.checked : false;
        }

        var css = '';

        // ── Container base layout (mirrors .menux-container from frontend CSS) ──
        var cbg = color('container_bg'), cborder = color('container_border');
        var cbgGradient = val('container_bg_gradient');
        var px = val('padding_x') || '0', py = val('padding_y') || '12';
        css += '#menux-preview-nav{';
        css += 'display:flex;flex-direction:row;align-items:center;flex-wrap:nowrap;';
        css += 'padding:' + py + 'px ' + Math.max(parseInt(px)||0, 12) + 'px;';
        if (cbgGradient)    css += 'background:' + cbgGradient + ';';
        else if (cbg)       css += 'background:' + cbg + ';';
        if (cborder)        css += 'border-bottom:1px solid ' + cborder + ';';
        var cbr = val('container_border_radius');
        if (cbr)            css += 'border-radius:' + parseInt(cbr) + 'px;';
        css += '}';

        // ── Nav list ──
        var gap = val('gap') || '20';
        var navJustify = val('nav_justify') || 'flex-start';
        css += '#menux-preview-nav .menux-list{display:flex;list-style:none;margin:0;flex:1;flex-wrap:wrap;gap:' + gap + 'px;justify-content:' + navJustify + ';}';
        css += '#menux-preview-nav .menux-list li{list-style:none;}';
        css += '#menux-preview-nav .menux-hamburger{display:none;}';

        // Entrance animation keyframes in preview
        var entAnim = (function(){ var el = document.querySelector('[name="menux_style[entrance_animation]"]:checked'); return el ? el.value : 'none'; })();
        var entDur  = val('entrance_duration') || '0.5';
        var entDel  = val('entrance_delay')    || '0';
        var entStag = parseFloat(val('entrance_stagger') || '0');
        if (entAnim !== 'none') {
            css += '@keyframes bm-entrance-fadeIn{from{opacity:0}to{opacity:1}}';
            css += '@keyframes bm-entrance-slideDown{from{opacity:0;transform:translateY(-24px)}to{opacity:1;transform:translateY(0)}}';
            css += '@keyframes bm-entrance-slideUp{from{opacity:0;transform:translateY(24px)}to{opacity:1;transform:translateY(0)}}';
            css += '@keyframes bm-entrance-slideLeft{from{opacity:0;transform:translateX(24px)}to{opacity:1;transform:translateX(0)}}';
            css += '@keyframes bm-entrance-slideRight{from{opacity:0;transform:translateX(-24px)}to{opacity:1;transform:translateX(0)}}';
            css += '@keyframes bm-entrance-zoomIn{from{opacity:0;transform:scale(0.85)}to{opacity:1;transform:scale(1)}}';
            css += '@keyframes bm-entrance-flipX{from{opacity:0;transform:perspective(400px) rotateX(-60deg)}to{opacity:1;transform:perspective(400px) rotateX(0)}}';
            if (entStag > 0) {
                document.querySelectorAll('#menux-preview-nav .menux-list > li').forEach(function(li, i) {
                    li.style.animation = 'bm-entrance-' + entAnim + ' ' + entDur + 's ease both ' + (parseFloat(entDel) + i * entStag) + 's';
                });
            } else {
                css += '#menux-preview-nav{animation:bm-entrance-'+entAnim+' '+entDur+'s ease both '+entDel+'s;}';
            }
        }

        // Stile Voci di Menu
        var lc = color('link_color'), fs = val('font_size'), fw = val('font_weight');
        var px = val('padding_x') || '0', py = val('padding_y') || '0';
        var br = val('link_border_radius');
        var lr = 'text-decoration:none; display:inline-flex; align-items:center; font-weight:bold; color:#333; transition:0.3s;';
        if (lc) lr += 'color:' + lc + ' !important;';
        if (fs) lr += 'font-size:' + fs + 'px;';
        if (fw) lr += 'font-weight:' + fw + ' !important;';
        if (parseInt(px) || parseInt(py)) lr += 'padding:' + py + 'px ' + px + 'px !important;';
        else lr += 'padding:8px 12px;';
        if (br !== '') lr += 'border-radius:' + br + 'px;';
        var gf = val('google_font'), ff = val('font_family');
        var tt = val('text_transform'), ls = val('letter_spacing');
        var ff_css = gf ? "'" + gf + "'," + (ff || 'sans-serif') : ff;
        if (ff_css) lr += 'font-family:' + ff_css + ';';
        if (tt && tt !== 'none') lr += 'text-transform:' + tt + ';';
        if (ls !== '') lr += 'letter-spacing:' + ls + 'px;';
        css += '#menux-preview-nav .menux-list li a.menux-link{' + lr + '}';

        // Hover / Active
        var hc = color('link_hover_color'), hbg = val('link_hover_bg_gradient') || color('link_hover_bg');
        var ac = color('link_active_color'), ab = color('link_active_border');
        var abg = val('link_active_bg_gradient') || color('link_active_bg');
        var afw = val('link_active_font_weight');
        // Link animation (mirrors css-generator.php link hover effects)
        var linkAnim = val('link_animation') || 'none';
        var linkTrans = val('link_transition') || '0.3';
        css += '#menux-preview-nav .menux-list li a.menux-link{transition:all ' + linkTrans + 's ease;}';
        var animHoverExtra = '';
        if (linkAnim === 'underline') {
            css += '#menux-preview-nav .menux-list li a.menux-link{border-bottom:2px solid transparent;}';
            animHoverExtra += 'border-bottom-color:currentColor !important;';
        } else if (linkAnim === 'lift') {
            animHoverExtra += 'transform:translateY(-3px);';
        } else if (linkAnim === 'scale') {
            animHoverExtra += 'transform:scale(1.1);';
        } else if (linkAnim === 'border-left') {
            css += '#menux-preview-nav .menux-list li a.menux-link{border-left:3px solid transparent;padding-left:' + (parseInt(px)||12) + 'px;}';
            animHoverExtra += 'border-left-color:currentColor !important;';
        }

        var hoverCss = animHoverExtra;
        if (hc)  hoverCss += 'color:' + hc + ' !important;';
        if (hbg) hoverCss += 'background:' + hbg + ' !important;';
        if (hoverCss) css += '#menux-preview-nav .menux-list li a.menux-link:hover{' + hoverCss + '}';
        if (ac || ab || abg || afw) {
            css += '#menux-preview-nav .menux-list li a.menux-link.active{';
            if (ac)  css += 'color:' + ac + ' !important;';
            if (ab)  css += 'border-bottom:2px solid ' + ab + ';';
            if (abg) css += 'background:' + abg + ' !important;';
            if (afw) css += 'font-weight:' + afw + ' !important;';
            css += '}';
        }

        // Hamburger Stile Predefinito
        var hstyle = val('hamburger_style') || 'classic';
        var h_gap = '5px', h_height = '3px', h_radius = '3px', h_width = '30px';
        if(hstyle === 'modern') { h_height = '4px'; h_radius = '10px'; h_gap = '6px'; }
        else if(hstyle === 'minimal') { h_height = '2px'; h_radius = '0px'; h_gap = '7px'; h_width = '35px'; }

        var halign = val('hamburger_align') || 'flex-end';
        var hbg = color('hamburger_bg');
        var h_bg_css = hbg ? 'background:'+hbg+'; border-radius:4px;' : '';
        var h_margin = halign === 'flex-start' ? 'margin-right:auto;' : (halign === 'center' ? 'margin-left:auto;margin-right:auto;' : 'margin-left:auto;');
        css += '#menux-preview-nav .menux-hamburger {cursor:pointer; padding:12px; flex-direction:column; gap:'+h_gap+'; width:'+h_width+'; box-sizing:content-box; ' + h_margin + h_bg_css + '}';
        
        var hcolor = color('hamburger_color') || '#333333';
        css += '#menux-preview-nav .menux-hamburger span {height:'+h_height+'; background:'+hcolor+'; width:100%; display:block; transition:all 0.3s ease-in-out; border-radius:'+h_radius+';}';
        
        // Animazione Preview Hamburger
        css += '#menux-preview-nav .menux-hamburger.open span:nth-child(1) { transform: translateY(calc('+h_gap+' + '+h_height+')) rotate(45deg); }';
        css += '#menux-preview-nav .menux-hamburger.open span:nth-child(2) { opacity: 0; }';
        css += '#menux-preview-nav .menux-hamburger.open span:nth-child(3) { transform: translateY(calc(-'+h_gap+' - '+h_height+')) rotate(-45deg); }';

        // Breakpoint per anteprima live
        var bp = val('mobile_breakpoint') || '768';
        var bpMode = (function(){ var el = document.querySelector('[name="menux_style[mobile_breakpoint_mode]"]:checked'); return el ? el.value : 'manual'; })();
        var m_pad = val('mobile_menu_pad') || '0';
        var m_shad = isChecked('mobile_menu_shadow') ? 'box-shadow: 0 4px 12px rgba(0,0,0,0.1);' : '';
        var openStyle = (function(){ var el = document.querySelector('[name="menux_style[mobile_open_style]"]:checked'); return el ? el.value : 'dropdown'; })();
        var ovBg = val('mobile_overlay_bg') || '#000000';
        var ovOp = val('mobile_overlay_opacity') || '0.5';
        var fsAlign = val('mobile_fullscreen_align') || 'center';
        var drawerW = val('mobile_drawer_width') || '280';
        var ovBlur  = parseInt(val('mobile_overlay_blur') || '0', 10);

        // Device-aware preview: force mobile styles when tablet/mobile device is active
        var activeDevice = window._bmPreviewDevice || 'desktop';
        var effectiveBp = (activeDevice === 'mobile') ? 99999
                        : (activeDevice === 'tablet') ? 99999
                        : bp;
        var mediaWrap = '@media(max-width:'+effectiveBp+'px){';

        css += mediaWrap;
        css += '  #menux-preview-nav { display: flex; flex-direction: row; align-items:center; flex-wrap:wrap; }';
        css += '  #menux-preview-nav .menux-hamburger { display:flex; }';

        if (openStyle === 'dropdown') {
            css += '  #menux-preview-nav .menux-list { display:none; flex-direction:column; width:100%; box-sizing:border-box; gap:0; padding:'+m_pad+'px; '+m_shad+' }';
            css += '  #menux-preview-nav .menux-list.show { display:flex; animation: bm-fadeIn .3s ease both; }';
            css += '  #menux-preview-nav .menux-list li { width: 100%; text-align: center; border-bottom: 1px solid rgba(0,0,0,0.05); }';
            css += '  #menux-preview-nav .menux-list li:last-child { border-bottom: none; }';
            css += '  #menux-preview-nav .menux-list li a.menux-link { padding: 15px !important; display:flex; justify-content:center; width:100%; box-sizing:border-box; }';
        } else if (openStyle === 'fullscreen') {
            css += '  #menux-preview-wrap { min-height: 360px; }';
            css += '  #menux-preview-nav .menux-hamburger { position:relative; z-index:100; }';
            css += '  #menux-preview-nav .menux-hamburger.open { display:none !important; }';
            css += '  #menux-preview-nav .menux-list { display:none; position:absolute; inset:0; z-index:99; flex-direction:column; align-items:'+fsAlign+'; justify-content:center; padding:60px 20px 20px; box-sizing:border-box; background:'+hexToRgba(ovBg,ovOp)+'; overflow-y:auto;'+(ovBlur?' backdrop-filter:blur('+ovBlur+'px);':'')+' }';
            css += '  #menux-preview-nav .menux-list.show { display:flex; animation: bm-fadeIn .3s ease both; }';
            css += '  #menux-preview-nav .menux-list li { width:100%; text-align:'+(fsAlign==='center'?'center':fsAlign==='flex-end'?'right':'left')+'; border-bottom:none; }';
            css += '  #menux-preview-nav .menux-list li a.menux-link { padding:16px 32px !important; font-size:clamp(20px,4vw,32px) !important; font-weight:700 !important; display:flex; justify-content:'+fsAlign+'; }';
        } else if (openStyle === 'drawer-left' || openStyle === 'drawer-right') {
            var isRight = openStyle === 'drawer-right';
            var side = isRight ? 'right:0;' : 'left:0;';
            css += '  #menux-preview-wrap { min-height: 360px; }';
            css += '  #menux-preview-nav .menux-hamburger { position:relative; z-index:100; }';
            css += '  #menux-preview-nav .menux-hamburger.open { display:none !important; }';
            css += '  #menux-preview-nav .menux-list { display:none; position:absolute; top:0; bottom:0; '+side+' width:min('+drawerW+'px,90%); z-index:99; flex-direction:column; align-items:flex-start; justify-content:flex-start; padding:64px 0 24px; box-sizing:border-box; background:'+ovBg+'; box-shadow:'+(isRight?'-4px':' 4px')+' 0 24px rgba(0,0,0,.2); overflow-y:auto;'+(ovBlur?' backdrop-filter:blur('+ovBlur+'px);':'')+' }';
            css += '  #menux-preview-nav .menux-list.show { display:flex; animation:'+(isRight?'bm-slideRight':'bm-slideLeft')+' .3s ease both; }';
            css += '  #menux-preview-nav .menux-list li { width:100%; border-bottom:1px solid rgba(128,128,128,.1); }';
            css += '  #menux-preview-nav .menux-list li a.menux-link { padding:14px 24px !important; display:flex; justify-content:flex-start; font-size:15px !important; }';
        }
        css += '}';

        // ── Dropdown indicator CSS ──
        var indType  = (function(){var el=document.querySelector('[name="menux_style[dropdown_indicator]"]:checked');return el?el.value:'triangle';})();
        var indColor = color('dropdown_indicator_color') || 'currentColor';
        var indSize  = parseInt(val('dropdown_indicator_size') || '10', 10);
        var indRot   = isChecked('dropdown_indicator_rotate');
        css += '#menux-preview-nav .menux-list > li{position:relative;}';
        if (indType !== 'none') {
            css += '#menux-preview-nav .menux-indicator{display:inline-flex;align-items:center;margin-left:4px;font-size:'+indSize+'px;line-height:1;color:'+indColor+';'+(indRot?'transition:transform .25s ease;':'')+'}';
            if (indRot) css += '#menux-preview-nav li.open .menux-indicator{transform:rotate(180deg);}';
        }

        // ── Submenu CSS ──
        var subBg        = color('submenu_bg');
        var subBorder    = color('submenu_border');
        var subLinkColor = color('submenu_link_color');
        var subHoverBg   = color('submenu_hover_bg');
        var subHoverLc   = color('submenu_hover_link_color');
        var subShadow    = isChecked('submenu_shadow');
        var subBr        = parseInt(val('submenu_border_radius') || '10', 10);
        var subPx        = parseInt(val('submenu_padding_x')     || '16', 10);
        var subPy        = parseInt(val('submenu_padding_y')     || '9',  10);
        var subFs        = parseInt(val('submenu_font_size')     || '14', 10);
        var subFw        = val('submenu_font_weight') || '400';
        var subMw        = parseInt(val('submenu_min_width')     || '200', 10);
        if (!subHoverBg) {
            // Hover adattivo: velo scuro su sfondi chiari e viceversa (stessa formula lineare del css-generator)
            var subBgRgb = menux_hexToRgb(subBg || '#ffffff');
            var subBgLum = subBgRgb ? (0.2126*subBgRgb[0] + 0.7152*subBgRgb[1] + 0.0722*subBgRgb[2]) / 255 : 1;
            subHoverBg = subBgLum > 0.5 ? 'rgba(0,0,0,.05)' : 'rgba(255,255,255,.08)';
        }
        css += '#menux-preview-nav .menux-sub-menu{display:none;position:absolute;top:100%;left:0;min-width:'+subMw+'px;padding:6px 0;z-index:200;list-style:none;margin:4px 0 0;'+(subBg?'background:'+subBg+';':'')+'border-radius:'+subBr+'px;'+(subShadow?'box-shadow:0 4px 16px rgba(0,0,0,.12);':'')+(subBorder?'border:1px solid '+subBorder+';':'')+'}';
        css += '#menux-preview-nav .menux-list > li:hover .menux-sub-menu{display:block;}';
        css += '#menux-preview-nav .menux-sub-menu li{padding:0;list-style:none;}';
        css += '#menux-preview-nav .menux-sub-menu a{display:block;padding:'+subPy+'px '+subPx+'px;font-size:'+subFs+'px;font-weight:'+subFw+';'+(subLinkColor?'color:'+subLinkColor+'!important;':'')+'}';
        css += '#menux-preview-nav .menux-sub-menu a:hover{background:'+subHoverBg+';'+(subHoverLc?'color:'+subHoverLc+'!important;':'')+'}';

        // Keyframes nell anteprima
        css += '@keyframes bm-fadeIn{from{opacity:0}to{opacity:1}}';
        css += '@keyframes bm-slideLeft{from{opacity:0;transform:translateX(-100%)}to{opacity:1;transform:translateX(0)}}';
        css += '@keyframes bm-slideRight{from{opacity:0;transform:translateX(100%)}to{opacity:1;transform:translateX(0)}}';

        // Overlay backdrop nella preview: solo per drawer (in fullscreen la lista stessa è l'overlay)
        if (openStyle !== 'dropdown') {
            css += '#menux-preview-wrap{position:relative;overflow:hidden;}';
        }
        if (openStyle === 'drawer-left' || openStyle === 'drawer-right') {
            css += '#menux-preview-overlay{position:absolute;inset:0;background:' + ovBg + ';opacity:0;pointer-events:none;transition:opacity .3s;z-index:89;}';
            css += '#menux-preview-overlay.visible{opacity:' + ovOp + ';pointer-events:auto;}';
        } else {
            css += '#menux-preview-overlay{display:none;}';
        }

        // Pulsante close nel preview
        css += '.menux-close-btn{display:none;position:fixed;top:16px;right:20px;background:none;border:none;font-size:32px;cursor:pointer;color:inherit;opacity:.7;z-index:100000;padding:8px;}';
        css += '.menux-close-btn.visible{display:block;}';
        css += '.menux-close-btn:hover{opacity:1;}';

        // ── Announcement bar preview ──
        if (isChecked('announcement_enabled') && val('announcement_text').trim()) {
            var annBgCss = val('announcement_bg') || '#1d4ed8';
            var annTcCss = val('announcement_text_color') || '#ffffff';
            var annFsCss = parseInt(val('announcement_font_size'), 10) || 13;
            var annPyCss = parseInt(val('announcement_padding_y'), 10) || 8;
            css += '#menux-preview-wrap .menux-preview-ann{display:flex;align-items:center;justify-content:center;background:' + annBgCss + ';color:' + annTcCss + ';font-size:' + annFsCss + 'px;padding:' + annPyCss + 'px 16px;text-align:center;line-height:1.5;box-sizing:border-box;}';
        }

        // ── Search icon preview ──
        if (isChecked('search_enabled')) {
            var srchColorCss = color('search_icon_color') || 'currentColor';
            css += '#menux-preview-nav .menux-search-wrap{display:flex;align-items:center;flex-shrink:0;}';
            css += '#menux-preview-nav .menux-search-btn{display:flex;align-items:center;justify-content:center;background:none;border:none;cursor:pointer;padding:8px;border-radius:8px;color:' + srchColorCss + ';transition:opacity .2s;}';
            css += '#menux-preview-nav .menux-search-btn svg{width:20px;height:20px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;}';
            css += '#menux-preview-nav .menux-search-btn:hover{opacity:.65;}';
        }

        // ── WooCommerce cart preview ──
        if (isChecked('woo_cart_enabled')) {
            var cartColorCss  = color('woo_cart_icon_color') || 'currentColor';
            var cartBadgeCss  = val('woo_cart_badge_bg') || '#ef4444';
            css += '#menux-preview-nav .menux-woo-cart-wrap{display:flex;align-items:center;flex-shrink:0;}';
            css += '#menux-preview-nav .menux-woo-cart{position:relative;display:inline-flex;}';
            css += '#menux-preview-nav .menux-woo-cart-btn{position:relative;display:inline-flex;align-items:center;gap:8px;color:' + cartColorCss + ';text-decoration:none;font-size:18px;line-height:1;padding:6px;transition:opacity .15s;}';
            css += '#menux-preview-nav .menux-woo-cart-btn i{font-size:20px;}';
            css += '#menux-preview-nav .menux-woo-cart-btn:hover{opacity:.7;}';
            css += '#menux-preview-nav .menux-woo-count{position:absolute;top:-4px;left:18px;min-width:18px;height:18px;padding:0 5px;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;background:' + cartBadgeCss + ';color:#fff;border-radius:9px;font-size:11px;font-weight:700;line-height:1;}';
            css += '#menux-preview-nav .menux-woo-total{font-size:13px;font-weight:600;color:' + cartColorCss + ';}';
        }

        var tag = document.getElementById('menux-live-style');
        if (!tag) { tag = document.createElement('style'); tag.id = 'menux-live-style'; document.head.appendChild(tag); }
        tag.textContent = css;
        if (typeof menuxFontPicker !== 'undefined') { menuxFontPicker.loadFont(val('google_font')); }
        if (typeof buildMobilePhonePreview === 'function') buildMobilePhonePreview();
    }

    /* ================================================================
       DEVICE SWITCHER
       ================================================================ */
    window._bmPreviewDevice = 'desktop';

    function menux_setDevice(device) {
        window._bmPreviewDevice = device;

        // Update button states
        document.querySelectorAll('.bm-device-btn').forEach(function(btn) {
            btn.classList.toggle('active', btn.dataset.device === device);
        });

        // Update outer frame class
        var outer = document.getElementById('bm-device-outer');
        if (outer) {
            outer.className = 'bm-device-outer bm-device-' + device;
        }

        // Show/hide device chrome bar
        var chrome = document.getElementById('bm-device-chrome');
        if (chrome) {
            chrome.style.display = (device !== 'desktop') ? 'block' : 'none';
        }

        // Update label
        var label = document.getElementById('bm-preview-device-label');
        if (label) {
            var labels = {
                desktop: '🖥️ Desktop — full width',
                tablet:  '📱 Tablet — 768px',
                mobile:  '📲 Mobile — 375px'
            };
            label.textContent = labels[device] || '';
        }

        // Re-run preview with forced breakpoint
        menux_liveStylePreview();
    }

    /* ════════════════════════════════════════════════════════════════
       LOGO UPLOADER (Advanced — per-slot)
    ════════════════════════════════════════════════════════════════ */

    function menuxLogoUpload(slotKey) {
        if (typeof wp === 'undefined' || !wp.media) {
            alert('WordPress Media Uploader not available.');
            return;
        }
        var frame = wp.media({
            title: 'Select Logo Image',
            button: { text: 'Use this image' },
            multiple: false,
            library: { type: ['image'] }
        });
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            var attIdInput = document.getElementById('bm-logo-att-' + slotKey);
            var urlInput   = document.getElementById('bm-logo-url-' + slotKey);
            var preview    = document.getElementById('bm-logo-preview-' + slotKey);

            if (attIdInput) attIdInput.value = attachment.id;
            if (urlInput)   urlInput.value   = '';

            if (preview) {
                var src  = (attachment.sizes && attachment.sizes.thumbnail)
                         ? attachment.sizes.thumbnail.url : attachment.url;
                preview.innerHTML = '<img src="' + src + '" style="max-width:80px;max-height:40px;object-fit:contain;border-radius:4px;" alt="">';
            }

            var slot = document.getElementById('bm-logo-slot-' + slotKey);
            if (slot) {
                var uploadBtn = slot.querySelector('.bm-btn-secondary');
                if (uploadBtn) uploadBtn.textContent = 'Change';
            }
            if (slotKey === 'desktop') {
                if (typeof menux_preview_logo !== 'undefined') menux_preview_logo.url = attachment.url;
                menux_updatePreview();
            }
        });
        frame.open();
    }

    function menuxLogoClear(slotKey) {
        var attIdInput = document.getElementById('bm-logo-att-' + slotKey);
        var urlInput   = document.getElementById('bm-logo-url-' + slotKey);
        var preview    = document.getElementById('bm-logo-preview-' + slotKey);

        if (attIdInput) attIdInput.value = '0';
        if (urlInput)   urlInput.value   = '';
        if (preview)    preview.innerHTML = '<span style="color:#9ca3af;font-size:11px;">No image</span>';

        var slot = document.getElementById('bm-logo-slot-' + slotKey);
        if (slot) {
            var uploadBtn = slot.querySelector('.bm-btn-secondary');
            if (uploadBtn) uploadBtn.textContent = 'Upload';
        }
        if (slotKey === 'desktop') {
            if (typeof menux_preview_logo !== 'undefined') menux_preview_logo.url = '';
            menux_updatePreview();
        }
    }

    function menuxLogoUrlChange(slotKey, val) {
        var attIdInput = document.getElementById('bm-logo-att-' + slotKey);
        var preview    = document.getElementById('bm-logo-preview-' + slotKey);
        if (attIdInput) attIdInput.value = '0';
        if (preview && val) {
            preview.innerHTML = '<img src="' + val + '" style="max-width:80px;max-height:40px;object-fit:contain;border-radius:4px;" alt="" onerror="this.style.display=\'none\'">';
        } else if (preview) {
            preview.innerHTML = '<span style="color:#9ca3af;font-size:11px;">No image</span>';
        }
        if (slotKey === 'desktop') {
            if (typeof menux_preview_logo !== 'undefined') menux_preview_logo.url = val || '';
            menux_updatePreview();
        }
    }

    /* ════════════════════════════════════════════════════════════════
       MEGA MENU TOGGLE helpers
    ════════════════════════════════════════════════════════════════ */

    function menuxMegaToggle(itemKey, enabled) {
        var badge     = document.getElementById('bm-mega-badge-'    + itemKey);
        var enableBtn = document.getElementById('bm-mega-enable-'   + itemKey);
        var controls  = document.getElementById('bm-mega-controls-' + itemKey);
        var cb        = document.querySelector('.bm-mega-toggle-cb[data-item-key="' + itemKey + '"]');
        if (cb) cb.checked = enabled;
        if (badge) {
            badge.textContent = enabled ? '⚡ ON' : 'OFF';
            badge.className   = 'bm-mega-badge ' + (enabled ? 'bm-mega-badge-on' : 'bm-mega-badge-off');
        }
        if (enableBtn) enableBtn.style.display = enabled ? 'none' : '';
        if (controls)  controls.style.display  = enabled ? 'flex' : 'none';
    }

    /* ════════════════════════════════════════════════════════════════
       MEGA MENU DEMO TEMPLATES
    ════════════════════════════════════════════════════════════════ */

    // Helper: build a complete item object from compact params.
    function _mxDi(type, label, icon, desc, url) {
        return { type: type, label: label||'', url: url||'', icon: icon||'', desc: desc||'', desc_color: '', heading_color: '', link_color: '', image_id: 0, image_url: '', image_width: '', image_height: '', content: '', target: '' };
    }

    var mxMegaDemos = [
        {
            name: 'SaaS Product',
            desc: '4 cols — Features, Docs, Company, CTA',
            gradient: 'linear-gradient(135deg,#0f172a 0%,#1e1b4b 55%,#312e81 100%)',
            // Dark panel → light, high-contrast text.
            palette: { heading: '#818cf8', link: '#e2e8f0', desc: '#94a3b8', accent: '#60a5fa', hover: '#f1f5f9' },
            look: { radius: 16, pad_y: 28, pad_x: 36, gap: 24, divider: 'solid', open: 180 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Features',      'fa-solid fa-bolt'),
                    _mxDi('link',    'Dashboard',     'fa-solid fa-chart-pie',   'Analytics & reports',    '#'),
                    _mxDi('link',    'Automations',   'fa-solid fa-robot',       'Save time with rules',   '#'),
                    _mxDi('link',    'Integrations',  'fa-solid fa-plug',        'Connect your tools',     '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Resources',     'fa-solid fa-book-open'),
                    _mxDi('link',    'Documentation', 'fa-solid fa-file-lines',  'Step-by-step guides',    '#'),
                    _mxDi('link',    'API Reference', 'fa-solid fa-code',        'For developers',         '#'),
                    _mxDi('link',    'Blog',          'fa-solid fa-rss',         'Tips & news',            '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Company',       'fa-solid fa-building'),
                    _mxDi('link',    'About us',      'fa-solid fa-users',       'Our story & team',       '#'),
                    _mxDi('link',    'Careers',       'fa-solid fa-briefcase',   "We're hiring!",          '#'),
                    _mxDi('link',    'Contact',       'fa-solid fa-envelope',    'Get in touch',           '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Get started',   'fa-solid fa-rocket'),
                    _mxDi('link',    'Free trial',    'fa-solid fa-star',        '14 days, no credit card','#'),
                    _mxDi('link',    'Pricing',       'fa-solid fa-tag',         'Plans for every team',   '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Sign in',       'fa-solid fa-arrow-right-to-bracket', '',            '#'),
                ]},
            ]
        },
        {
            name: 'E-Commerce',
            desc: '3 cols — Categories, Deals, Help',
            gradient: 'linear-gradient(135deg,#ffffff 0%,#fdf2f8 55%,#fce7f3 100%)',
            // Light panel → dark text with a warm pink heading accent.
            palette: { heading: '#be185d', link: '#334155', desc: '#64748b', accent: '#db2777', hover: '#9f1239' },
            look: { radius: 12, pad_y: 26, pad_x: 34, gap: 22, divider: 'solid', open: 200 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Shop by category', 'fa-solid fa-shop'),
                    _mxDi('link',    'Electronics',  'fa-solid fa-laptop',      'Phones, tablets, PCs',   '#'),
                    _mxDi('link',    'Clothing',      'fa-solid fa-shirt',       'Men, women, kids',       '#'),
                    _mxDi('link',    'Home & Garden', 'fa-solid fa-house',       'Furniture & decor',      '#'),
                    _mxDi('link',    'Sports',        'fa-solid fa-futbol',      'Outdoor & fitness',      '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Deals & Offers',   'fa-solid fa-fire'),
                    _mxDi('link',    'Flash Sales',   'fa-solid fa-bolt',        'Today only',             '#'),
                    _mxDi('link',    'New Arrivals',  'fa-solid fa-star',        'Fresh this week',        '#'),
                    _mxDi('link',    'Clearance',     'fa-solid fa-percent',     'Up to 70% off',          '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'My Account',       'fa-solid fa-circle-user'),
                    _mxDi('link',    'My Orders',     'fa-solid fa-box',         'Track your orders',      '#'),
                    _mxDi('link',    'Returns',       'fa-solid fa-arrow-rotate-left','Easy 30-day returns','#'),
                    _mxDi('link',    'Support',       'fa-solid fa-headset',     "We're here for you",     '#'),
                ]},
            ]
        },
        {
            name: 'Creative Agency',
            desc: '3 cols — Services, Work, Studio',
            gradient: 'linear-gradient(135deg,#6d28d9 0%,#7c3aed 50%,#db2777 100%)',
            // Vivid purple panel → near-white text, light-lilac headings.
            palette: { heading: '#e9d5ff', link: '#f5f3ff', desc: '#c4b5fd', accent: '#fbbf24', hover: '#ffffff' },
            look: { radius: 20, pad_y: 28, pad_x: 36, gap: 26, divider: 'solid', open: 220 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Services',      'fa-solid fa-wand-magic-sparkles'),
                    _mxDi('link',    'Web Design',    'fa-solid fa-pen-ruler',   'Beautiful, fast sites',  '#'),
                    _mxDi('link',    'Branding',      'fa-solid fa-palette',     'Identity & logo design', '#'),
                    _mxDi('link',    'SEO & Growth',  'fa-solid fa-chart-line',  'Rank higher, grow faster','#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Work',      'fa-solid fa-images'),
                    _mxDi('link',    'Portfolio',     'fa-solid fa-briefcase',   'Selected projects',      '#'),
                    _mxDi('link',    'Case Studies',  'fa-solid fa-magnifying-glass','Results & stories',  '#'),
                    _mxDi('link',    'Testimonials',  'fa-solid fa-quote-left',  'What clients say',       '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Studio',        'fa-solid fa-building-columns'),
                    _mxDi('link',    'About',         'fa-solid fa-circle-info', 'Our story',              '#'),
                    _mxDi('link',    'Team',          'fa-solid fa-people-group','Meet the creatives',     '#'),
                    _mxDi('link',    'Start a project','fa-solid fa-rocket',     "Let's build together",   '#'),
                ]},
            ]
        },
        {
            name: 'News & Blog',
            desc: '3 cols — Topics, Sections, Connect',
            gradient: 'linear-gradient(135deg,#ffffff 0%,#f0fdfa 100%)',
            // Light panel → dark text, teal heading accent.
            palette: { heading: '#0f766e', link: '#334155', desc: '#64748b', accent: '#0d9488', hover: '#0f766e' },
            look: { radius: 8, pad_y: 24, pad_x: 32, gap: 30, divider: 'solid', open: 160 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Topics',        'fa-solid fa-hashtag'),
                    _mxDi('link',    'Technology',    'fa-solid fa-microchip',   'AI, software & gadgets', '#'),
                    _mxDi('link',    'Business',      'fa-solid fa-chart-bar',   'Markets & startups',     '#'),
                    _mxDi('link',    'Design',        'fa-solid fa-pen-nib',     'UI/UX & creativity',     '#'),
                    _mxDi('link',    'Science',       'fa-solid fa-flask',       'Research & discoveries', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Sections',      'fa-solid fa-newspaper'),
                    _mxDi('link',    'Interviews',    'fa-solid fa-microphone',  'In-depth conversations', '#'),
                    _mxDi('link',    'Opinion',       'fa-solid fa-comments',    "Editor's picks",         '#'),
                    _mxDi('link',    'Guides',        'fa-solid fa-map',         'Practical how-tos',      '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Connect',       'fa-solid fa-satellite-dish'),
                    _mxDi('link',    'Newsletter',    'fa-solid fa-envelope',    'Weekly digest',          '#'),
                    _mxDi('link',    'Podcast',       'fa-solid fa-podcast',     'Listen & subscribe',     '#'),
                    _mxDi('link',    'RSS Feed',      'fa-solid fa-rss',         'Follow updates',         '#'),
                ]},
            ]
        },
        {
            name: 'Corporate',
            desc: '3 cols — Solutions, Industries, Company',
            gradient: 'linear-gradient(135deg,#0c4a6e 0%,#0284c7 55%,#38bdf8 100%)',
            // Bright sky-blue panel → deep navy text for strong contrast.
            palette: { heading: '#bae6fd', link: '#f0f9ff', desc: '#7dd3fc', accent: '#fbbf24', hover: '#ffffff' },
            look: { radius: 10, pad_y: 26, pad_x: 34, gap: 24, divider: 'solid', open: 200 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Solutions',     'fa-solid fa-gear'),
                    _mxDi('link',    'Enterprise',    'fa-solid fa-city',        'Large-scale deployments','#'),
                    _mxDi('link',    'SMB',           'fa-solid fa-store',       'Small & medium business','#'),
                    _mxDi('link',    'Startups',      'fa-solid fa-seedling',    'Grow from day one',      '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Industries',    'fa-solid fa-industry'),
                    _mxDi('link',    'Healthcare',    'fa-solid fa-heart-pulse', 'Secure & compliant',     '#'),
                    _mxDi('link',    'Finance',       'fa-solid fa-coins',       'FinTech solutions',      '#'),
                    _mxDi('link',    'Retail',        'fa-solid fa-bag-shopping','Omnichannel commerce',   '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Company',       'fa-solid fa-landmark'),
                    _mxDi('link',    'About',         'fa-solid fa-circle-info', 'Mission & values',       '#'),
                    _mxDi('link',    'Press',         'fa-solid fa-bullhorn',    'News & media',           '#'),
                    _mxDi('link',    'Partners',      'fa-solid fa-handshake',   'Grow together',          '#'),
                ]},
            ]
        },
        {
            name: 'Restaurant',
            desc: '3 cols — Menu, Visit Us, Reserve',
            gradient: 'linear-gradient(135deg,#ea580c 0%,#f97316 50%,#dc2626 100%)',
            // Warm orange-to-red panel → white text, soft cream headings.
            palette: { heading: '#fff7ed', link: '#ffffff', desc: '#fed7aa', accent: '#fef08a', hover: '#ffffff' },
            look: { radius: 18, pad_y: 28, pad_x: 36, gap: 24, divider: 'dashed', open: 240 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Menu',      'fa-solid fa-utensils'),
                    _mxDi('link',    'Starters',      'fa-solid fa-leaf',        'Fresh & seasonal',       '#'),
                    _mxDi('link',    'Main Courses',  'fa-solid fa-drumstick-bite',"Chef's specialties",   '#'),
                    _mxDi('link',    'Desserts',      'fa-solid fa-cake-candles', 'Sweet endings',         '#'),
                    _mxDi('link',    'Wine List',     'fa-solid fa-wine-glass',  'Curated selection',      '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Visit Us',      'fa-solid fa-location-dot'),
                    _mxDi('link',    'Locations',     'fa-solid fa-map-location-dot','Find a restaurant',  '#'),
                    _mxDi('link',    'Hours',         'fa-solid fa-clock',       'Open 7 days a week',     '#'),
                    _mxDi('link',    'Private Events','fa-solid fa-champagne-glasses','Celebrate with us', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Reserve',       'fa-solid fa-calendar-check'),
                    _mxDi('link',    'Book a Table',  'fa-solid fa-table',       'Online reservation',     '#'),
                    _mxDi('link',    'Delivery',      'fa-solid fa-motorcycle',  'Order to your door',     '#'),
                    _mxDi('link',    'Gift Cards',    'fa-solid fa-gift',        'The perfect present',    '#'),
                ]},
            ]
        },
        {
            name: 'Travel & Tourism',
            desc: '4 cols — Destinations, Trips, Stays, Inspiration',
            gradient: 'linear-gradient(135deg,#0c4a6e 0%,#0891b2 50%,#06b6d4 100%)',
            // Ocean blue-to-cyan panel → white text, light cyan headings.
            palette: { heading: '#cffafe', link: '#f0f9ff', desc: '#a5f3fc', accent: '#fde68a', hover: '#ffffff' },
            look: { radius: 16, pad_y: 28, pad_x: 36, gap: 26, divider: 'solid', open: 220 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Destinations',  'fa-solid fa-earth-americas'),
                    _mxDi('link',    'Europe',        'fa-solid fa-landmark',    'Cities, coasts & culture','#'),
                    _mxDi('link',    'Asia',          'fa-solid fa-torii-gate',  'Ancient & vibrant',      '#'),
                    _mxDi('link',    'Americas',      'fa-solid fa-mountain-sun','Wild nature & cities',   '#'),
                    _mxDi('link',    'Oceania',       'fa-solid fa-water',       'Islands & reefs',        '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Trip Types',    'fa-solid fa-route'),
                    _mxDi('link',    'Adventure',     'fa-solid fa-person-hiking','Trekking & expeditions', '#'),
                    _mxDi('link',    'Beach & Sun',   'fa-solid fa-umbrella-beach','Relax by the sea',     '#'),
                    _mxDi('link',    'City Breaks',   'fa-solid fa-city',        'Short urban getaways',   '#'),
                    _mxDi('link',    'Cruises',       'fa-solid fa-ship',        'All-inclusive at sea',   '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Where to Stay', 'fa-solid fa-bed'),
                    _mxDi('link',    'Hotels',        'fa-solid fa-hotel',       'Rated & reviewed',       '#'),
                    _mxDi('link',    'Villas',        'fa-solid fa-house-chimney','Private & exclusive',   '#'),
                    _mxDi('link',    'Hostels',       'fa-solid fa-people-roof', 'Budget & social',        '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Plan Your Trip','fa-solid fa-compass'),
                    _mxDi('link',    'Travel Guides', 'fa-solid fa-map',         'Expert tips & itineraries','#'),
                    _mxDi('link',    'Visa Info',     'fa-solid fa-passport',    'Entry requirements',     '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Book Now',      'fa-solid fa-plane-departure','Find the best deals',  '#'),
                ]},
            ]
        },
        {
            name: 'Online Learning',
            desc: '3 cols — Courses, Instructors, Community',
            gradient: 'linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#4338ca 100%)',
            // Deep indigo panel → light text, bright indigo headings.
            palette: { heading: '#a5b4fc', link: '#e0e7ff', desc: '#818cf8', accent: '#fb923c', hover: '#ffffff' },
            look: { radius: 16, pad_y: 28, pad_x: 36, gap: 24, divider: 'solid', open: 200 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Explore Courses','fa-solid fa-graduation-cap'),
                    _mxDi('link',    'Web Development','fa-solid fa-code',       'HTML, CSS, JS & more',   '#'),
                    _mxDi('link',    'Data Science',  'fa-solid fa-chart-column','Python, ML & analytics', '#'),
                    _mxDi('link',    'Design & UX',   'fa-solid fa-pen-ruler',   'Figma, UI patterns',     '#'),
                    _mxDi('link',    'Business',      'fa-solid fa-briefcase',   'Marketing, PM & growth', '#'),
                    _mxDi('link',    'All Courses',   'fa-solid fa-grid-2',      'Browse the full catalog', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Instructors','fa-solid fa-chalkboard-user'),
                    _mxDi('link',    'Meet the Team', 'fa-solid fa-people-group','Experts from top companies','#'),
                    _mxDi('link',    'Teach with Us', 'fa-solid fa-microphone',  'Share your knowledge',   '#'),
                    _mxDi('divider', ''),
                    _mxDi('heading', 'Certifications', 'fa-solid fa-certificate'),
                    _mxDi('link',    'Career Paths',  'fa-solid fa-road',        'Structured learning tracks','#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Community',     'fa-solid fa-users'),
                    _mxDi('link',    'Forum',         'fa-solid fa-comments',    'Ask & answer questions',  '#'),
                    _mxDi('link',    'Discord',       'fa-brands fa-discord',    'Live chat & events',      '#'),
                    _mxDi('link',    'Live Events',   'fa-solid fa-video',       'Webinars & workshops',    '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Free Trial',    'fa-solid fa-star',        '7 days, no credit card',  '#'),
                ]},
            ]
        },
        {
            name: 'Healthcare',
            desc: '3 cols — Services, Doctors, Patients',
            gradient: 'linear-gradient(135deg,#eff6ff 0%,#dbeafe 55%,#e0f2fe 100%)',
            // Soft light-blue panel → dark text, medical blue headings.
            palette: { heading: '#1d4ed8', link: '#1e293b', desc: '#475569', accent: '#2563eb', hover: '#1d4ed8' },
            look: { radius: 14, pad_y: 26, pad_x: 34, gap: 24, divider: 'solid', open: 200 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Services',  'fa-solid fa-stethoscope'),
                    _mxDi('link',    'Primary Care',  'fa-solid fa-user-doctor', 'General medicine',       '#'),
                    _mxDi('link',    'Specialist Care','fa-solid fa-heart-pulse','Cardio, ortho & more',   '#'),
                    _mxDi('link',    'Mental Health', 'fa-solid fa-brain',       'Therapy & counselling',  '#'),
                    _mxDi('link',    'Diagnostics',   'fa-solid fa-microscope',  'Lab tests & imaging',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Doctors',   'fa-solid fa-id-card'),
                    _mxDi('link',    'Find a Doctor', 'fa-solid fa-magnifying-glass','Search by specialty', '#'),
                    _mxDi('link',    'Departments',   'fa-solid fa-hospital',    'Clinics & centres',      '#'),
                    _mxDi('link',    'Emergency',     'fa-solid fa-truck-medical','24/7 urgent care',      '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'For Patients',  'fa-solid fa-circle-user'),
                    _mxDi('link',    'Book Appointment','fa-solid fa-calendar-plus','Online booking',       '#'),
                    _mxDi('link',    'Patient Portal','fa-solid fa-lock',        'Records & results',      '#'),
                    _mxDi('link',    'Insurance',     'fa-solid fa-shield-halved','Coverage & billing',    '#'),
                    _mxDi('link',    'FAQ',           'fa-solid fa-circle-question','Common questions',     '#'),
                ]},
            ]
        },
        {
            name: 'Real Estate',
            desc: '3 cols — Buy, Rent, Services',
            gradient: 'linear-gradient(135deg,#1c1917 0%,#292524 55%,#44403c 100%)',
            // Charcoal panel → light text, warm gold headings.
            palette: { heading: '#fbbf24', link: '#e7e5e4', desc: '#a8a29e', accent: '#fbbf24', hover: '#ffffff' },
            look: { radius: 8, pad_y: 28, pad_x: 38, gap: 30, divider: 'solid', open: 220 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Buy a Property','fa-solid fa-house-circle-check'),
                    _mxDi('link',    'Apartments',    'fa-solid fa-building',    'Studios to penthouses',  '#'),
                    _mxDi('link',    'Houses',        'fa-solid fa-house',       'Family homes & villas',  '#'),
                    _mxDi('link',    'Commercial',    'fa-solid fa-store',       'Offices, shops & lots',  '#'),
                    _mxDi('link',    'New Builds',    'fa-solid fa-helmet-safety','Off-plan projects',     '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Rent',          'fa-solid fa-key'),
                    _mxDi('link',    'Short-term',    'fa-solid fa-calendar-days','Weekly & monthly stays','#'),
                    _mxDi('link',    'Long-term',     'fa-solid fa-file-contract','Lease agreements',      '#'),
                    _mxDi('link',    'Furnished',     'fa-solid fa-couch',       'Move-in ready',          '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Services',  'fa-solid fa-handshake'),
                    _mxDi('link',    'Sell Your Home','fa-solid fa-tag',         'Free valuation',         '#'),
                    _mxDi('link',    'Property Mgmt', 'fa-solid fa-clipboard-list','Hands-off landlording','#'),
                    _mxDi('link',    'Mortgage Calc', 'fa-solid fa-calculator',  'Estimate repayments',    '#'),
                    _mxDi('link',    'Contact Agent', 'fa-solid fa-phone',       'Speak to an expert',     '#'),
                ]},
            ]
        },
        {
            name: 'Fitness & Wellness',
            desc: '3 cols — Train, Nutrition, Community',
            gradient: 'linear-gradient(135deg,#991b1b 0%,#dc2626 50%,#ea580c 100%)',
            // Energetic red-to-orange panel → white text, warm cream headings.
            palette: { heading: '#fef2f2', link: '#ffffff', desc: '#fecaca', accent: '#fde68a', hover: '#ffffff' },
            look: { radius: 16, pad_y: 26, pad_x: 34, gap: 22, divider: 'solid', open: 160 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Train',         'fa-solid fa-dumbbell'),
                    _mxDi('link',    'Workout Plans', 'fa-solid fa-list-check',  'Beginner to advanced',   '#'),
                    _mxDi('link',    'Classes',       'fa-solid fa-person-running','Yoga, HIIT, Pilates',   '#'),
                    _mxDi('link',    'Personal Training','fa-solid fa-user-check','1-on-1 coaching',       '#'),
                    _mxDi('link',    'Online Gym',    'fa-solid fa-video',       'Train from anywhere',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Nutrition',     'fa-solid fa-apple-whole'),
                    _mxDi('link',    'Meal Plans',    'fa-solid fa-bowl-food',   'Tailored to your goals', '#'),
                    _mxDi('link',    'Supplements',   'fa-solid fa-jar',         'Protein, vitamins & more','#'),
                    _mxDi('link',    'Recipes',       'fa-solid fa-utensils',    'Healthy & delicious',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Wellness',      'fa-solid fa-heart'),
                    _mxDi('link',    'Meditation',    'fa-solid fa-spa',         'Mindfulness & sleep',    '#'),
                    _mxDi('link',    'Progress Tracker','fa-solid fa-chart-line','Log & measure results',  '#'),
                    _mxDi('link',    'Community',     'fa-solid fa-users',       'Challenges & motivation','#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Start Free',    'fa-solid fa-rocket',      '30-day free trial',      '#'),
                ]},
            ]
        },
        {
            name: 'Photography Studio',
            desc: '3 cols — Services, Portfolio, Book',
            gradient: 'linear-gradient(135deg,#0a0a0a 0%,#171727 50%,#1e1b2e 100%)',
            palette: { heading: '#cbd5e1', link: '#f1f5f9', desc: '#94a3b8', accent: '#e2e8f0', hover: '#ffffff' },
            look: { radius: 6, pad_y: 30, pad_x: 40, gap: 32, divider: 'solid', open: 260 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Services',      'fa-solid fa-camera'),
                    _mxDi('link',    'Weddings',      'fa-solid fa-heart',       'Timeless moments',       '#'),
                    _mxDi('link',    'Portraits',     'fa-solid fa-person',      'Personal & professional','#'),
                    _mxDi('link',    'Commercial',    'fa-solid fa-building',    'Brand & product shoots', '#'),
                    _mxDi('link',    'Events',        'fa-solid fa-champagne-glasses','Corporate & social', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Portfolio',     'fa-solid fa-images'),
                    _mxDi('link',    'Gallery',       'fa-solid fa-photo-film',  'Browse all work',        '#'),
                    _mxDi('link',    'Behind the Scenes','fa-solid fa-clapperboard','Process & stories',   '#'),
                    _mxDi('link',    'Film & Video',  'fa-solid fa-film',        'Motion & reels',         '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Work With Me',  'fa-solid fa-handshake'),
                    _mxDi('link',    'Packages',      'fa-solid fa-tag',         'Pricing & inclusions',   '#'),
                    _mxDi('link',    'Book a Session','fa-solid fa-calendar-check','Check availability',   '#'),
                    _mxDi('link',    'Client Area',   'fa-solid fa-lock',        'Download your photos',   '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Contact',       'fa-solid fa-envelope',    "Let's create together",  '#'),
                ]},
            ]
        },
        {
            name: 'Law Firm',
            desc: '3 cols — Practice Areas, Firm, Consultation',
            gradient: 'linear-gradient(135deg,#0b1d33 0%,#13304f 55%,#1d4368 100%)',
            // Deep navy panel → light text, champagne-gold headings. Classic & authoritative.
            palette: { heading: '#d4b06a', link: '#e8eef5', desc: '#8fa3b8', accent: '#d4b06a', hover: '#ffffff' },
            look: { radius: 4, pad_y: 30, pad_x: 40, gap: 30, divider: 'solid', open: 240 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Practice Areas','fa-solid fa-scale-balanced'),
                    _mxDi('link',    'Corporate Law', 'fa-solid fa-building',    'M&A, contracts, compliance','#'),
                    _mxDi('link',    'Family Law',    'fa-solid fa-house',       'Divorce, custody & estates','#'),
                    _mxDi('link',    'Personal Injury','fa-solid fa-car-burst',  'No win, no fee',         '#'),
                    _mxDi('link',    'Employment',    'fa-solid fa-briefcase',   'Workplace rights & disputes','#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'The Firm',      'fa-solid fa-landmark'),
                    _mxDi('link',    'Our Attorneys', 'fa-solid fa-user-tie',    'Experienced advocates',  '#'),
                    _mxDi('link',    'Case Results',  'fa-solid fa-gavel',       'Verdicts & settlements', '#'),
                    _mxDi('link',    'Testimonials',  'fa-solid fa-quote-left',  'What clients say',       '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Get Help',      'fa-solid fa-handshake'),
                    _mxDi('link',    'Free Consultation','fa-solid fa-calendar-check','Confidential, no obligation','#'),
                    _mxDi('link',    'Legal Resources','fa-solid fa-file-contract','Guides & FAQ',         '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Call Us 24/7',  'fa-solid fa-phone',       'Immediate assistance',   '#'),
                ]},
            ]
        },
        {
            name: 'Finance & Banking',
            desc: '3 cols — Banking, Invest, Support',
            gradient: 'linear-gradient(135deg,#022c22 0%,#064e3b 55%,#047857 100%)',
            // Emerald panel → mint headings, near-white links. Trustworthy & modern.
            palette: { heading: '#6ee7b7', link: '#ecfdf5', desc: '#a7f3d0', accent: '#34d399', hover: '#ffffff' },
            look: { radius: 12, pad_y: 28, pad_x: 36, gap: 24, divider: 'solid', open: 200 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Personal Banking','fa-solid fa-building-columns'),
                    _mxDi('link',    'Accounts',      'fa-solid fa-wallet',      'Checking & savings',     '#'),
                    _mxDi('link',    'Cards',         'fa-solid fa-credit-card', 'Debit, credit & rewards','#'),
                    _mxDi('link',    'Loans',         'fa-solid fa-hand-holding-dollar','Personal & auto',  '#'),
                    _mxDi('link',    'Mortgages',     'fa-solid fa-house',       'Rates from 2.9%',        '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Invest & Save', 'fa-solid fa-chart-line'),
                    _mxDi('link',    'Investing',     'fa-solid fa-money-bill-trend-up','Stocks, funds & ETFs','#'),
                    _mxDi('link',    'Retirement',    'fa-solid fa-piggy-bank',  'Plan your future',       '#'),
                    _mxDi('link',    'Insurance',     'fa-solid fa-umbrella',    'Life, home & travel',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Help & Security','fa-solid fa-shield-halved'),
                    _mxDi('link',    'Mobile App',    'fa-solid fa-mobile-screen','Bank from anywhere',    '#'),
                    _mxDi('link',    'Security Center','fa-solid fa-lock',       'Protect your accounts',  '#'),
                    _mxDi('link',    'Find a Branch', 'fa-solid fa-location-dot','ATMs & offices near you','#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Open an Account','fa-solid fa-arrow-right-to-bracket','In under 10 minutes','#'),
                ]},
            ]
        },
        {
            name: 'Fashion & Beauty',
            desc: '4 cols — Women, Men, Beauty, The Edit',
            gradient: 'linear-gradient(135deg,#faf8f5 0%,#f1ebe3 60%,#e9dfd3 100%)',
            // Ivory editorial panel → near-black text, warm bronze accent. Minimal luxe.
            palette: { heading: '#1c1917', link: '#44403c', desc: '#a8a29e', accent: '#b45309', hover: '#1c1917' },
            look: { radius: 0, pad_y: 32, pad_x: 42, gap: 34, divider: 'solid', open: 260 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Women',         'fa-solid fa-venus'),
                    _mxDi('link',    'New In',        'fa-solid fa-star',        'This week’s arrivals','#'),
                    _mxDi('link',    'Dresses',       'fa-solid fa-shirt',       'Day to evening',         '#'),
                    _mxDi('link',    'Shoes & Bags',  'fa-solid fa-bag-shopping','Complete the look',      '#'),
                    _mxDi('link',    'Jewellery',     'fa-solid fa-gem',         'Fine & fashion',         '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Men',           'fa-solid fa-mars'),
                    _mxDi('link',    'New In',        'fa-solid fa-star',        'Fresh drops',            '#'),
                    _mxDi('link',    'Tailoring',     'fa-solid fa-user-tie',    'Suits & blazers',        '#'),
                    _mxDi('link',    'Accessories',   'fa-solid fa-glasses',     'Watches, belts & more',  '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Beauty',        'fa-solid fa-wand-magic-sparkles'),
                    _mxDi('link',    'Skincare',      'fa-solid fa-droplet',     'Cleanse, treat, glow',   '#'),
                    _mxDi('link',    'Makeup',        'fa-solid fa-paintbrush',  'Bestsellers & new shades','#'),
                    _mxDi('link',    'Fragrance',     'fa-solid fa-spray-can-sparkles','Signature scents', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'The Edit',      'fa-solid fa-newspaper'),
                    _mxDi('link',    'Trend Report',  'fa-solid fa-fire',        'What to wear now',       '#'),
                    _mxDi('link',    'Lookbook',      'fa-solid fa-camera',      'Styled by our editors',  '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Sale',          'fa-solid fa-tag',         'Up to 50% off',          '#'),
                ]},
            ]
        },
        {
            name: 'Hotel & Resort',
            desc: '3 cols — Rooms, Experiences, Plan',
            gradient: 'linear-gradient(135deg,#2c1a0e 0%,#4a2c17 50%,#6b4226 100%)',
            // Rich bronze-brown panel → warm sand headings, cream links. Quiet luxury.
            palette: { heading: '#e7c898', link: '#faf3ea', desc: '#c9a87e', accent: '#e7c898', hover: '#ffffff' },
            look: { radius: 14, pad_y: 30, pad_x: 38, gap: 26, divider: 'solid', open: 240 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Rooms & Suites','fa-solid fa-bed'),
                    _mxDi('link',    'Deluxe Rooms',  'fa-solid fa-door-open',   'Garden or city views',   '#'),
                    _mxDi('link',    'Suites',        'fa-solid fa-crown',       'Space to unwind',        '#'),
                    _mxDi('link',    'Villas',        'fa-solid fa-house-chimney','Private pool & butler', '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Experiences',   'fa-solid fa-spa'),
                    _mxDi('link',    'Spa & Wellness','fa-solid fa-leaf',        'Massages & rituals',     '#'),
                    _mxDi('link',    'Dining',        'fa-solid fa-utensils',    '3 restaurants, 2 bars',  '#'),
                    _mxDi('link',    'Pool & Beach',  'fa-solid fa-umbrella-beach','Cabanas & sunset bar', '#'),
                    _mxDi('link',    'Activities',    'fa-solid fa-person-swimming','Excursions & sport',  '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Plan Your Stay','fa-solid fa-calendar-check'),
                    _mxDi('link',    'Offers',        'fa-solid fa-gift',        'Packages & long-stay deals','#'),
                    _mxDi('link',    'Weddings & Events','fa-solid fa-champagne-glasses','Unforgettable settings','#'),
                    _mxDi('link',    'Getting Here',  'fa-solid fa-location-dot','Transfers & directions', '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Book Direct',   'fa-solid fa-bell-concierge','Best rate guaranteed', '#'),
                ]},
            ]
        },
        {
            name: 'Nonprofit & Charity',
            desc: '3 cols — Causes, Get Involved, About',
            gradient: 'linear-gradient(135deg,#f0fdf4 0%,#dcfce7 55%,#d1fae5 100%)',
            // Soft hopeful green panel → dark text, deep green headings.
            palette: { heading: '#15803d', link: '#1f2937', desc: '#6b7280', accent: '#16a34a', hover: '#15803d' },
            look: { radius: 16, pad_y: 26, pad_x: 34, gap: 24, divider: 'solid', open: 180 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Our Causes',    'fa-solid fa-hand-holding-heart'),
                    _mxDi('link',    'Clean Water',   'fa-solid fa-droplet',     'Wells & sanitation',     '#'),
                    _mxDi('link',    'Education',     'fa-solid fa-graduation-cap','Schools & scholarships','#'),
                    _mxDi('link',    'Environment',   'fa-solid fa-seedling',    'Reforestation projects', '#'),
                    _mxDi('link',    'Emergency Relief','fa-solid fa-kit-medical','Rapid disaster response','#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Get Involved',  'fa-solid fa-handshake-angle'),
                    _mxDi('link',    'Volunteer',     'fa-solid fa-people-group','On the ground or remote','#'),
                    _mxDi('link',    'Fundraise',     'fa-solid fa-bullhorn',    'Start your own campaign','#'),
                    _mxDi('link',    'Corporate Partners','fa-solid fa-building','Match & sponsor',       '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'About Us',      'fa-solid fa-earth-americas'),
                    _mxDi('link',    'Our Impact',    'fa-solid fa-chart-line',  'Reports & numbers',      '#'),
                    _mxDi('link',    'Stories',       'fa-solid fa-book-open',   'From the field',         '#'),
                    _mxDi('link',    'Transparency',  'fa-solid fa-magnifying-glass','Where your money goes','#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Donate Now',    'fa-solid fa-heart',       'Every gift counts',      '#'),
                ]},
            ]
        },
        {
            name: 'Events & Conference',
            desc: '3 cols — Program, Speakers, Attend',
            gradient: 'linear-gradient(135deg,#100624 0%,#3b0764 55%,#86198f 100%)',
            // Electric night-violet panel → light text, orchid headings, gold accent.
            palette: { heading: '#f0abfc', link: '#faf5ff', desc: '#c084fc', accent: '#fde047', hover: '#ffffff' },
            look: { radius: 18, pad_y: 28, pad_x: 36, gap: 24, divider: 'solid', open: 220 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Program',       'fa-solid fa-calendar-days'),
                    _mxDi('link',    'Schedule',      'fa-solid fa-clock',       'Day-by-day agenda',      '#'),
                    _mxDi('link',    'Keynotes',      'fa-solid fa-microphone-lines','Main-stage sessions','#'),
                    _mxDi('link',    'Workshops',     'fa-solid fa-lightbulb',   'Hands-on deep dives',    '#'),
                    _mxDi('link',    'After Party',   'fa-solid fa-music',       'Network & celebrate',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Speakers',      'fa-solid fa-users'),
                    _mxDi('link',    'Lineup 2026',   'fa-solid fa-star',        '60+ industry leaders',   '#'),
                    _mxDi('link',    'Call for Papers','fa-solid fa-file-pen',   'Submit your talk',       '#'),
                    _mxDi('link',    'Past Editions', 'fa-solid fa-video',       'Watch the recordings',   '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Attend',        'fa-solid fa-ticket'),
                    _mxDi('link',    'Venue & Travel','fa-solid fa-map-location-dot','How to get there',   '#'),
                    _mxDi('link',    'Sponsors',      'fa-solid fa-handshake',   'Partner with us',        '#'),
                    _mxDi('link',    'FAQ',           'fa-solid fa-circle-question','Everything you need', '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Get Tickets',   'fa-solid fa-bolt',        'Early bird ends soon',   '#'),
                ]},
            ]
        },
        {
            name: 'Automotive',
            desc: '3 cols — Models, Service, Owners',
            gradient: 'linear-gradient(135deg,#1f2937 0%,#374151 55%,#4b5563 100%)',
            // Gunmetal steel panel → light text, signal-red headings. Sleek showroom feel.
            palette: { heading: '#f87171', link: '#f3f4f6', desc: '#9ca3af', accent: '#ef4444', hover: '#ffffff' },
            look: { radius: 8, pad_y: 28, pad_x: 36, gap: 26, divider: 'solid', open: 220 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Models',        'fa-solid fa-car'),
                    _mxDi('link',    'Sedans',        'fa-solid fa-car-side',    'Comfort meets performance','#'),
                    _mxDi('link',    'SUVs & Crossovers','fa-solid fa-truck-pickup','Room for every adventure','#'),
                    _mxDi('link',    'Electric',      'fa-solid fa-bolt',        'Zero emissions, full torque','#'),
                    _mxDi('link',    'Compare Models','fa-solid fa-table-list',  'Side-by-side specs',     '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Service & Parts','fa-solid fa-screwdriver-wrench'),
                    _mxDi('link',    'Book a Service','fa-solid fa-calendar-check','Certified technicians','#'),
                    _mxDi('link',    'Genuine Parts', 'fa-solid fa-gears',       'OEM quality guaranteed', '#'),
                    _mxDi('link',    'Tyres & Wheels','fa-solid fa-circle-notch','Fitting & balancing',    '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Owners',        'fa-solid fa-key'),
                    _mxDi('link',    'Financing',     'fa-solid fa-calculator',  'Leasing & loan options', '#'),
                    _mxDi('link',    'Warranty',      'fa-solid fa-shield-halved','Coverage & extensions', '#'),
                    _mxDi('link',    'Roadside Assist','fa-solid fa-road',       '24/7 wherever you are',  '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Book a Test Drive','fa-solid fa-gauge-high','Feel it for yourself',  '#'),
                ]},
            ]
        },
        {
            name: 'Gaming & Esports',
            desc: '3 cols — Games, Esports, Community',
            gradient: 'linear-gradient(135deg,#020617 0%,#0c1a3a 55%,#123a5c 100%)',
            // Midnight panel → neon-cyan headings, lime accent. Built for the arena.
            palette: { heading: '#22d3ee', link: '#e2e8f0', desc: '#64748b', accent: '#a3e635', hover: '#ffffff' },
            look: { radius: 12, pad_y: 26, pad_x: 34, gap: 22, divider: 'solid', open: 180 },
            cols: [
                { width_pct: '', items: [
                    _mxDi('heading', 'Games',         'fa-solid fa-gamepad'),
                    _mxDi('link',    'New Releases',  'fa-solid fa-fire',        'Just dropped',           '#'),
                    _mxDi('link',    'Top Charts',    'fa-solid fa-ranking-star','Most played this week',  '#'),
                    _mxDi('link',    'Free to Play',  'fa-solid fa-gift',        'Jump in for free',       '#'),
                    _mxDi('link',    'All Genres',    'fa-solid fa-puzzle-piece','RPG, FPS, strategy & more','#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Esports',       'fa-solid fa-trophy'),
                    _mxDi('link',    'Tournaments',   'fa-solid fa-crosshairs',  'Compete for prizes',     '#'),
                    _mxDi('link',    'Live Matches',  'fa-solid fa-tv',          'Watch now',              '#'),
                    _mxDi('link',    'Rankings',      'fa-solid fa-chart-column','Teams & leaderboards',   '#'),
                ]},
                { width_pct: '', items: [
                    _mxDi('heading', 'Community',     'fa-solid fa-headset'),
                    _mxDi('link',    'Forums',        'fa-solid fa-comments',    'Strategy & LFG',         '#'),
                    _mxDi('link',    'Discord',       'fa-brands fa-discord',    '40k members online',     '#'),
                    _mxDi('link',    'Creators',      'fa-solid fa-video',       'Streams & highlights',   '#'),
                    _mxDi('divider', ''),
                    _mxDi('link',    'Join Free',     'fa-solid fa-rocket',      'Create your player profile','#'),
                ]},
            ]
        },
    ];

    /* ════════════════════════════════════════════════════════════════
       MEGA MENU EDITOR
    ════════════════════════════════════════════════════════════════ */

    var menuxMegaEditor = (function() {

        var _activeKey = null;
        var _data      = [];
        var _drag      = { colIdx: -1, itemIdx: -1 };
        var _style     = {};   // per-item style overrides
        var _activeTab = 'content';

        function newCol() {
            return { width_pct: '', align: 'left', items: [] };
        }
        function newItem(type) {
            var it = { type: type || 'link', label: '', url: '', icon: '', desc: '', desc_color: '', link_color: '', heading_color: '', image_id: 0, image_url: '', image_width: '', image_height: '', content: '', target: '' };
            if (type === 'dynamic') {
                it.source = 'posts';
                it.dyn_count = '5';
                it.dyn_orderby = 'date';
                it.dyn_post_type = 'post';
                it.dyn_view_all = '';
                it.dyn_view_all_label = '';
            }
            return it;
        }

        // Orderby options offered per dynamic source (value → human label).
        var DYN_ORDERBY = {
            posts:   [ ['date','Most recent'], ['title','Title (A–Z)'], ['modified','Recently updated'] ],
            wc_cats: [ ['name','Name (A–Z)'], ['count','Most products'], ['menu_order','Manual order'] ]
        };

        function open(itemKey) {
            _activeKey = itemKey;

            var hiddenInput = document.getElementById('mega-json-' + itemKey);
            _data = [];
            if (hiddenInput && hiddenInput.value) {
                try { _data = JSON.parse(hiddenInput.value) || []; } catch(e) {}
            }

            var titleEl = document.getElementById('menux-mega-dialog-title');
            if (titleEl) {
                var itemEl  = document.getElementById('bm-mega-item-' + itemKey);
                var labelEl = itemEl ? itemEl.querySelector('.bm-mega-item-label') : null;
                titleEl.textContent = 'Edit Megamenu — ' + (labelEl ? labelEl.textContent : itemKey);
            }

            // Load per-item style
            var styleInput = document.getElementById('mega-style-json-' + itemKey);
            _style = {};
            if (styleInput && styleInput.value && styleInput.value !== '{}') {
                try { _style = JSON.parse(styleInput.value) || {}; } catch(e) {}
            }
            // Reset to content tab and populate appearance fields
            menuxMegaSwitchTab('content');
            _populateAppearance();
            _bindAppearanceLive();

            // Keep max-w field in sync when the user toggles Full width
            var fwEl = document.getElementById('bm-mega-full-' + itemKey);
            if (fwEl && !fwEl._menuxMaxWSynced) {
                fwEl.addEventListener('change', _syncMaxWState);
                fwEl._menuxMaxWSynced = true;
            }

            render();
            renderPreview();

            var overlay = document.getElementById('menux-mega-overlay');
            if (overlay) { overlay.style.display = 'flex'; }
        }

        function close() {
            var overlay = document.getElementById('menux-mega-overlay');
            if (overlay) overlay.style.display = 'none';
            _activeKey = null;
            // Reset so _bindAppearanceLive() re-attaches handlers if the panel
            // DOM is ever recreated between open() calls.
            _appearanceBound = false;
        }

        function save() {
            if (!_activeKey) return;
            collectFromDOM();
            var hiddenInput = document.getElementById('mega-json-' + _activeKey);
            if (hiddenInput) {
                hiddenInput.value = JSON.stringify(_data);
            }
            _collectAppearance();
            var styleInput = document.getElementById('mega-style-json-' + _activeKey);
            if (styleInput) { styleInput.value = JSON.stringify(_style); }
            var summary = document.getElementById('bm-mega-summary-' + _activeKey);
            if (summary) {
                var num = _data.length;
                summary.innerHTML = num > 0
                    ? '<span class="bm-mega-info">' + num + ' column(s) configured</span>'
                    : '<span class="bm-mega-info bm-mega-info-empty">No columns yet — click Edit Megamenu.</span>';
            }
            close();
        }

        function collectFromDOM() {
            var wrap = document.getElementById('menux-mega-cols-wrap');
            if (!wrap) return;
            wrap.querySelectorAll('.bm-mega-col-editor').forEach(function(colEl, colIdx) {
                if (!_data[colIdx]) return;
                var w = colEl.querySelector('.bm-mega-col-width');
                if (w) _data[colIdx].width_pct = w.value;
            });
        }

        function render() {
            var wrap = document.getElementById('menux-mega-cols-wrap');
            if (!wrap) return;
            wrap.innerHTML = '';
            _data.forEach(function(col, colIdx) {
                wrap.appendChild(buildColEl(col, colIdx));
            });
            if (_data.length === 0) {
                wrap.innerHTML = '<div style="flex:1;display:flex;align-items:center;justify-content:center;padding:40px 24px;">'
                    + '<div style="text-align:center;max-width:460px;">'
                    + '<div style="font-size:48px;margin-bottom:12px;">✨</div>'
                    + '<h3 style="margin:0 0 8px;font-size:18px;font-weight:700;color:#1f2937;">First time here?</h3>'
                    + '<p style="margin:0 0 24px;font-size:13px;color:#6b7280;line-height:1.6;">Choose a ready-made template to get started — you can customize links, icons, colors and layout freely afterwards.</p>'
                    + '<button type="button" onclick="mxMegaDemoOpen()" style="background:linear-gradient(135deg,#4f46e5,#7c3aed);border:none;color:#fff;padding:11px 28px;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;box-shadow:0 4px 14px rgba(99,102,241,.35);">🎨 Choose a template</button>'
                    + '<div style="margin-top:16px;">'
                    + '<button type="button" onclick="menuxMegaAddCol()" style="background:none;border:none;color:#6b7280;font-size:12px;cursor:pointer;text-decoration:underline;">or start from scratch</button>'
                    + '</div>'
                    + '</div>'
                    + '</div>';
            }
            // Disable "+ Add Column" and count buttons > current length when at max
            var addBtn = document.querySelector('#menux-mega-dialog .bm-mega-col-footer button, #menux-mega-dialog button[onclick="menuxMegaAddCol()"]');
            renderPreview();
        }

        function htmlEsc(s) {
            if (!s) return '';
            return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
        }

        function renderPreview() {
            var wrap = document.getElementById('menux-mega-preview');
            if (!wrap) return;

            // Global defaults (PHP-injected) → per-item _style overrides take priority
            var D       = window.menuxMegaDefaults || {};
            var bg      = _style.bg      || D.bg      || '#ffffff';
            var padY    = (_style.pad_y !== '' && _style.pad_y !== undefined) ? Math.min(parseInt(_style.pad_y), 40) : (D.pad_y !== undefined ? D.pad_y : 16);
            var padX    = (_style.pad_x !== '' && _style.pad_x !== undefined) ? Math.min(parseInt(_style.pad_x), 60) : (D.pad_x !== undefined ? D.pad_x : 16);
            var gap     = (_style.gap   !== '' && _style.gap   !== undefined) ? parseInt(_style.gap)                 : (D.gap   !== undefined ? D.gap   : 12);
            var clrLink    = _style.link    || D.link    || '#374151';
            var clrHead    = _style.head    || D.head    || '#9ca3af';
            var clrDesc    = _style.desc    || D.desc    || '#9ca3af';
            var clrAccent  = _style.accent  || D.accent  || '#667eea';
            var clrDivider = _style.divider || D.divider || '#e5e7eb';
            var radius     = (_style.radius !== '' && _style.radius !== undefined) ? Math.min(parseInt(_style.radius), 40) : 8;
            var divStyle   = _style.divider_style || 'solid';

            if (_data.length === 0) {
                wrap.innerHTML = '<div style="color:#9ca3af;font-size:11px;text-align:center;padding:20px 0;">Add columns to see the preview</div>';
                return;
            }

            var maxW = (_style.max_w !== '' && _style.max_w !== undefined) ? parseInt(_style.max_w) : 0;
            var maxWCss = maxW > 0 ? 'max-width:' + maxW + 'px;margin-left:auto;margin-right:auto;' : '';
            var html = '<div style="background:' + htmlEsc(bg) + ';border-radius:0 0 ' + radius + 'px ' + radius + 'px;' + maxWCss + '">';
            html += '<div style="display:flex;gap:' + gap + 'px;padding:' + padY + 'px ' + padX + 'px;">';

            _data.forEach(function(col, ci) {
                var w = (col.width_pct && parseInt(col.width_pct) > 0) ? col.width_pct : null;
                var flex = w ? '0 0 ' + w + '%;max-width:' + w + '%' : '1';
                var padL = ci > 0 ? 'padding-left:' + gap + 'px;' : '';
                var colAlign = col.align || 'left';
                var alignCss = colAlign !== 'left' ? 'text-align:' + colAlign + ';' : '';
                html += '<div style="flex:' + flex + ';min-width:0;' + padL + alignCss + '">';

                (col.items || []).forEach(function(item) {
                    switch (item.type) {
                        case 'heading':
                            html += '<div style="font-size:8px;font-weight:700;color:' + (item.heading_color || clrHead) + ';text-transform:uppercase;letter-spacing:.7px;padding-bottom:5px;border-bottom:1px ' + divStyle + ' ' + clrDivider + ';margin-bottom:6px;">';
                            if (item.icon) html += '<i class="' + htmlEsc(item.icon) + '" style="margin-right:3px;font-size:8px;"></i>';
                            html += (htmlEsc(item.label) || '—') + '</div>';
                            break;
                        case 'divider':
                            html += '<hr style="border:none;border-top:1px ' + divStyle + ' ' + clrDivider + ';margin:5px 0;">';
                            break;
                        case 'image':
                            if (item.image_url) {
                                var imgW = item.image_width  ? item.image_width  + '%' : '100%';
                                var imgH = item.image_height ? item.image_height + '%' : 'auto';
                                html += '<img src="' + htmlEsc(item.image_url) + '" style="width:' + imgW + ';height:' + imgH + ';border-radius:5px;display:block;margin-bottom:5px;object-fit:cover;" alt="">';
                            } else {
                                html += '<div style="background:#e5e7eb;height:44px;border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:16px;margin-bottom:5px;">🖼</div>';
                            }
                            break;
                        case 'shortcode':
                            html += '<div style="background:#f0f4ff;border:1px dashed #a78bfa;border-radius:4px;padding:4px 6px;font-size:9px;color:#5b21b6;margin-bottom:4px;">⚙ ' + (htmlEsc(item.label) || 'Shortcode') + '</div>';
                            break;
                        case 'dynamic':
                            var dSrc = item.source === 'wc_cats' ? 'product categories' : 'recent posts';
                            var dN   = parseInt(item.dyn_count, 10) || 5;
                            html += '<div style="background:#f5f3ff;border:1px dashed #c4b5fd;border-radius:4px;padding:5px 7px;margin-bottom:4px;">';
                            html += '<div style="font-size:9px;color:#6d28d9;font-weight:600;margin-bottom:3px;">✨ ' + dN + ' ' + dSrc + '</div>';
                            for (var di = 0; di < Math.min(dN, 3); di++) {
                                html += '<div style="display:flex;align-items:center;gap:5px;padding:2px 0;">';
                                if (item.icon) html += '<i class="' + htmlEsc(item.icon) + '" style="font-size:10px;color:#667eea;"></i>';
                                html += '<span style="height:7px;width:' + (70 - di * 12) + '%;background:#ddd6fe;border-radius:3px;display:inline-block;"></span></div>';
                            }
                            if (item.dyn_view_all === '1') html += '<div style="font-size:9px;color:#7c3aed;font-weight:600;margin-top:3px;">' + (htmlEsc(item.dyn_view_all_label) || 'View all →') + '</div>';
                            html += '</div>';
                            break;
                        default:
                            html += '<div style="display:flex;align-items:flex-start;gap:6px;padding:3px 5px;border-radius:4px;margin-bottom:1px;justify-content:' + (colAlign === 'center' ? 'center' : colAlign === 'right' ? 'flex-end' : 'flex-start') + ';">';
                            if (item.icon) html += '<i class="' + htmlEsc(item.icon) + '" style="font-size:12px;color:' + clrAccent + ';flex-shrink:0;margin-top:1px;"></i>';
                            html += '<span>';
                            html += '<span style="display:block;font-size:11px;font-weight:500;color:' + (item.link_color || clrLink) + ';line-height:1.3;">' + (htmlEsc(item.label) || '<span style="color:#d1d5db;font-style:italic;">Link</span>') + '</span>';
                            if (item.desc) html += '<span style="display:block;font-size:9px;color:' + (item.desc_color || clrDesc) + ';">' + htmlEsc(item.desc) + '</span>';
                            html += '</span></div>';
                    }
                });

                if (!col.items || col.items.length === 0) {
                    html += '<div style="font-size:9px;color:#d1d5db;text-align:center;padding:10px 0;font-style:italic;">Empty</div>';
                }
                html += '</div>';
            });

            html += '</div></div>';
            wrap.innerHTML = html;
        }

        function buildColEl(col, colIdx) {
            var div = document.createElement('div');
            div.className = 'bm-mega-col-editor';

            var header = document.createElement('div');
            header.className = 'bm-mega-col-header';
            var _colAlign = col.align || 'left';
            var _dupDisabled = (_data.length >= MAX_COLS) ? ' disabled title="Max 4 columns"' : ' title="Duplicate column"';
            var _alignBtnsHtml = (function() {
                var h = '<div style="display:inline-flex;border:1px solid #d1d5db;border-radius:5px;overflow:hidden;">';
                [['left','L'],['center','C'],['right','R']].forEach(function(a) {
                    var active = _colAlign === a[0];
                    h += '<button type="button" class="bm-mega-align-btn" data-align="' + a[0] + '"'
                        + ' onclick="menuxMegaEditor.setColAlign(' + colIdx + ',\'' + a[0] + '\')"'
                        + ' style="background:' + (active ? '#4f46e5' : '#fff') + ';color:' + (active ? '#fff' : '#6b7280') + ';border:none;padding:3px 7px;font-size:11px;cursor:pointer;font-weight:700;" title="Align ' + a[0] + '">' + a[1] + '</button>';
                });
                return h + '</div>';
            }());
            header.innerHTML = '<span>Column ' + (colIdx + 1) + '</span>'
                + '<div style="display:flex;align-items:center;gap:6px;">'
                + _alignBtnsHtml
                + '<input type="number" class="bm-mega-col-width bm-input" value="' + (col.width_pct || '') + '" min="5" max="100" placeholder="auto" style="width:56px;font-size:11px;" title="Width %">'
                + '<span style="font-size:11px;color:#9ca3af;">%</span>'
                + '<button type="button" onclick="menuxMegaEditor.duplicateCol(' + colIdx + ')"' + _dupDisabled + ' style="background:none;border:none;color:#4f46e5;cursor:pointer;font-size:14px;line-height:1;padding:2px 4px;">&#10697;</button>'
                + '<button type="button" onclick="menuxMegaEditor.removeCol(' + colIdx + ')" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:16px;line-height:1;padding:2px 4px;" title="Remove column">&times;</button>'
                + '</div>';
            div.appendChild(header);

            // Persist width edits into _data immediately. Without this, the value
            // is only read by collectFromDOM() at save() time, so any re-render
            // (add/remove/reorder item) triggered before saving would rebuild the
            // input from stale _data and silently discard the typed width.
            var widthInput = header.querySelector('.bm-mega-col-width');
            if (widthInput) {
                widthInput.addEventListener('input', function() { col.width_pct = this.value; });
            }

            var itemsDiv = document.createElement('div');
            itemsDiv.className = 'bm-mega-col-items';
            (col.items || []).forEach(function(item, itemIdx) {
                itemsDiv.appendChild(buildItemEl(item, colIdx, itemIdx));
            });
            // Drop at end of column (empty column or after last item).
            itemsDiv.addEventListener('dragover', function(e) {
                if (!e.target.classList.contains('bm-mega-col-item')) {
                    e.preventDefault();
                    e.dataTransfer.dropEffect = 'move';
                    itemsDiv.classList.add('bm-drag-over-col');
                }
            });
            itemsDiv.addEventListener('dragleave', function(e) {
                if (!itemsDiv.contains(e.relatedTarget)) itemsDiv.classList.remove('bm-drag-over-col');
            });
            itemsDiv.addEventListener('drop', function(e) {
                if (e.target.classList.contains('bm-mega-col-item')) return;
                e.preventDefault();
                itemsDiv.classList.remove('bm-drag-over-col');
                var srcCol = _drag.colIdx, srcIdx = _drag.itemIdx;
                if (srcCol === -1) return;
                var moved = _data[srcCol].items.splice(srcIdx, 1)[0];
                _data[colIdx].items.push(moved);
                _drag.colIdx = _drag.itemIdx = -1;
                render();
            });
            div.appendChild(itemsDiv);

            var footer = document.createElement('div');
            footer.className = 'bm-mega-col-footer';
            footer.style.position = 'relative';

            var addBtn = document.createElement('button');
            addBtn.type = 'button';
            addBtn.style.cssText = 'width:100%;background:#f5f3ff;color:#4f46e5;border:1px dashed #a78bfa;padding:7px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;';
            addBtn.textContent = '+ Add Item';

            var menu = document.createElement('div');
            menu.className = 'bm-mega-add-item-menu';
            menu.style.cssText = 'display:none;position:absolute;bottom:100%;left:0;background:#fff;border:1px solid #e5e7eb;border-radius:8px;box-shadow:0 8px 20px rgba(0,0,0,.12);z-index:9999;padding:6px;min-width:160px;';
            var types = [
                { type:'link',      label:'Link' },
                { type:'heading',   label:'Section heading' },
                { type:'divider',   label:'Divider' },
                { type:'image',     label:'Image' },
                { type:'shortcode', label:'Shortcode / Widget' },
                { type:'dynamic',   label:'✨ Dynamic content' },
            ];
            types.forEach(function(t) {
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.style.cssText = 'display:block;width:100%;text-align:left;background:none;border:none;padding:7px 10px;font-size:12px;color:#374151;cursor:pointer;border-radius:5px;';
                btn.textContent = t.label;
                btn.onmouseenter = function() { this.style.background='#f0f4ff'; this.style.color='#4f46e5'; };
                btn.onmouseleave = function() { this.style.background=''; this.style.color='#374151'; };
                btn.onclick = (function(type, ci) {
                    return function() {
                        menu.style.display = 'none';
                        menuxMegaEditor.addItem(ci, type);
                    };
                })(t.type, colIdx);
                menu.appendChild(btn);
            });

            addBtn.onclick = function(e) {
                e.stopPropagation();
                menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
            };
            _bindAddMenuAutoClose();

            footer.appendChild(addBtn);
            footer.appendChild(menu);
            div.appendChild(footer);

            return div;
        }

        function buildItemEl(item, colIdx, itemIdx) {
            var el = document.createElement('div');
            el.className = 'bm-mega-col-item';
            el.setAttribute('data-item-idx', itemIdx);
            el.draggable = true;

            var typeColors = { link:'#e0e7ff', heading:'#fef3c7', divider:'#f3f4f6', image:'#d1fae5', shortcode:'#fee2e2', dynamic:'#ede9fe' };
            var typeColor  = typeColors[item.type] || '#e0e7ff';

            var lbl;
            if (item.type === 'dynamic') {
                var srcName = item.source === 'wc_cats' ? 'product categories' : 'recent posts';
                lbl = '✨ ' + (item.dyn_count || '5') + ' ' + srcName;
            } else {
                lbl = item.label || (item.type === 'divider' ? '— divider —' : item.type);
            }
            el.innerHTML = '<span style="cursor:grab;color:#9ca3af;margin-right:2px;user-select:none;">⠿</span>'
                + '<span class="bm-mega-col-item-type" style="background:' + typeColor + ';color:#374151;">' + item.type + '</span>'
                + '<span class="bm-mega-col-item-label">' + htmlEsc(lbl.substring(0, 40)) + '</span>'
                + '<button type="button" onclick="menuxMegaEditor.editItem(' + colIdx + ',' + itemIdx + ')" '
                + 'style="background:#4f46e5;border:none;border-radius:6px;padding:4px 12px;font-size:12px;font-weight:600;cursor:pointer;color:#fff;margin-left:auto;white-space:nowrap;" title="Edit">✏️ Edit</button>'
                + '<button type="button" onclick="menuxMegaEditor.removeItem(' + colIdx + ',' + itemIdx + ')" '
                + 'style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:14px;padding:2px 4px;" title="Remove">&times;</button>';

            el.addEventListener('dragstart', function(e) {
                _drag.colIdx  = colIdx;
                _drag.itemIdx = itemIdx;
                e.dataTransfer.effectAllowed = 'move';
                setTimeout(function() { el.classList.add('bm-dragging'); }, 0);
            });
            el.addEventListener('dragend', function() {
                el.classList.remove('bm-dragging');
                document.querySelectorAll('.bm-drag-over').forEach(function(x) { x.classList.remove('bm-drag-over'); });
            });
            el.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                el.classList.add('bm-drag-over');
            });
            el.addEventListener('dragleave', function() {
                el.classList.remove('bm-drag-over');
            });
            el.addEventListener('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                el.classList.remove('bm-drag-over');
                var srcCol = _drag.colIdx, srcIdx = _drag.itemIdx;
                var dstCol = colIdx,       dstIdx = itemIdx;
                if (srcCol === -1 || (srcCol === dstCol && srcIdx === dstIdx)) return;
                var moved = _data[srcCol].items.splice(srcIdx, 1)[0];
                if (srcCol === dstCol && srcIdx < dstIdx) dstIdx--;
                _data[dstCol].items.splice(dstIdx, 0, moved);
                _drag.colIdx = _drag.itemIdx = -1;
                render();
            });

            return el;
        }

        var MAX_COLS = 4;

        function addCol() {
            if (_data.length >= MAX_COLS) return;
            _data.push(newCol());
            render();
        }

        function duplicateCol(colIdx) {
            if (_data.length >= MAX_COLS) return;
            var clone = JSON.parse(JSON.stringify(_data[colIdx]));
            _data.splice(colIdx + 1, 0, clone);
            render();
        }

        function setColAlign(colIdx, align) {
            if (!_data[colIdx]) return;
            _data[colIdx].align = align;
            render();
        }

        function removeCol(colIdx) {
            _data.splice(colIdx, 1);
            render();
        }

        function setCols(n) {
            n = Math.min(n, MAX_COLS);
            while (_data.length < n) _data.push(newCol());
            _data = _data.slice(0, n);
            render();

            document.querySelectorAll('.bm-mega-col-count-btn').forEach(function(btn) {
                var active = parseInt(btn.getAttribute('data-cols'), 10) === n;
                btn.style.borderColor = active ? '#4f46e5' : '#e5e7eb';
                btn.style.background  = active ? '#eef2ff' : '#fff';
                btn.style.color       = active ? '#4f46e5' : '#374151';
            });
        }

        function addItem(colIdx, type) {
            if (!_data[colIdx]) return;
            _data[colIdx].items = _data[colIdx].items || [];
            var item = newItem(type);
            _data[colIdx].items.push(item);
            var newIdx = _data[colIdx].items.length - 1;
            render();
            editItem(colIdx, newIdx);
        }

        function removeItem(colIdx, itemIdx) {
            if (!_data[colIdx] || !_data[colIdx].items) return;
            _data[colIdx].items.splice(itemIdx, 1);
            render();
        }

        var _itemTypeFields = {
            'link':      ['label','url','icon','desc','link_color','desc_color','target'],
            'heading':   ['label','icon','heading_color'],
            'divider':   [],
            'image':     ['label','image_url','image_width','image_height','url','target'],
            'shortcode': ['label','content'],
        };

        function editItem(colIdx, itemIdx) {
            if (!_data[colIdx] || !_data[colIdx].items[itemIdx]) return;
            var item = _data[colIdx].items[itemIdx];

            var overlay = document.getElementById('menux-mega-item-edit-overlay');
            if (!overlay) {
                overlay = document.createElement('div');
                overlay.id = 'menux-mega-item-edit-overlay';
                overlay.style.cssText = 'display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1000001;align-items:center;justify-content:center;';
                document.body.appendChild(overlay);
            }

            // Dynamic blocks get a purpose-built form (dropdowns + toggle).
            if (item.type === 'dynamic') {
                editDynamicItem(item, colIdx, itemIdx, overlay);
                return;
            }

            var fields = _itemTypeFields;
            var activeFields = fields[item.type] || ['label','url'];

            var formHTML = '<div style="background:#fff;border-radius:12px;padding:24px;width:min(480px,95vw);box-shadow:0 16px 40px rgba(0,0,0,.2);">';
            formHTML += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;">';
            formHTML += '<h3 style="margin:0;font-size:15px;font-weight:700;color:#1f2937;">Edit item — <em>' + item.type + '</em></h3>';
            formHTML += '<button type="button" onclick="menuxMegaEditor.closeItemEdit()" style="background:none;border:none;font-size:22px;cursor:pointer;color:#6b7280;">&times;</button>';
            formHTML += '</div>';

            var labelMap = { label:'Label', url:'Link URL', icon:'Icon (FontAwesome)', desc:'Description', desc_color:'Description color', link_color:'Link color', heading_color:'Heading color', target:'Open in new tab', image_url:'Image', image_width:'Width (%)', image_height:'Height (%)', content:'Shortcode / Content' };

            activeFields.forEach(function(f) {
                formHTML += '<div style="margin-bottom:12px;">';
                formHTML += '<label style="display:block;font-size:12px;font-weight:600;color:#374151;margin-bottom:4px;">' + (labelMap[f] || f) + '</label>';
                if (f === 'target') {
                    formHTML += '<label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;">'
                        + '<input type="checkbox" id="mega-edit-' + f + '" ' + (item[f] === '_blank' ? 'checked' : '') + '>'
                        + ' Open in new tab</label>';
                } else if (f === 'content') {
                    formHTML += '<textarea id="mega-edit-' + f + '" rows="4" style="width:100%;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">' + htmlEsc(item[f] || '') + '</textarea>';
                } else if (f === 'icon') {
                    formHTML += '<div style="display:flex;gap:6px;align-items:center;">'
                        + '<input type="text" id="mega-edit-icon" value="' + (item[f] || '') + '" placeholder="e.g. fa-solid fa-house" style="flex:1;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">'
                        + '<button type="button" onclick="mxIconPicker.open(document.getElementById(\'mega-edit-icon\'))" style="padding:0 12px;height:36px;border:1px solid #d1d5db;border-radius:6px;background:#f9fafb;cursor:pointer;font-size:13px;white-space:nowrap;" title="Pick icon">🎨 Pick</button>'
                        + '</div>';
                } else if (f === 'desc_color' || f === 'link_color' || f === 'heading_color') {
                    var cVal  = item[f] || '';
                    var cDef  = (f === 'link_color') ? '#374151' : '#9ca3af';
                    var hexId = 'mega-' + f + '-hex';
                    var rstId = 'mega-' + f + '-reset';
                    formHTML += '<div style="display:flex;align-items:center;gap:8px;">'
                        + '<input type="color" id="mega-edit-' + f + '" value="' + (cVal || cDef) + '" style="width:38px;height:32px;padding:2px;border:1px solid #d1d5db;border-radius:6px;cursor:pointer;" oninput="document.getElementById(\'' + hexId + '\').textContent=this.value">'
                        + '<span id="' + hexId + '" style="font-size:12px;color:#6b7280;font-family:monospace;">' + (cVal || cDef) + '</span>'
                        + '<label style="display:inline-flex;align-items:center;gap:5px;font-size:12px;color:#6b7280;cursor:pointer;margin-left:8px;">'
                        + '<input type="checkbox" id="' + rstId + '" ' + (!cVal ? 'checked' : '') + ' onchange="var p=document.getElementById(\'mega-edit-' + f + '\');var h=document.getElementById(\'' + hexId + '\');if(this.checked){p.dataset.orig=p.value;p.value=\'' + cDef + '\';h.textContent=\'default\';}else{p.value=p.dataset.orig||\'' + cDef + '\';h.textContent=p.value;}">'
                        + ' Use default</label>'
                        + '</div>';
                } else if (f === 'image_url') {
                    formHTML += '<div style="display:flex;gap:6px;align-items:center;">'
                        + '<input type="text" id="mega-edit-image_url" value="' + (item.image_url || '') + '" placeholder="https://… or use Upload" style="flex:1;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">'
                        + '<button type="button" onclick="mxMegaUploadImg()" style="padding:0 12px;height:36px;border:1px solid #d1d5db;border-radius:6px;background:#f9fafb;cursor:pointer;font-size:13px;white-space:nowrap;" title="Upload from Media Library">📁 Upload</button>'
                        + '</div>'
                        + (item.image_url ? '<img id="mega-img-preview" src="' + item.image_url + '" style="margin-top:8px;max-width:100%;max-height:80px;border-radius:6px;border:1px solid #e5e7eb;" alt="">' : '<span id="mega-img-preview"></span>');
                } else if (f === 'image_width' || f === 'image_height') {
                    formHTML += '<div style="display:flex;align-items:center;gap:6px;">'
                        + '<input type="number" id="mega-edit-' + f + '" value="' + (item[f] || '') + '" min="1" max="100" placeholder="auto" style="width:80px;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">'
                        + '<span style="font-size:12px;color:#6b7280;">% &nbsp;<em style="font-weight:400;">(leave empty for auto)</em></span>'
                        + '</div>';
                } else {
                    formHTML += '<input type="text" id="mega-edit-' + f + '" value="' + htmlEsc(item[f] || '') + '" style="width:100%;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">';
                }
                formHTML += '</div>';
            });

            formHTML += '<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:18px;">';
            formHTML += '<button type="button" onclick="menuxMegaEditor.closeItemEdit()" style="background:#fff;border:1px solid #d1d5db;color:#374151;padding:8px 18px;border-radius:7px;font-size:13px;cursor:pointer;">Cancel</button>';
            formHTML += '<button type="button" onclick="menuxMegaEditor.applyItemEdit(' + colIdx + ',' + itemIdx + ')" style="background:linear-gradient(135deg,#4f46e5,#7c3aed);border:none;color:#fff;padding:8px 20px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;">Apply</button>';
            formHTML += '</div>';
            formHTML += '</div>';

            overlay.innerHTML = formHTML;
            overlay.style.display = 'flex';
        }

        // Builds the <option> list for the orderby dropdown of a given source.
        function dynOrderbyOptions(source, selected) {
            var opts = DYN_ORDERBY[source] || DYN_ORDERBY.posts;
            return opts.map(function(o) {
                var sel = (o[0] === selected) ? ' selected' : '';
                return '<option value="' + o[0] + '"' + sel + '>' + htmlEsc(o[1]) + '</option>';
            }).join('');
        }

        // Repopulates the orderby dropdown when the source changes, resetting
        // the selection to that source's first (default) option.
        window.mxDynSourceChange = function(sel) {
            var ob = document.getElementById('mega-edit-dyn_orderby');
            if (ob) ob.innerHTML = dynOrderbyOptions(sel.value, null);
            var ptRow = document.getElementById('mega-dyn-posttype-row');
            if (ptRow) ptRow.style.display = (sel.value === 'posts') ? '' : 'none';
        };

        function editDynamicItem(item, colIdx, itemIdx, overlay) {
            var fieldCss = 'width:100%;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;background:#fff;';
            var lblCss   = 'display:block;font-size:12px;font-weight:600;color:#374151;margin-bottom:4px;';
            var source   = item.source === 'wc_cats' ? 'wc_cats' : 'posts';

            var h = '<div style="background:#fff;border-radius:12px;padding:24px;width:min(480px,95vw);box-shadow:0 16px 40px rgba(0,0,0,.2);max-height:90vh;overflow-y:auto;">';
            h += '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;">';
            h += '<h3 style="margin:0;font-size:15px;font-weight:700;color:#1f2937;">✨ Dynamic content</h3>';
            h += '<button type="button" onclick="menuxMegaEditor.closeItemEdit()" style="background:none;border:none;font-size:22px;cursor:pointer;color:#6b7280;">&times;</button>';
            h += '</div>';

            h += '<p style="margin:0 0 16px;font-size:11px;color:#6b7280;line-height:1.5;background:#f5f3ff;border:1px solid #ede9fe;border-radius:8px;padding:10px 12px;">This block fills itself automatically: it lists your latest posts or your WooCommerce categories, and stays up to date as you publish new content.</p>';

            // Source
            h += '<div style="margin-bottom:12px;"><label style="' + lblCss + '">Content source</label>';
            h += '<select id="mega-edit-source" onchange="mxDynSourceChange(this)" style="' + fieldCss + '">';
            h += '<option value="posts"' + (source === 'posts' ? ' selected' : '') + '>Recent posts</option>';
            h += '<option value="wc_cats"' + (source === 'wc_cats' ? ' selected' : '') + '>WooCommerce product categories</option>';
            h += '</select></div>';

            // Post type (only for posts)
            h += '<div id="mega-dyn-posttype-row" style="margin-bottom:12px;' + (source === 'posts' ? '' : 'display:none;') + '">';
            h += '<label style="' + lblCss + '">Post type</label>';
            h += '<input type="text" id="mega-edit-dyn_post_type" value="' + htmlEsc(item.dyn_post_type || 'post') + '" placeholder="post" style="' + fieldCss + '">';
            h += '<span style="display:block;font-size:11px;color:#9ca3af;margin-top:3px;">Slug of the post type to list (default: <code>post</code>).</span></div>';

            // Count + Orderby row
            h += '<div style="display:flex;gap:12px;margin-bottom:12px;">';
            h += '<div style="flex:0 0 110px;"><label style="' + lblCss + '">How many</label>';
            h += '<input type="number" id="mega-edit-dyn_count" value="' + htmlEsc(item.dyn_count || '5') + '" min="1" max="20" style="' + fieldCss + '"></div>';
            h += '<div style="flex:1;"><label style="' + lblCss + '">Order by</label>';
            h += '<select id="mega-edit-dyn_orderby" style="' + fieldCss + '">' + dynOrderbyOptions(source, item.dyn_orderby) + '</select></div>';
            h += '</div>';

            // Icon
            h += '<div style="margin-bottom:12px;"><label style="' + lblCss + '">Icon (applied to every link)</label>';
            h += '<div style="display:flex;gap:6px;align-items:center;">';
            h += '<input type="text" id="mega-edit-icon" value="' + htmlEsc(item.icon || '') + '" placeholder="e.g. fa-solid fa-newspaper" style="flex:1;font-size:12px;border:1px solid #d1d5db;border-radius:6px;padding:8px;box-sizing:border-box;">';
            h += '<button type="button" onclick="mxIconPicker.open(document.getElementById(\'mega-edit-icon\'))" style="padding:0 12px;height:36px;border:1px solid #d1d5db;border-radius:6px;background:#f9fafb;cursor:pointer;font-size:13px;white-space:nowrap;" title="Pick icon">🎨 Pick</button>';
            h += '</div></div>';

            // View all toggle + label
            h += '<div style="margin-bottom:6px;padding-top:6px;border-top:1px solid #f3f4f6;">';
            h += '<label style="display:inline-flex;align-items:center;gap:7px;cursor:pointer;font-size:13px;color:#374151;font-weight:600;">';
            h += '<input type="checkbox" id="mega-edit-dyn_view_all" ' + (item.dyn_view_all === '1' ? 'checked' : '') + ' onchange="document.getElementById(\'mega-dyn-viewall-row\').style.display=this.checked?\'\':\'none\';">';
            h += ' Add a “View all →” link at the end</label></div>';
            h += '<div id="mega-dyn-viewall-row" style="margin-bottom:12px;' + (item.dyn_view_all === '1' ? '' : 'display:none;') + '">';
            h += '<input type="text" id="mega-edit-dyn_view_all_label" value="' + htmlEsc(item.dyn_view_all_label || '') + '" placeholder="View all →" style="' + fieldCss + '">';
            h += '<span style="display:block;font-size:11px;color:#9ca3af;margin-top:3px;">Links to the blog page (posts) or the shop page (categories). Leave empty for the default text.</span></div>';

            h += '<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:18px;">';
            h += '<button type="button" onclick="menuxMegaEditor.closeItemEdit()" style="background:#fff;border:1px solid #d1d5db;color:#374151;padding:8px 18px;border-radius:7px;font-size:13px;cursor:pointer;">Cancel</button>';
            h += '<button type="button" onclick="menuxMegaEditor.applyItemEdit(' + colIdx + ',' + itemIdx + ')" style="background:linear-gradient(135deg,#4f46e5,#7c3aed);border:none;color:#fff;padding:8px 20px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;">Apply</button>';
            h += '</div></div>';

            overlay.innerHTML = h;
            overlay.style.display = 'flex';
        }

        function closeItemEdit() {
            var overlay = document.getElementById('menux-mega-item-edit-overlay');
            if (overlay) overlay.style.display = 'none';
        }

        function applyItemEdit(colIdx, itemIdx) {
            if (!_data[colIdx] || !_data[colIdx].items[itemIdx]) return;
            var item   = _data[colIdx].items[itemIdx];

            if (item.type === 'dynamic') {
                var srcEl = document.getElementById('mega-edit-source');
                var src   = (srcEl && srcEl.value === 'wc_cats') ? 'wc_cats' : 'posts';
                item.source = src;
                var cntEl = document.getElementById('mega-edit-dyn_count');
                var cnt   = cntEl ? parseInt(cntEl.value, 10) : 5;
                if (isNaN(cnt) || cnt < 1) cnt = 1; if (cnt > 20) cnt = 20;
                item.dyn_count = String(cnt);
                var obEl = document.getElementById('mega-edit-dyn_orderby');
                item.dyn_orderby = obEl ? obEl.value : 'date';
                var ptEl = document.getElementById('mega-edit-dyn_post_type');
                item.dyn_post_type = (ptEl && ptEl.value.trim()) ? ptEl.value.trim() : 'post';
                var icEl = document.getElementById('mega-edit-icon');
                item.icon = icEl ? icEl.value : '';
                var vaEl = document.getElementById('mega-edit-dyn_view_all');
                item.dyn_view_all = (vaEl && vaEl.checked) ? '1' : '';
                var valEl = document.getElementById('mega-edit-dyn_view_all_label');
                item.dyn_view_all_label = valEl ? valEl.value : '';
                closeItemEdit();
                render();
                return;
            }

            var fields = _itemTypeFields;
            var activeFields = fields[item.type] || ['label','url'];

            activeFields.forEach(function(f) {
                if (f === 'desc_color' || f === 'link_color' || f === 'heading_color') {
                    var resetCb = document.getElementById('mega-' + f + '-reset');
                    if (resetCb && resetCb.checked) {
                        item[f] = '';
                    } else {
                        var el = document.getElementById('mega-edit-' + f);
                        item[f] = el ? el.value : '';
                    }
                    return;
                }
                var el = document.getElementById('mega-edit-' + f);
                if (!el) return;
                if (f === 'target') {
                    item[f] = el.checked ? '_blank' : '';
                } else {
                    item[f] = el.value || '';
                }
            });

            closeItemEdit();
            render();
        }

        function applyPreset(d) {
            if (d.gradient) _style.bg = d.gradient;
            if (d.palette) {
                if (d.palette.heading) _style.head   = d.palette.heading;
                if (d.palette.link)    _style.link   = d.palette.link;
                if (d.palette.desc)    _style.desc   = d.palette.desc;
                if (d.palette.accent)  _style.accent = d.palette.accent;
                if (d.palette.hover)   _style.hover  = d.palette.hover;
            }
            if (d.look) {
                if (d.look.radius  !== undefined && d.look.radius  !== '') _style.radius = d.look.radius;
                if (d.look.pad_y   !== undefined && d.look.pad_y   !== '') _style.pad_y  = d.look.pad_y;
                if (d.look.pad_x   !== undefined && d.look.pad_x   !== '') _style.pad_x  = d.look.pad_x;
                if (d.look.gap     !== undefined && d.look.gap     !== '') _style.gap    = d.look.gap;
                if (d.look.divider !== undefined && d.look.divider !== '') _style.divider_style = d.look.divider;
            }
            _populateAppearance();
        }

        function loadDemo(idx) {
            var d = mxMegaDemos[idx];
            if (!d) return;
            _data = JSON.parse(JSON.stringify(d.cols));
            if (d.palette) {
                _data.forEach(function(col) {
                    (col.items || []).forEach(function(it) {
                        if (it.type === 'link' && it.desc) it.desc_color = d.palette.desc || '';
                    });
                });
            }
            applyPreset(d);
            render();
            renderPreview();
            mxMegaDemoClose();
        }

        function menuxMegaSwitchTab(tab) {
            _activeTab = tab;
            var cols    = document.getElementById('menux-mega-cols-wrap');
            var appear  = document.getElementById('menux-mega-appearance-panel');
            var tools   = document.getElementById('menux-mega-content-tools');
            var btnC    = document.getElementById('menux-mega-tab-content-btn');
            var btnA    = document.getElementById('menux-mega-tab-appear-btn');
            var isC = tab === 'content';
            if (cols)   cols.style.display   = isC ? 'flex' : 'none';
            if (appear) appear.style.display = isC ? 'none' : 'block';
            // The toolbar itself stays visible: it hosts the tab switcher, so hiding
            // it would strand the user on the Appearance tab. Only the content tools
            // toggle. The live preview stays visible on both tabs — Appearance edits
            // re-render it live via _bindAppearanceLive().
            if (tools)  tools.style.display  = isC ? 'flex' : 'none';
            if (btnC) { btnC.style.background = isC ? '#fff' : 'transparent'; btnC.style.color = isC ? '#4f46e5' : '#6b7280'; btnC.style.boxShadow = isC ? '0 1px 3px rgba(0,0,0,.1)' : 'none'; }
            if (btnA) { btnA.style.background = isC ? 'transparent' : '#fff'; btnA.style.color = isC ? '#6b7280' : '#4f46e5'; btnA.style.boxShadow = isC ? 'none' : '0 1px 3px rgba(0,0,0,.1)'; }
            // Re-render so the preview reflects any column edits made before switching tabs.
            renderPreview();
        }

        function _populateAppearance() {
            var bgVal = document.getElementById('bm-ms-bg-val');
            var bgSw  = document.getElementById('bm-ms-bg-swatch');
            if (bgVal) bgVal.value = _style.bg || '';
            if (bgSw)  bgSw.style.background = _style.bg || 'transparent';
            function setNum(id, val) { var e = document.getElementById(id); if (e) e.value = (val !== undefined && val !== '') ? val : ''; }
            setNum('bm-ms-pad-y',  _style.pad_y);
            setNum('bm-ms-pad-x',  _style.pad_x);
            setNum('bm-ms-gap',    _style.gap);
            setNum('bm-ms-radius', _style.radius);
            setNum('bm-ms-font',   _style.font_size);
            setNum('bm-ms-max-w',  _style.max_w);
            function setColor(field, colorId, checkId) {
                var cp = document.getElementById(colorId);
                var cb = document.getElementById(checkId);
                if (_style[field]) { if (cp) cp.value = _style[field]; if (cb) cb.checked = true; }
                else                { if (cb) cb.checked = false; }
            }
            setColor('link',    'bm-ms-link',    'bm-ms-link-use');
            setColor('head',    'bm-ms-head',    'bm-ms-head-use');
            setColor('accent',  'bm-ms-accent',  'bm-ms-accent-use');
            setColor('hover',   'bm-ms-hover',   'bm-ms-hover-use');
            setColor('desc',    'bm-ms-desc',    'bm-ms-desc-use');
            setColor('divider', 'bm-ms-divider', 'bm-ms-divider-use');
            var ds = document.getElementById('bm-ms-divider-style');
            if (ds) ds.value = _style.divider_style || '';
            _syncMaxWState();
        }

        function _collectAppearance() {
            var bgVal = document.getElementById('bm-ms-bg-val');
            _style.bg = (bgVal && bgVal.value) ? bgVal.value : '';
            function getNum(id) { var e = document.getElementById(id); return (e && e.value.trim() !== '') ? e.value.trim() : ''; }
            _style.pad_y     = getNum('bm-ms-pad-y');
            _style.pad_x     = getNum('bm-ms-pad-x');
            _style.gap       = getNum('bm-ms-gap');
            _style.radius    = getNum('bm-ms-radius');
            _style.font_size = getNum('bm-ms-font');
            _style.max_w     = getNum('bm-ms-max-w');
            function getColor(colorId, checkId) { var cp = document.getElementById(colorId); var cb = document.getElementById(checkId); return (cb && cb.checked && cp && cp.value) ? cp.value : ''; }
            _style.link          = getColor('bm-ms-link',    'bm-ms-link-use');
            _style.head          = getColor('bm-ms-head',    'bm-ms-head-use');
            _style.accent        = getColor('bm-ms-accent',  'bm-ms-accent-use');
            _style.hover         = getColor('bm-ms-hover',   'bm-ms-hover-use');
            _style.desc          = getColor('bm-ms-desc',    'bm-ms-desc-use');
            _style.divider       = getColor('bm-ms-divider', 'bm-ms-divider-use');
            var ds = document.getElementById('bm-ms-divider-style');
            _style.divider_style = (ds && ds.value) ? ds.value : '';
        }

        function menuxMegaResetStyle() {
            _style = {};
            _populateAppearance();
        }

        // Live-update the preview when any Appearance field changes. Bound once
        // (delegated on the panel) so editing padding, gap, radius, colors or the
        // divider style reflects in the preview immediately — not just background.
        // Single document-level handler that closes every open "+ Add Item" menu.
        // Bound once instead of once-per-column-per-render (which leaked a new
        // listener referencing a detached menu node on every editor render).
        var _addMenuDocBound = false;
        function _bindAddMenuAutoClose() {
            if (_addMenuDocBound) return;
            document.addEventListener('click', function() {
                document.querySelectorAll('.bm-mega-add-item-menu').forEach(function(m) {
                    m.style.display = 'none';
                });
            });
            _addMenuDocBound = true;
        }

        var _appearanceBound = false;
        function _bindAppearanceLive() {
            if (_appearanceBound) return;
            var panel = document.getElementById('menux-mega-appearance-panel');
            if (!panel) return;
            var handler = function() { _collectAppearance(); renderPreview(); };
            panel.addEventListener('input',  handler);
            panel.addEventListener('change', handler);
            _appearanceBound = true;
        }

        // Grey-out and disable the Panel Max Width field when the panel is not
        // full-width: margin:auto only centers a position:absolute element when
        // both left:0 and right:0 are set, which only holds for full-width panels.
        function _syncMaxWState() {
            var fwChk  = _activeKey ? document.getElementById('bm-mega-full-' + _activeKey) : null;
            var isFull = fwChk ? fwChk.checked : true;
            var el     = document.getElementById('bm-ms-max-w');
            if (!el) return;
            el.disabled = !isFull;
            var row = el.parentNode;
            if (row) {
                row.style.opacity = isFull ? '' : '0.4';
                row.title = isFull ? '' : 'Panel Max Width requires "Full width" to be enabled';
            }
        }

        function setStyleBg(val) {
            // Preserve any unsaved edits the user made to the other Appearance
            // fields before _populateAppearance() rewrites every input from _style.
            _collectAppearance();
            _style.bg = val || '';
            _populateAppearance();
            renderPreview();
        }

        return {
            open:          open,
            close:         close,
            save:          save,
            addCol:        addCol,
            duplicateCol:  duplicateCol,
            setColAlign:   setColAlign,
            removeCol:     removeCol,
            setCols:       setCols,
            addItem:       addItem,
            removeItem:    removeItem,
            editItem:      editItem,
            closeItemEdit: closeItemEdit,
            applyItemEdit: applyItemEdit,
            renderPreview: renderPreview,
            loadDemo:      loadDemo,
            switchTab:     menuxMegaSwitchTab,
            resetStyle:    menuxMegaResetStyle,
            setStyleBg:    setStyleBg,
        };
    })();

    function menuxMegaOpen(key)   { menuxMegaEditor.open(key); }
    function menuxMegaClose()     { menuxMegaEditor.close(); }
    function menuxMegaSave()      { menuxMegaEditor.save(); }
    function menuxMegaAddCol()    { menuxMegaEditor.addCol(); }
    function menuxMegaSetCols(n)  { menuxMegaEditor.setCols(n); }
    function menuxMegaSwitchTab(t){ menuxMegaEditor.switchTab(t); }
    function menuxMegaResetStyle(){ menuxMegaEditor.resetStyle(); }
    function menuxMegaSetStyleBg(v){ menuxMegaEditor.setStyleBg(v); }

    // ── Gradient / Background picker ──────────────────────────────────
    function mxMegaBgPick(val) {
        // Update per-item _style.bg and sync the Appearance tab UI
        if (menuxMegaEditor && menuxMegaEditor.setStyleBg) {
            menuxMegaEditor.setStyleBg(val);
        }
    }
    function mxMegaBgCustom() {
        var dir = (document.getElementById('bm-grad-dir') || {}).value || '135deg';
        var c1  = (document.getElementById('bm-grad-c1') || {}).value  || '#4f46e5';
        var c2  = (document.getElementById('bm-grad-c2') || {}).value  || '#7c3aed';
        mxMegaBgPick('linear-gradient(' + dir + ',' + c1 + ' 0%,' + c2 + ' 100%)');
    }

    // ── Demo template picker ──────────────────────────────────────────
    function mxMegaDemoOpen() {
        var el = document.getElementById('mx-demo-picker');
        if (!el) { el = _mxBuildDemoModal(); }
        el.style.display = 'flex';
    }
    function mxMegaDemoClose() {
        var el = document.getElementById('mx-demo-picker');
        if (el) el.style.display = 'none';
    }
    function mxMegaUploadImg() {
        if (typeof wp === 'undefined' || !wp.media) { alert('WordPress Media Library is not available.'); return; }
        var frame = wp.media({ title: 'Choose an Image', button: { text: 'Use this image' }, multiple: false, library: { type: ['image'] } });
        frame.on('select', function() {
            var att = frame.state().get('selection').first().toJSON();
            var urlInput = document.getElementById('mega-edit-image_url');
            if (urlInput) {
                urlInput.value = att.url || '';
                var preview = document.getElementById('mega-img-preview');
                if (preview) { preview.tagName === 'IMG' ? (preview.src = att.url) : (preview.outerHTML = '<img id="mega-img-preview" src="' + att.url + '" style="margin-top:8px;max-width:100%;max-height:80px;border-radius:6px;border:1px solid #e5e7eb;" alt="">'); }
            }
        });
        frame.open();
    }
    function _mxBuildDemoModal() {
        var wrap = document.createElement('div');
        wrap.id = 'mx-demo-picker';
        wrap.style.cssText = 'display:none;position:fixed;inset:0;background:rgba(0,0,0,.78);z-index:1000020;align-items:flex-start;justify-content:center;padding:24px;overflow-y:auto;';
        wrap.onclick = function(e) { if (e.target === wrap) mxMegaDemoClose(); };

        var cards = mxMegaDemos.map(function(d, i) {
            // Mini column preview: each column = a small rectangle with placeholder bars
            var colPreviews = d.cols.map(function(col) {
                var bars = col.items.slice(0, 5).map(function(it) {
                    if (it.type === 'divider') {
                        return '<div style="height:1px;background:#d1d5db;margin:4px 0;"></div>';
                    }
                    var isHeading = it.type === 'heading';
                    return '<div style="height:' + (isHeading ? '6' : '4') + 'px;border-radius:2px;background:'
                        + (isHeading ? '#6366f1' : '#cbd5e1') + ';margin-bottom:' + (isHeading ? '5' : '3') + 'px;opacity:' + (isHeading ? '1' : '0.75') + ';"></div>';
                }).join('');
                return '<div style="flex:1;background:#f1f5f9;border-radius:5px;padding:7px 5px;min-width:0;">' + bars + '</div>';
            }).join('');

            return '<div style="border:2px solid #e5e7eb;border-radius:12px;overflow:hidden;cursor:default;transition:border-color .15s,box-shadow .15s;"'
                + ' onmouseenter="this.style.borderColor=\'#6366f1\';this.style.boxShadow=\'0 4px 20px rgba(99,102,241,.18)\'"'
                + ' onmouseleave="this.style.borderColor=\'#e5e7eb\';this.style.boxShadow=\'none\'">'
                + '<div style="height:48px;background:' + d.gradient + ';"></div>'
                + '<div style="padding:14px;">'
                + '<div style="font-size:13px;font-weight:700;color:#111827;margin-bottom:3px;">' + d.name + '</div>'
                + '<div style="font-size:11px;color:#6b7280;margin-bottom:10px;">' + d.desc + '</div>'
                + '<div style="display:flex;gap:4px;margin-bottom:12px;">' + colPreviews + '</div>'
                + '<button type="button" onclick="menuxMegaEditor.loadDemo(' + i + ')"'
                + ' style="width:100%;background:linear-gradient(135deg,#4f46e5,#7c3aed);border:none;color:#fff;padding:7px 0;border-radius:7px;font-size:12px;font-weight:700;cursor:pointer;">Apply →</button>'
                + '</div>'
                + '</div>';
        }).join('');

        wrap.innerHTML = '<div style="background:#fff;border-radius:16px;box-shadow:0 24px 64px rgba(0,0,0,.35);width:min(1100px,98vw);font-family:-apple-system,sans-serif;overflow:hidden;">'
            // Header
            + '<div style="background:linear-gradient(135deg,#4f46e5,#7c3aed);padding:14px 24px;display:flex;align-items:center;justify-content:space-between;">'
            + '<div><div style="color:rgba(255,255,255,.65);font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:2px;">Mega Menu</div>'
            + '<div style="color:#fff;font-size:16px;font-weight:700;">✨ Preset Templates</div></div>'
            + '<button type="button" onclick="mxMegaDemoClose()" style="background:rgba(255,255,255,.15);border:none;color:#fff;width:32px;height:32px;border-radius:50%;cursor:pointer;font-size:20px;line-height:1;display:flex;align-items:center;justify-content:center;">&times;</button>'
            + '</div>'
            // Subtitle
            + '<div style="padding:10px 24px;background:#fafafa;border-bottom:1px solid #e5e7eb;">'
            + '<p style="margin:0;font-size:12px;color:#6b7280;">' + mxMegaDemos.length + ' ready-to-use presets covering the most common use cases. Pick one and customize links, icons, descriptions and colors to match your brand.</p>'
            + '</div>'
            // Grid
            + '<div style="padding:20px 24px;display:grid;grid-template-columns:repeat(4,1fr);gap:16px;overflow-y:auto;flex:1;">'
            + cards
            + '</div>'
            + '<div style="padding:12px 24px;border-top:1px solid #f0f0f0;background:#fafafa;text-align:right;">'
            + '<button type="button" onclick="mxMegaDemoClose()" style="background:#fff;border:1px solid #d1d5db;color:#374151;padding:7px 20px;border-radius:8px;font-size:13px;cursor:pointer;">Close</button>'
            + '</div>'
            + '</div>';

        document.body.appendChild(wrap);
        return wrap;
    }

    /* ================================================================
       HELP MODAL
       ================================================================ */

    window.menuxHelpOpen = function() {
        var modal = document.getElementById('menux-help-modal');
        if (!modal) return;
        var section = window._menuxActiveSection || 'structure';
        menuxHelpGoSection(section);
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    };

    window.menuxHelpClose = function() {
        var modal = document.getElementById('menux-help-modal');
        if (modal) modal.style.display = 'none';
        document.body.style.overflow = '';
    };

    window.menuxHelpGoSection = function(key) {
        document.querySelectorAll('.menux-help-section').forEach(function(el) { el.style.display = 'none'; });
        document.querySelectorAll('.menux-help-nav-btn').forEach(function(btn) { btn.classList.remove('active'); });
        var sec = document.getElementById('menux-help-sec-' + key);
        if (sec) sec.style.display = 'block';
        var btn = document.querySelector('.menux-help-nav-btn[data-help-section="' + key + '"]');
        if (btn) btn.classList.add('active');
        var content = document.getElementById('menux-help-content');
        if (content) content.scrollTop = 0;
    };

    document.addEventListener('click', function(e) {
        var modal = document.getElementById('menux-help-modal');
        if (modal && e.target === modal) menuxHelpClose();
    });

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            var modal = document.getElementById('menux-help-modal');
            if (modal && modal.style.display !== 'none') menuxHelpClose();
        }
    });


